使用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 it's not a pipeline, I don't prefer it. Is there another solution?
推荐答案
cat a.txt | xargs -d $'\n' sh -c 'for arg do command1 "$arg"; command2 "$arg"; ...; done' _
...或者没有对猫的无用使用:
<a.txt xargs -d $'\n' 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 $'\n'
是GNU扩展,这导致xargs
将输入文件的每一行都视为单独的数据项.要防止xargs尝试对读取的流进行类似shell的解析(但 不太兼容),则必须使用this或-0
(期望使用NUL而不是换行符). (如果没有GNU xargs,则可以使用tr '\n' '\0' <a.txt | xargs -0 ...
而不使用-d
来获得面向行的读取).
Similarly, the use of -d $'\n'
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 '\n' '\0' <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屋!