0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シェルスクリプトのif文の書き方

Posted at

シェルスクリプトに限らず条件分岐(if文)の書き方ってすぐ忘れるのでメモです。

A. if文の基本形

コマンド1, コマンド2の実行結果(True ,False)によって、
処理1, 処理2, 処理3を実行します。

if コマンド1; then
    処理1
elif コマンド2; then
    処理2
else
    処理3
fi

例)pythonコマンドの有無の判定

if which python; then
    PYTHON=python
elif which python3; then
    PYTHON=python3
else
    exit
fi

B. if文の省略形(ワンライナー的書き方)

敷居は高いですが、慣れてくると余計な文言が減って逆に読みやすいと思います。

省略形 if文 意味
コマンド1 && コマンド2 if コマンド1; then コマンド2 fi 1を実行してTrueなら2も実行
コマンド1 || コマンド2 if ! コマンド1; then コマンド2 fi 1を実行してFalseなら2を実行
コマンド1; コマンド2 コマンド1
コマンド2
1を実行して、結果によらず2を実行
コマンド1 && コマンド2 || コマンド3 if コマンド1; then コマンド2; else コマンド3 fi 1を実行してTrueなら2を実行、Falseなら3を実行

例)pythonコマンドの判定

which python && PYTHON=python || which python3 && PYTHON=python3 || exit

C. if文 + [コマンド(=testコマンド)

if文のコマンド部分ですが、実際には[がよく使われます。

if [ 条件式1 ]; then
    処理1
elif [ 条件式2 ]; then
    処理2
else
    処理3
fi

[はコマンド(lsとかechoとかと同類)ですので、前後にスペースが必須です。
[コマンドの詳細(条件式部分)は本稿では省略です。

例).bashrc.localファイルが存在したら読み込む

if [ -f "$HOME/.bashrc.local" ]; then
    source "$HOME/.bashrc.local"`
fi

D. if文 + [の省略形

if文の省略形に[コマンドを適用したパターンです。この形式がよくでてきます。

省略形 if文
[ 条件式 ] && コマンド if [ 条件式 ]; then コマンド fi
[ 条件式 ] || コマンド if ! [ 条件式 ]; then コマンド fi

例).bashrc.localファイルが存在したら読み込む

[ -f "$HOME/.bashrc.local" ] && . "$HOME/.bashrc.local"`

.sourceコマンドの省略形
※こういった処理が何個も並んでいる場合、
 ifとかthenとかfiとかがあると逆に可読性が下がります。(個人の感想です)

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?