シェルスクリプトにおける条件分岐
[履歴] [最終更新] (2018/05/29 00:52:30)
プログラミング/IoT の関連商品 (Amazonのアソシエイトとして、当メディアは適格販売により収入を得ています。)
最近の投稿
注目の記事

if-elif-else

C言語など、一般の言語と同様にif文による条件分岐が記述できます。elif ('else if'でも'elsif'でもない) であったり、then, fiと記述されるあたりなどが、Rubyとよく似ていますね (Rubyが取り入れたのでしょうか)。以下のサンプルでは、testというファイルのステータスを確認するコマンドを用いています。

sample.sh

#!/bin/sh

if test -r sample.sh
then
    echo 'sample.sh exists and can be read.'
elif test -f sample.sh; then  # 一行で記述するときはセミコロンが必須
    echo 'sample.sh exists'
else
    echo 'sample.sh does not exist'
fi


if [ -f sample.sh ]; then  # []はtestの略記法
    echo 1024
fi

実行例 (chmod +x sample.sh を忘れずに)

$ ./sample.sh
sample.sh exists and can be read.
1024

正規表現等を使う (bash 記法)

[[]] で囲むと正規表現等を使えます。

sample.bash

#!/bin/bash

if [[ "aaa" == *aa ]]; then
    echo "true"
else
    echo "false"
fi

if [[ "aaa" =~ [a-z]{3} ]]; then
    echo "true"
else
    echo "false"
fi

実行例

$ bash sample.bash
true
true

case

)の左の合致文字列では、ワイルドカードが使用できます。*)とすることで、C言語などのdefault相当の分岐ができます。

sample.sh

#!/bin/sh

VAR=xyz
case $VAR in
    XYZ) echo "VAR is XYZ" ;;
    xyz) echo "VAR is xyz" ;;
    *) echo "ELSE" ;;
esac

実行例

$ ./sample.sh
VAR is xyz
関連ページ
    ファイル内容を再帰的に検索 (grep) find コマンドはファイル名についてディレクトリを再帰的に検索します。ファイルの内容について指定したディレクトリ以下を再帰的に検索するためには grep に -r オプションを付与します。その際 -n および -i オプションも付与しておくと便利です。未来創発 NRI grep です。
    コマンドのエイリアスを登録する (update-alternatives) mybin という名前のコマンドを登録 sudo update-alternatives --install /usr/local/bin/mybin mybin /usr/bin/echo 10 sudo update-alternatives --install /usr/local/bin/mybin mybin