コマンドの終了ステータスあれこれ

bash: GNU Bourne-Again Shell

パイプで連結したコマンド文字列の終了ステータス

  • パイプで連結したコマンド文字列の終了ステータスは、最後に実行したコマンドの終了ステータスになる
  • パイプで連結したそれぞれの終了ステータスが知りたいときは予約変数の PIPESTATUS 配列を参照する
    • (配列の添え字は 0 から数える)
      • 1 番目なら ${PIPESTATUS[0]}
      • 2 番目なら ${PIPESTATUS[1]}
      • 3 番目なら ${PIPESTATUS[2]}
    • $? と同じく、次のコマンドを実行すると内容が消える
$ ls -l log.txt
ls: cannot access 'log.txt': No such file or directory
$ foo | tee log.txt
bash: foo: command not found
$ echo $?
0
$ ls -l log.txt
-rw-r--r-- 1 y.okazawa 1049089 0  8月  7 19:07 log.txt
$ foo | tee log.txt
bash: foo: command not found
$ echo ${PIPESTATUS[@]}
127 0

log.txt は存在しない。
foo は存在しないコマンドだからすぐに消えた。
foo を実行したプロセスの標準出力は空だから tee コマンドは何も受け取ることなく log.txt を作成するだけで終わる。
tee は正常終了したので終了ステータス $? は 0 になった。
ファイルサイズ 0 の log.txt が存在する。
PIPESTATUS は長さ 2 の配列変数で、foo の失敗による終了ステータス 127 と tee の成功による終了ステータス 0 が入ってる。
$ ls -l log.txt
ls: cannot access 'log.txt': No such file or directory
$ echo 'start' | foo | tee log.txt
bash: foo: command not found
$ echo $?
0
$ ls -l log.txt
-rw-r--r-- 1 y.okazawa 1049089 0  8月  7 19:07 log.txt
$ echo 'start' | foo | tee log.txt
$ echo ${PIPESTATUS[@]}
0 127 0

log.txt は存在しない。
echo コマンドの標準出力は foo に接続されるはずだけど foo はすぐに消えた。
foo を実行したプロセスの標準出力は空だから tee コマンドは何も受け取ることなく log.txt を作成するだけで終わる。
tee は正常終了したので終了ステータス $? は 0 になった。
ファイルサイズ 0 の log.txt が存在する。
PIPESTATUS は長さ 3 の配列変数で、echo の成功による 0 と foo の失敗による 127 と tee の成功による 0 が入ってる。
$ ls -l log.txt
ls: cannot access 'log.txt': No such file or directory
$ echo 'start' | tee log.txt | foo
bash: foo: command not found
$ echo $?
127
$ ls -l log.txt
-rw-r--r-- 1 y.okazawa 1049089 6  8月  7 19:12 log.txt
$ echo 'start' | tee log.txt | foo
$ echo ${PIPESTATUS[@]}
0 0 127

log.txt は存在しない。
echo コマンドの標準出力は tee コマンドの標準入力へ接続し、log.txt と標準出力へ書き込まれる。
tee コマンドの標準出力は foo に接続されるはずだけどfoo はすぐに消えた。
foo は存在しないコマンドだったので終了ステータス $? は 127 になった。
ファイルサイズ 6 byte (s t a r t \n) の log.txt が存在する。
PIPESTATUS は長さ 3 の配列変数で、echo の成功による 0 と tee の成功による 0 と foo の失敗による 127 が入ってる。

xargs の終了ステータス

xargs(1)

Exit Status

xargs exits with the following status:

0 if it succeeds 123 if any invocation of the command exited with status 1-125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred.

Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal.

  • 全部成功したら xargs の終了ステータスは 0
  • 終了ステータスが 1 から 125 のコマンドが 1 つでもあるなら xargs の終了ステータスは 123
  • 終了ステータスが 255 のコマンドが 1 つでもあるなら xargs の終了ステータスは 124
  • いずれかのコマンドがシグナルで停止したら xargs の終了ステータスは 125
  • いずれかのコマンドを実行できなかったら xargs の終了ステータスは 126
  • いずれかのコマンドが存在しなかったら xargs の終了ステータスは 127
  • それ以外の何かがあったら xargs の終了ステータスは 1

128 以上の終了ステータスはプログラムが致命的なシグナルにより停止したことを伝えるためシェルが使う。