为什么 xargs 在传递给子 shell 时跳过第一个参数?

eli*_*ias 9 shell xargs

寻找一种在 xargs 单行中调用多个命令的方法,我在 findutils 中找到了从 xargs 调用 shell 的建议,如下所示:

$ find ... | xargs sh -c 'command $@'
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我像这样使用 xargs,出于某种原因,它会跳过第一个参数:

$ seq 10 | xargs bash -c 'echo $@'
2 3 4 5 6 7 8 9 10
$ seq 10 | xargs -n2 bash -c 'echo $@'
2
4
6
8
10
Run Code Online (Sandbox Code Playgroud)

我的 shell 或 xargs 版本有问题吗?那个文件不准确吗?

使用xargs (GNU findutils) 4.4.2GNU bash,版本 4.3.11(1)-release

Jan*_*nis 14

[bash] 手册页说:“-c string如果存在 -c 选项,则从字符串中读取命令。如果字符串后面有参数,则将它们分配给位置参数,从 $0 开始。 ” - 键为$0 ; 这意味着命令名称应为第一个参数。

seq 10 | xargs sh -c 'echo $@; echo $0' sh
1 2 3 4 5 6 7 8 9 10
sh
Run Code Online (Sandbox Code Playgroud)


Joh*_*024 11

为什么 xargs 在传递给子 shell 时跳过第一个参数?

它没有。Bash 将第一个参数分配给 $0:

$ seq 10 | xargs -n2 bash -c 'echo $0'
1
3
5
7
9
Run Code Online (Sandbox Code Playgroud)

$@扩展为$1 $2 $3.... 因此, 的值$0不包含在 中$@