home wiki.fukuchiharuki.me
Menu

キーワード

  • exit
  • &&
  • ||

関連

概要

実行結果を利用して正常系や異常系に対処します。

実行結果を表現する方法

正常終了する

  • sample.sh
    # 正常終了
    exit 0

異常終了する

  • sample.sh
    # 異常終了
    exit 1

コマンドの実行結果をシェルスクリプトの実行結果にする

exit がなければ最後に実行したコマンドの実行結果がそのシェルスクリプトの実行結果になります。

正常終了の例

  • sample.sh
    # コマンド rm を実行
    rm sample.sh

次の実行結果を得ます。

$ ./sample.sh
$ echo $?
0
$

異常終了の例

  • sample.sh
    # コマンド rm を実行
    rm sample2.sh

次の実行結果を得ます。

$ ./sample.sh
rm: cannot remove `sample2.sh': そのようなファイルやディレクトリはありません
$ echo $?
1
$

実行結果を利用する方法

正常終了のとき次の処理を続ける

sample.sh が正常終了のとき next.sh を続けるには次のようにします。

$ ./sample.sh && ./next.sh

異常終了のとき次の処理を続ける

sample.sh が異常終了のとき exception.sh を続けるには次のようにします。

$ ./sample.sh || exception.sh

正常終了と異常終了で続ける処理を振り分ける

&& と || を連ねて書くと振り分ける動作をします。

正常終了の例

  • sample.sh
    echo sample
    exit 0
  • next.sh
    echo next
  • exception.sh
    echo exception

次の実行結果を得ます。

$ ./sample.sh && ./next.sh || ./exception.sh
sample
next
$

異常終了の例

  • sample.sh
    echo sample
    exit 1
  • next.sh
    echo next
  • exception.sh
    echo exception

次の実行結果を得ます。

$ ./sample.sh && ./next.sh || ./exception.sh
sample
exception
$

参考