🖥

Bash | if の中に書くアレを単体で書くと終了コードが変わる

2023/08/26に公開

検証

条件式だけを単体で書き、その後の終了コードの変化を見てみる。

exit_code.sh
echo exit code is $? at first

[[ 'A' == 'A' ]]

echo exit code is $? after matched

[[ 'A' == 'B' ]]

echo exit code is $? after not matched

結果

マッチに失敗した後の終了コードが、エラーを示す 1 に変わっているのが分かる。

exit_code.sh
$ bash exit_code.sh

exit code is 0 at first
exit code is 0 after matched
exit code is 1 after not matched

コード的解決策

「if 文を書きたくない、&& でつなげて簡潔に書きたい」という場合は、最後に || true を入れてあげれば良さそう。

i_want_simple_syntax.sh
[[ $WORD == 'A' ]] && echo 'WORD is A' || true
[[ $WORD == 'B' ]] && echo 'WORD is B' || true

echo exit code is $?

結果

$ WORD=A bash i_want_simple_syntax.sh

WORD is A
exit code is 0

if 文の中での検証

では、 if 文の中ではどうなるのだろう。

exit_code_in_if.sh
echo exit code is $? at first

if [[ 'A' == 'A' ]]
then
  echo exit code is $? in matched if 
fi

echo exit code is $? after matched if

if [[ 'A' == 'B' ]]
then
  echo a is b
else
  echo exit code is $? in not matched else
fi

echo exit code is $? after not matched if

結果

この場合は「マッチしなかった判定の else の中」でだけ、終了コードが変わっているのが分かる。

どうやら if は終了コードの変化を「閉じ込めて」くれるらしい。
というより、その仕組を利用したのが、そもそも if / then / else なのかも。

$ exit_code_in_if.sh

exit code is 0 at first
exit code is 0 in matched if
exit code is 0 after matched if
exit code is 1 in not matched else
exit code is 0 after not matched if

環境

  • bash 3.2

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2016-07-22

Discussion