使用 xargs 运行多个命令 [英] Running multiple commands with xargs
问题描述
cat a.txt | xargs -I % echo %
在上面的例子中,xargs 将 echo %
作为命令参数.但在某些情况下,我需要多个命令来处理参数而不是一个.例如:
In the example above, xargs takes echo %
as the command argument. But in some cases, I need multiple commands to process the argument instead of one. For example:
cat a.txt | xargs -I % {command1; command2; ... }
但是 xargs 不接受这种形式.我知道的一个解决方案是我可以定义一个函数来包装命令,但我想避免这种情况,因为它很复杂.有没有更好的解决方案?
But xargs doesn't accept this form. One solution I know is that I can define a function to wrap the commands, but I want to avoid that because it is complex. Is there a better solution?
推荐答案
cat a.txt | xargs -d $'
' sh -c 'for arg do command1 "$arg"; command2 "$arg"; ...; done' _
...或者,如果没有无用的猫:
...or, without a Useless Use Of cat:
<a.txt xargs -d $'
' sh -c 'for arg do command1 "$arg"; command2 "$arg"; ...; done' _
<小时>
解释一些细节:
To explain some of the finer points:
使用
"$arg"
而不是%
(以及xargs 中没有
-I
命令行)是出于安全原因:在sh
的命令行参数列表上传递数据而不是将其替换为代码可防止数据可能包含的内容(例如$(rm -rf ~)
,举一个特别恶意的例子)不被作为代码执行.
The use of
"$arg"
instead of%
(and the absence of-I
in thexargs
command line) is for security reasons: Passing data onsh
's command-line argument list instead of substituting it into code prevents content that data might contain (such as$(rm -rf ~)
, to take a particularly malicious example) from being executed as code.
同样,-d $'
'
的使用是一个 GNU 扩展,它导致 xargs
将输入文件的每一行视为一个单独的数据项.这个或 -0
(它需要 NULs 而不是换行符)是必要的,以防止 xargs 尝试将类似 shell(但不完全 shell 兼容)的解析应用到流它读取.(如果你没有 GNU xargs,你可以使用 tr '
' ' ' <a.txt | xargs -0 ...
获得面向行的阅读,无需 -d
).
Similarly, the use of -d $'
'
is a GNU extension which causes xargs
to treat each line of the input file as a separate data item. Either this or -0
(which expects NULs instead of newlines) is necessary to prevent xargs from trying to apply shell-like (but not quite shell-compatible) parsing to the stream it reads. (If you don't have GNU xargs, you can use tr '
' ' ' <a.txt | xargs -0 ...
to get line-oriented reading without -d
).
_
是 $0
的占位符,这样 xargs
添加的其他数据值变成 $1
及以后,这恰好是 for
循环迭代的默认值集.
The _
is a placeholder for $0
, such that other data values added by xargs
become $1
and onward, which happens to be the default set of values a for
loop iterates over.
这篇关于使用 xargs 运行多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!