LoginSignup
9
3

More than 5 years have passed since last update.

Macのxargsの-Iオプションに潜む罠

Posted at

どういう罠か、とりあえず実例を示します。

$ echo "64byte string.**************************************************" | xargs -I% echo %%%%
64byte string.**************************************************64byte string.**************************************************64byte string.**************************************************%

最後の%が64byte string***に展開されてません。これはxargsで-Iオプションを使うと引数にとるパイプから受け取った文字列を展開したコマンドが、256byte以上になることを許さないからです(日本語むずかしい)

manの-Iオプションの項目に記述されています。

XARGS(1)                  BSD General Commands Manual                 XARGS(1)

NAME
     xargs -- construct argument list(s) and execute utility

SYNOPSIS
     xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr] [-L number] [-n number [-x]] [-P maxprocs] [-s size] [utility [argument ...]]

...

-I replstr
    Execute utility for each input line, replacing one or more occurrences of replstr in up to replacements (or 5 if no -R flag is specified) arguments to utility with the entire line of input.  The resulting arguments, after replacement is done, will not be allowed to grow beyond 255 bytes; this is implemented by concatenating as much of the argument containing replstr as possible, to the constructed arguments to utility, up to 255 bytes.  The 255 byte limit does not apply to arguments to utility which do not contain replstr, and furthermore, no replacement will be done on utility itself.  Implies -x.

そもそも-I replstrオプションはreplstrで指定した文字列を(SYNOPSISの)utility節に記述するとpipeから受け取った文字列をそこに展開する、というものです。で、今回このエントリで言ってることは The resulting arguments, after replacement is done, will not be allowed to grow beyond 255 bytes; という部分です。要は-Iオプション使ってやたら長いコマンド(or pipeからやたら長い文字列を受け取るコマンド)を記述したらpipeから受け取った文字列が展開されないよ、という話です。

ちなみにLinux(debian6)のxargsのmanを見たところこの制限の記述はなく、実際試してみても展開されました。

-I replace-str
    Replace occurrences of replace-str in the initial-arguments with names read from standard input.  Also, unquoted blanks do not terminate input items; instead  the  separator  is  the newline character.  Implies -x and -L 1.
$ echo "64byte string.**************************************************" | xargs -I% echo %%%%
64byte string.**************************************************64byte string.**************************************************64byte string.**************************************************64byte string.**************************************************
9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3