我正在考虑 xargs 的一些细微差别。
阅读问题: ( xargs 中 -L 和 -n 有什么区别 ) 我感觉很烦。
当我使用多参数命令时
sh -c "..."
xargs 做错了(我认为):
MacOS、FreeBSD 和 Linux 中的错误或者我在这里遗漏的东西:
$ ls *.h | xargs -L 1 sh -c 'echo "$# -- $*"'
3 -- quick brown fox.h
我的期望与
相同$ ls *.h | xargs -L 1
the quick brown fox.h
但看起来,“sh -c '...'”吃掉了一个参数(`the')
有人知道为什么以及如何解决吗?
以下是 Debian 11 下
man sh
的说明:
dash -c (...) command_string [command_name [argument ...]]
-c Read commands from the command_string operand instead of
from the standard input. Special parameter 0 will be set
from the command_name operand and the positional parameters
($1, $2, etc.) set from the remaining argument operands.
这意味着如果执行
sh -c 'echo "blah"' the quick brown fox
,命令字符串后的第一个单词(即the
)将用于设置$0
(命令名称),其余单词将被分配给$1
, $2
和 $3
。
图示:
sh -c 'echo ">>> command name is \"$0\", I have $# arguments: $*"' the quick brown fox
>>> command name is "the", I have 3 arguments: quick brown fox
因此,要么在 xargs
调用中添加尾随
command_name参数:
echo 'the quick brown fox' | xargs -L 1 sh -c 'echo "$# -- $*"' CommandName
...或使用
sh -c
以外的其他命令。
希望有帮助。