LoginSignup
0
0

More than 5 years have passed since last update.

シェルスクリプトでtry~exceptやbegin~rescue~endっぽいことをする

Posted at

シェルスクリプトはデフォルトだとひとつのコマンドがエラーになってもそのまま実行を続けるというRubyやPythonで育った人には信じられない仕様なのですが、set -eをつけるとRubyやPythonのようにエラーが発生(コマンドの終了ステータスが0以外だった場合)した時点でスクリプトの実行が終了します。

ifの条件式として実行するとset -eの影響を受けなくなるので、Rubyのbegin~rescue~endやPythonのtry~except相当のことができます。

#!/bin/sh

set -eu    # このサンプルだと -e だけでよいが習慣として set -eu してる

## 当然ここで停止する
#ssh aaaaaaaaaaaaa

## サブシェルで実行してもコマンドの終了ステータスがサブシェルの
## 終了ステータスになるのでやっぱりここで止まる
#(ssh aaaaaaaaaaaaa)

## ブロックで括っても同様に止まる
#{
#  ssh aaaaaaaaaaaaa
#}

# ifの条件式として実行すると終了ステータスをもとに制御ができる
if ! ssh impossible_server_abcdefghijklmnopqrstu; then
  echo "ssh error"  # エラーだった場合実行する処理
fi

echo "end of script"

これでいいのかな・・・?

0
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
0
0