なんとなくで使ってしまっているxargs。
毎回勉強して覚えるんだけど抜けていくのでまとめます。
xargsとは
Man page of XARGS には以下のように書かれています。
xargs - 標準入力を読み込んでコマンドラインを作成し、それを実行する
tmp$ date | xargs echo Sat Aug 10 00:34:32 JST 2019
上の例はdateの結果をechoの引数として利用している。
※ちなみにdate | xargsと設定したときもechoが呼び出される(何もつけないとecho扱い)
また以下の例を試してみましょう。
test$ echo a a test$ echo a | echo b b test$ echo a | xargs echo b b a test$
これは通常通りですね。
test$ echo a a
これはecho aの結果(標準出力)をpipeで渡しているものの、echo bはそれをなんの利用もしないのでbしか表示されていません。
test$ echo a | echo b b
そして最後にこれ。xargsで受け取ったパターンです。xargsはpipe前のコマンドの標準出力を受け取りxargsの次のコマンドに引数として付与します。
そのためecho bの後ろにaがくっつくことになりecho b aというコマンドが発行されたことになります。
test$ echo a | xargs echo b b a
注意点
xargsの後ろにつけたコマンドはaliasが無効化される模様。
test$ ls total 0 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 file1 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 file2 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 file3 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 file4 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 file5 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 file6 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 file7 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 file8 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 file9 test$ test$ find . -type f | xargs ls ←aliasが効いていない ./file1 ./file2 ./file3 ./file4 ./file5 ./file6 ./file7 ./file8 ./file9 test$ find . -type f | xargs ls -l -rw-r--r-- 1 test wheel 0 Aug 10 00:38 ./file1 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 ./file2 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 ./file3 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 ./file4 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 ./file5 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 ./file6 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 ./file7 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 ./file8 -rw-r--r-- 1 test wheel 0 Aug 10 00:38 ./file9