条件文: bash プログラミングで使用できる条件文は合計 5 つあります。
- if ステートメント
- if-else ステートメント
- if..elif..else..fi ステートメント (Else If ラダー)
- if..then..else..if..then..fi..fi..(ネストされた if)
- switch ステートメント
構文を使用した説明は次のとおりです。
if ステートメント
このブロックは、指定された条件が true の場合に処理されます。
構文:
if [ expression ] then statement fi>
if-else ステートメント
if 部分で指定された条件が true でない場合、else 部分が実行されます。
構文
if [ expression ] then statement1 else statement2 fi>
if..elif..else..fi ステートメント (Else If ラダー)
1 つの if-else ブロックで複数の条件を使用するには、シェルで elif キーワードを使用します。式 1 が true の場合、ステートメント 1 と 2 が実行され、このプロセスが続行されます。どの条件も true でない場合は、else 部分が処理されます。
構文
if [ expression1 ] then statement1 statement2 . . elif [ expression2 ] then statement3 statement4 . . else statement5 fi>
if..then..else..if..then..fi..fi..(ネストされた if)
ネストされた if-else ブロックは、1 つの条件が満たされた後で別の条件を再度チェックする場合に使用できます。構文では、expression1 が false の場合、else 部分が処理され、再度、expression2 がチェックされます。
構文:
if [ expression1 ] then statement1 statement2 . else if [ expression2 ] then statement3 . fi fi>
switch ステートメント
case ステートメントは switch ステートメントとして機能し、指定された値がパターンと一致する場合、その特定のパターンのブロックを実行します。
一致が見つかると、2 つのセミコロン (;;) までの関連するすべてのステートメントが実行されます。
最後のコマンドが実行されると、ケースは終了します。
一致するものがない場合、ケースの終了ステータスは 0 になります。
構文:
case in Pattern 1) Statement 1;; Pattern n) Statement n;; esac>
プログラム例
例 1:
実装するif>声明
#Initializing two variables> a=10> b=20> > #Check whether they are equal> if> [>$a> ==>$b> ]> then> >echo> 'a is equal to b'> fi> > #Check whether they are not equal> if> [>$a> !=>$b> ]> then> >echo> 'a is not equal to b'> fi> |
>
>
出力
$bash -f main.sh a is not equal to b>
例 2:
実装するif.else>声明
#Initializing two variables> a=20> b=20> > if> [>$a> ==>$b> ]> then> >#If they are equal then>print> this> >echo> 'a is equal to b'> else> >#>else> print> this> >echo> 'a is not equal to b'> fi> |
>
>
出力
$bash -f main.sh a is equal to b>
例 3:
実装するswitch>声明
CARS=>'bmw'> > #Pass the variable in string> case> '$CARS'> in> >#>case> 1> >'mercedes'>)>echo> 'Headquarters - Affalterbach, Germany'> ;;> > >#>case> 2> >'audi'>)>echo> 'Headquarters - Ingolstadt, Germany'> ;;> > >#>case> 3> >'bmw'>)>echo> 'Headquarters - Chennai, Tamil Nadu, India'> ;;> esac> |
>
>
出力
$bash -f main.sh Headquarters - Chennai, Tamil Nadu, India.>
注記: シェル スクリプトは大文字と小文字を区別する言語であるため、スクリプトを記述する際には適切な構文に従う必要があります。
Javaでnullをチェックする