bashスクリプトでは、ifステートメントが条件が真であるかどうかをチェックします。その場合、シェルはifステートメントに関連付けられたコードのブロックを実行します。ステートメントが真でない場合、シェルはifステートメントブロックの終わりを超えてジャンプし、続行します。
このガイドでは、if、if、if..elif..else..fiステートメントの使用方法を学習します。 If-elseステートメントは、bashスクリプトでは条件付きステートメントとも呼ばれます。
ifステートメント
構文:
if [condition_command]
then
command1
command2
……..
last_command
fi
例:
以下のbashスクリプトの例では、ifcondiステートメントを使用して2つの数値を比較しています。
#!/bin/bash
number=150
if [ $number -eq 150 ]
then
echo "Number is 150"
fi if-elseステートメント
通常のifステートメントに加えて、elseブロックを使用してifステートメントを拡張できます。基本的な考え方は、ステートメントがtrueの場合、ifブロックを実行することです。ステートメントがfalseの場合、elseブロックを実行します。ここで、ブロックはコマンドのセットです。
構文:
if [condition_command]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
例:
#!/bin/bash
number=150
if [ $number -gt 250 ]
then
echo "Number is greater"
else
echo "Number is smaller"
fi If..elif..elseステートメント
bashスクリプトで、ifステートメントを使用して複数の条件を適用する場合は、「ifelifelse」を使用します。このタイプの条件ステートメントでは、最初の条件が満たされた場合、その下のコードが実行されます。それ以外の場合、条件がチェックされ、一致しない場合は、以下のelseステートメントが実行されます。構文と例を以下に示します。
構文:
if [condition_command]
then
command1
command2
……..
last_command
elif [condition_command2]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
例:
#!/bin/bash
number=150
if [ $number -gt 300 ]
then
echo "Number is greater"
elif [ $number -lt 300 ]
then
echo "Number is Smaller"
else
echo "Number is equal to actual value"
fi ネストされたifステートメント
ifステートメントとelseステートメントはbashスクリプトにネストできます。キーワード「fi」は、内側のifステートメントの終わりを示し、すべてのifステートメントはキーワード「fi」で終わる必要があります。
ネストされたifの基本構文を以下に示します:
if [condition_command]
then
command1
command2
……..
last_command
else
if [condition_command2]
then
command1
command2
……..
last_command
else
command1
command2
。 last_command
fi
fi
例:
#!/bin/bash
number=150
if [ $number -eq 150 ]
then
echo "Number is 150"
else
if [ $number -gt 150 ]
then
echo "Number is greater"
else
echo "'Number is smaller"
fi
fi