LoginSignup
2
0

More than 3 years have passed since last update.

if文を抜けた後の$?

Posted at

問題

下のようなシェルスクリプトがあったとします。

iftest.sh
#!/bin/sh

if [[ $1 == "test" ]]; then
  echo "argument passed"
  #以下引数に"test"を渡した時に実行したい処理
  hogehoge
fi

exit $?

このスクリプトを引数を渡さずに実行したとします。

$ ./iftest.sh

さて、この時にこのスクリプトが返すexit codeは何でしょう?

  1. 最後に評価した[[ $1 == "test" ]]の結果を返す。引数を渡さずにスクリプトを実行したので、1を返す。
  2. 評価の結果に関わらず0を返す。

答え

正解は2番です。ここでこのシェルの振る舞いについて語られています。また、こちらにシェルの仕様が明記されています。

The exit status of the if command shall be the exit status of the then or else compound-list that was executed, or zero, if none was executed.

if文の条件がfalseとなりthenやelseに続くコマンドが実行されなかった場合、その直後のexit codeは0になるそうです。条件がtrueとなってthenやelseに続くコマンドが実行された場合は、そのコマンドのexit codeが返ります。

おわりに

このシェルの振る舞いを知らない人もいるかもしれないので、もしif文の条件がfalseの場合には必ず0を返したい場合、下のスクリプトの方がわかりやすいかもしれないですね。

iftest.sh
#!/bin/sh

typeset rc=0

if [[ $1 == "test" ]]; then
  echo "argument passed"
  #以下引数に"test"を渡した時に実行したい処理
  hogehoge
  rc=$?
fi

exit $rc
2
0
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
2
0