Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

28
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Bash の戻り値判定を様々なパターンで記述する

Last updated at Posted at 2019-02-03

概要

関数やコマンドの戻り値を判定して、条件分岐させたいときにいくつか書き方が考えられるのでまとめてみる。

1. $? を使った典型的な if-then

hogehoge
if [ $? -ne 0 ]; then
  # エラー処理
fi
  • 直感的でわかりやすい
  • ちょっと冗長
  • set -e しているときに hogehoge が失敗すると、エラー処理までたどり着かない

2. $? を使わずに if-then

if ! hogehoge; then
  # エラー処理
fi
    1. よりも 1 行削れる
  • その分直感的に欠ける?

3. if を使わずに OR 演算子で判定

hogehoge || {
  # エラー処理
}
  • || は左辺のコマンドが異常終了 (戻り値が 0 以外) した際に右辺を評価する。波括弧 { } でくくることで評価の対象を複数行で書くことができる
  • 見た目が無名関数っぽくてかっこいい
  • でも慣れていない人にとっては読み辛いかも

まとめ

多少の冗長性は犠牲にしてでも、慣れ親しんだ・読みやすい記法に倒したほうが (特に Bash においては) バグを生みにくいのではないかと個人的には感じる。

28
15
4

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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
28
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?