シェル・プログラミング:6. if文
シェルは,単に,UNIX のコマンド処理ということだけではなく,プログラミング言語としての一面があると感じるのが,「if文」の存在です。
■if 文 ([ ] 部分はオプション)
if 条件
then
処理1
[elif 条件]
[then]
[処理2]
[else]
[処理3]
fi
次の例は,例2のスクリプトにおいて,スクリプトを実行する段階で変数が代入されなかったとき,相手に尋ねるものです。
#
# 例 11
#
#!/bin/sh
echo '# Example 11'
message=$*
if [ ! -s $message ]
then
echo -n 'Enter your message: '
read message
fi
echo "Your message to your boss was: $message"
実行例1) % sh script "I'm drinking!" # Example 11 Your message to your boss was: I'm drinking! % 実行例2) % sh script # Example 11 Enter your message: Getting fat? Your message to your boss was: Getting fat? %
この例において,[ ] 内の -s は条件判定用の演算子。[ ] は条件評価の命令。
test コマンド:[condition ], test condition[ ]内,また,testに続く条件conditionを評価する。真ならば0,偽ならば1を返す。- 条件演算子
・文字列評価 string1 = string2 両者が同じ string1 != string2 上の反対 ・数値評価 num1 -gt num2 num1 > num2 num1 -ge num2 num1 >= num2 num1 -eq num2 num1 = num2 num1 -le num2 num1 <= num2 num1 -lt num2 num1 < num2 num1 -ne num2 num1 not = num2 ・ファイル検査 -r file file 読み込み可 -w file file 書き込み可 -x file file 実行可 -e file file 存在 -s file file が空でない -d file file はディレクトリ -f file file は通常のファイル ・論理演算 ! condition 条件 condition の否定 cond1 -a cond2 cond1 AND cond2 cond1 -o cond2 cond1 OR cond2
- [ノート] 省略形:
&&と||・command1 && command2 これは以下と同じ。 if [command1] then command2 fi ・command1 || command2 これは以下と同じ。 if [!command1] then command2 fi