LoginSignup
21
13

More than 5 years have passed since last update.

コマンドが「失敗した時」に別のコマンドを実行する方法

Posted at

コマンド hoge の終了ステータスが成功した場合に別のコマンド piyo を実行したい場合、

success.sh
if hoge; then
    piyo
fi

と書く。逆に hoge が失敗だった場合だけpiyoを実行した場合どうするか。

|| を使う。

そのものずばりの機能があって、

pipepipe.sh
hoge || piyo

と書けば、hogeが失敗した場合だけpiyoが実行される。||の代わりに&&を使えば、hogeが成功した場合だけpiyoが実行される。

@nise_nabe さん、ありがとうございました。

! を使う。

!というコマンドがあって、こいつは、

bikkuri.sh
! hoge

とすると、まずhogeが実行されて、hogeの終了ステータスが0だったら1を、0以外だったら0を終了ステータスとして返してくれる。
なので、

bikkuriif.sh
if ! hoge; then
    piyo
fi

と書けば、hogeが失敗した場合だけpiyoが実行される。

@leihcrev さん、ありがとうございました。

21
13
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
21
13