5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

シェルスクリプトでxargsを使って関数に引数を渡したい

Last updated at Posted at 2020-04-21

シェルスクリプトで複数並列で実行したいときに、xargs-Pオプションを使えることを知りました。
xargsから-Pでプロセス数を指定すれば複雑な処理も並列でできるじゃん!と思いましたが、なかなかできずに詰まりました。

シェルで並列実行したいはずが、気づけばxargsで関数に引数を渡したい人になっておりました笑
結論から言うと、以下で実現できました。

export -f function
${ARRAY} | xargs -n 1 -I{} bash -c "function {}"

具体的なシェルスクリプトだと、以下のようです。

#!/bin/bash

function randomWait() {
  TARGET=$1
  sec=`expr $RANDOM % 10`
  sleep $sec
  echo ${TARGET}
}

export -f randomWait
cat hogehoge.txt | xargs -n 1 -I{} -P 10 bash -c "randomWait {}"

例えば、hogehoge.txtに1-20までの数字をいれておくと、ランダムな順番で出力されます。

xargsのオプション
-nで一度に渡す引数の数を指定します。今回の関数は引数をひとつとるので、1を指定しています。
-Iで置換文字列を指定しています。{}を指定して、randomWaitに引数を渡すようにしています。
-Pで並行実行プロセス数を指定しています。

exportのオプション
-fでシェル変数としてexportしています。これでコマンドとして認識されます。

bashのオプション
-cで後に指定する文字列をコマンドを引数つきで実行してくれます。

参考

https://qiita.com/D-3/items/8bdb834ff53256cef481
http://171rr.blog.fc2.com/blog-entry-14.html

5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?