gpt4 book ai didi

unix - 了解UNIX命令xargs

转载 作者:行者123 更新时间:2023-12-03 09:40:19 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com