【问题标题】:Glob matching only returning first match全局匹配只返回第一个匹配
【发布时间】:2018-06-25 19:22:29
【问题描述】:

我正在编写一种自定义的rm 脚本,我想将通配符匹配传递给它。我在工作目录中有几个文件与我传递给脚本的通配符匹配,但我只从一个简单的测试用例中得到其中一个:

sh remove r*

remove 脚本中,我将其缩减为仅

echo $1

目录内容如下:

$ ls
file2  file4          newTestFile  remove_engine  restore
file3  fileName_1234  remove       remove_w       restore_engine

这就是我得到的结果。

$ sh remove r*
remove

我知道 BASH 甚至在脚本执行之前就扩展了通配符。但是为什么我没有得到与f* 匹配的目录中的所有文件?

【问题讨论】:

  • $1 是第一个匹配项。 $2 是第二个。 "$@" 都是他们
  • 请注意,根本问题与通配无关。您可以使用sh remove foo bar 重现相同的问题

标签: bash shell unix command-line parameters


【解决方案1】:

路径名扩展,又称通配符,将单个 shell 单词扩展为多个。你的情况

./remove r*

和跑步完全一样

./remove remove remove_engine restore remove remove_w restore_engine

正如您所发现的,$1 将是 remove,因为这是第一个参数。其余文件是单独的位置参数,所以$2 将是remove_engine$3 将是restore

要处理所有参数,您可以在循环中使用"$@"

for file in "$@"
do
  printf 'One of the matches was: %s\n' "$file"
done

或者直接在也接受多个参数的命令中:

# Delete all matches
echo rm "$@"

【讨论】:

    猜你喜欢
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多