unix - 了解UNIX命令xargs

标签 unix xargs

我对此很困惑。需要一些澄清。

示例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/

相关文章:

C Linux编程-管道使子进程退出

c++ - Unix系统上C++中的简单glob?

linux - 在 linux shell 中将我的输入文本转换为输出的最佳方法是什么

linux - 仅显示目录,不显示其内容 `find -type d | xargs ls`

linux - 喂入 pv 并写入日志文件不起作用

linux - 多个进度条

linux - Shell 脚本钻石

linux - 如何将别名命令与 xargs 一起使用?

bash - xargs jar tvf - 不起作用

c - 参数列表太长。构建 Hubbub HTML 解析库。执行