LoginSignup
3
6

More than 5 years have passed since last update.

bash の set -eu と wait と subprocess についてのメモ

Posted at

bash で set -eu としておくと、エラーが発生した時にそこで終了してくれるので便利なんですが (参考)、
& つけて background 処理した時にエラー検知できなくてはまったのでメモ

#!/bin/bash

exec 2>&1
set -eux

./sleep3_error.sh  & # sleep 3 して exit 1 するスクリプト

wait

echo "OK"

これを実行すると、正常終了してしまう。

$ sh 1.sh ; echo $?
+ wait
+ ./sleep3_error.sh


+ echo OK
OK
0

これを、下記のように、pid 指定でwait しておくとエラー検知できる。

#!/bin/bash

exec 2>&1
set -eux

./sleep3_error.sh  & # sleep 3 して exit 1 するスクリプト
pid1=$!

wait $pid1

echo "OK"

実行結果

$ sh 2.sh ; echo $?
+ pid1=83798
+ wait 83798
+ ./sleep3_error.sh
1

ちゃんとエラー(1)で終わってる。

複数の処理を & で実行して、すべて正常終了したら、次の処理、みたいなのやろうとしたとき、wait しか書かないと、エラー起きてても次に進んでしまうので注意。

なんでこうなってんだろ。

参考: bash - 複数のバックグラウンド処理の終了判定! - mk-mode BLOG

3
6
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
3
6