Xargs

如何指定 xargs 一次執行帶有所有參數的命令?

  • November 23, 2018

xargs有一個選項-n用於指定每次執行的命令的最大參數數。

有沒有辦法指定xargs應該始終同時執行所有提供的參數的任何命令?(就像在沒有 的情況下直接執行帶有所有參數的命令一樣xargs,我並不是試圖避免由於系統對命令行長度的限製而導致的失敗)

以下不是我的問題。請忽略它,如果它分散你的注意力。 我不想使用命令替換,因為它會刪除NUL和尾隨換行符,所以我正在考慮將其xargs用作替代方案。但我不想xargs將 args 分組進行多次執行,因為使用不同參數子集的多次執行的結果可能與使用所有參數的單次執行的結果不同,具體取決於 xargs 執行的命令。所以我想告訴你xargs總是一次執行所有的論點。

我仍然不確定我是否理解您所追求的,但是將-x選項(“如果命令行不適合則退出”)與-n設置為巨大值(大於系統限制)的選項結合起來應該:

a) 確保xargs只執行一次,無論有多少參數給它

b) 如果參數由於作業系統或 xargs-internal 限製而無法放入單個命令中,則會出錯。

例子:

$ seq 1 10000 | xargs -n 100000000 -x sh -c 'echo "$#"' sh
10000
$ seq 1 100000 | xargs -n 100000000 -x sh -c 'echo "$#"' sh
xargs: argument list too long

不幸的是,這不適用於 BSD 或 solaris 的 xargs。在 *BSD 上,該-x選項將導致xargs使用單個參數執行其命令,而不是退出:

fz11_2$ jot 10000 1 | xargs -n 10000 -x sh -c 'echo $#' sh | head -3
1
1
1
xargs: sh: terminated with signal 13; aborting

只有一些可笑-s的小論據會導致-x觸發:

fz11_2$ jot 10000 1 | xargs -s 19 -n 10000 -x sh -c 'echo $#' sh | head -3
xargs: insufficient space for arguments

標準似乎與 GNU xargs 行為相匹配:

-n  number
      Invoke utility using as many standard input arguments as
      possible, up to number (a positive decimal integer) arguments
      maximum. Fewer arguments shall be used if:
      + The command line length accumulated exceeds the size specified
        by the -s option (or {LINE_MAX} if there is no -s option).
      + The last iteration has fewer than number, but not zero,
        operands remaining.
-x
      Terminate if a constructed command line will not fit in the
      implied or specified size (see the -s option above).

引用自:https://unix.stackexchange.com/questions/483672