我对此很困惑。需要一些澄清。
示例1:
pgrep string | xargs ps
示例2:
find . | xargs grep whatever
从示例1中,我收集到的是这种方式:
搜索作为正在运行的进程名称的一部分的“字符串”,并将所有匹配项的进程标识返回到“xargs ps”->,后者仅将ps附加到匹配项(它们本身就是进程标识)以得到相同的结果输出为:
ps <processid>
有人可以解释在这种情况下xargs实际做什么吗?
从示例2中,我收集到的是这种方式:
它从当前工作目录中递归搜索一些“字符串”。
在这里,“xargs”究竟如何工作?
我认为'xargs'反复将标准输入的数据附加到给xargs的'argument'(通常本身就是UNIX命令)。
从xargs()手册页:
xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored.
最佳答案
通常, xargs 像这样使用
prog | xargs utility
其中
prog
预期会输出一个或多个换行符/空格分隔的结果。诀窍是xargs
不必为每个结果调用一次utility
,而是将结果拆分为子列表,并为每个子列表调用utility
。如果要强制xargs为每个结果调用utility
,则需要使用xargs -L1
调用它。请注意,
xargs
向您保证发送给utility
的子列表比ARG_MAX
短(如果您很好奇,则可以使用ARG_MAX
获得getconf ARG_MAX
的当前值。)这是如何避免那些可怕的“参数列表长”错误的方法。
关于unix - 了解UNIX命令xargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1898044/