使用花括号参数列表多次执行命令

Har*_*rev 9 bash shell command-line command-line-arguments brace-expansion

当我需要使用不同的参数多次运行命令时,我使用了这种方法(完全不了解它):

touch {a,b,c}
Run Code Online (Sandbox Code Playgroud)

这相当于:

touch a
touch b
touch c
Run Code Online (Sandbox Code Playgroud)

我认为使用以下循环可以实现同样的目的:

for file in {a,b,c}; do touch $file; done
Run Code Online (Sandbox Code Playgroud)

但是,我偶然发现了一个不起作用的情况:

pear channel-discover {"pear.phpunit.de","pear.symfony-project.com"}
Run Code Online (Sandbox Code Playgroud)

我有几个问题:

  1. 第一个例子中发生的事情的名称是什么,到底发生了什么?
  2. 将此方法用于简单事物而不是for-in循环是否更好?
  3. 为什么pear命令不能那样工作?命令脚本应该实现一些处理这些参数的技术,还是shell负责呢?

Sha*_*hin 12

这称为Brace Expansion,它扩展为给定字符串的空格分隔列表.

所以touch {a,b,c}相当于

touch a b c
Run Code Online (Sandbox Code Playgroud)

虽然touch {a,b,c}x相当于:

touch ax bx cx
Run Code Online (Sandbox Code Playgroud)

您的pear命令基本上将运行为:

pear channel-discover pear.phpunit.de pear.symfony-project.com
Run Code Online (Sandbox Code Playgroud)

这可能不是你的预期.如果您希望为每个字符串运行一次命令,请使用for循环(它回答您的第二个问题),或使用大括号扩展和xargs的组合.


Jen*_*ens 6

问题是与你的期望相反,支撑扩张

touch {a,b,c}
Run Code Online (Sandbox Code Playgroud)

相当于

touch a b c   # NOT 3 separate invocations.
Run Code Online (Sandbox Code Playgroud)

(echo {a,b,c}用于验证).似乎pear channel-discover不接受两个 args.您可能会看到相同的错误

pear channel-discover pear.phpunit.de pear.symfony-project.com
Run Code Online (Sandbox Code Playgroud)