LoginSignup
128
128

More than 5 years have passed since last update.

シェルスクリプトでエラー時の処理を行う方法

Posted at

変数 $? を利用する方法

$?
直前に実行されたコマンドのステータス(終了フラグ)を表します。これを使って実行されたコマンドが正しく終了したかどうか判定します。

連載 シェルスクリプト・ステップ・バイ・ステップ 第5回 シェルの変数に慣れる

#!/bin/bash

function my_command() {
    # 処理
    return 1
}

my_command
if [ $? -gt 0 ]; then
    # エラー処理
fi

いままで上記のようにコマンドを実行した後の $? の値を見て分岐させていた。
機能としては十分なのだが、もっとスッキリした書き方がある。

OR演算子 || を利用する方法

コマンドの戻り値を直接利用する。論理積でコマンドを繋いでいく方法と同じやり方。

#!/bin/bash

function my_command() {
    # 処理
    return 1
}

function my_error() {
    # エラー処理
    exit 1
}

my_command || my_error

スタイリッシュだ。

参考リンク

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