logo

Bash スクリプト – Else If ステートメント

この記事では、Else If ステートメントの bash スクリプトを作成する方法について説明します。

二分探索木からの削除

条件文 : 特定の条件に基づいて特定の機能を実行するステートメントは、条件ステートメントと呼ばれます。 bash スクリプトには、IF、IF-ELSE、IF-ELSE-IF などの条件ステートメントがいくつかあります。各ステートメントには独自の動作方法があり、必要に応じてそれらを使用します。



IF ステートメント

このステートメントは、条件だけをチェックする必要がある場合に使用されます。条件が true であると判明した場合、if ブロック内に記述されたステートメントが実行されます。

構文:

if (condition) then statement fi>

コード:



if [ 15 -gt 10 ] then # If variable less than 10 echo 'a is greater than 10' fi>

このプログラムは、15 が 10 より大きいかどうかの条件をチェックします。 15 が 10 より大きい場合、IF ブロック内に書かれたステートメントが画面に表示されます。

出力:

a is greater than 10>



IF-ELSE ステートメント

If ステートメントに見られるように、条件が true の場合、IF ステートメント ブロックは実行されますが、条件が false の場合は何も返されず、実行もされません。 IF ステートメントの条件が false になった後でプログラムに特定のアクションを実行させたい場合は、If ステートメントの後に ELSE ステートメントを使用します。

構文:

if [condition ] then If statement else ELSE statement fi>
  • 条件が true の場合: IF ステートメントが実行されます。
  • 条件が false の場合: ELSE ステートメントが実行されます。

コード:

if [ 5 -gt 10 ] then # If variable less than 10 echo 'number is greater than 10' else echo 'number is less than 10' fi>

出力:

number is less than 10>

ELIF (ELSE IF) ステートメント

ELIF は、bash スクリプトの ELSE IF ステートメントに使用されるキーワードです。ループ内に IF-ELSE ステートメントだけでは解決できない条件が 3 つ以上存在する場合は、ELIF が使用されます。 1 つの if-else ループ内で複数の ELIF 条件を定義できます。

パワーシェル管理者

ELIF 構文:

if [ condition1 ] then statement1 elif [ condition2 ] then statement2 elif [condition3 ] then statement3 else statement_n fi>

コード:

#!/bin/bash # Initializing the variable a=20 if [ $a <10 ] then # If variable less than 10 echo 'a is less than 10' elif [ $a < 25 ] then # If variable less than 25 echo 'a is less than 25' else # If variable is greater than 25 echo 'a is greater than 25' fi>

出力:

postgresqlで列を削除する方法
a is greater than 25>

NESTED ステートメント

別のステートメント内に 1 つまたは複数の条件ステートメントが記述されている場合、これは、別の IF ステートメント内の IF ステートメントのように、ネストされたステートメントと呼ばれます。

構文 (入れ子になった IF):

If [condition] then if [condition_2] then statement_1 fi fi>

例:

#!/bin/bash #Initializing the variable if [ 12 -gt 10 ] then if [ 12 -gt 15] then echo 'number is greater than 15' else echo 'number is less than 15' fi fi>

出力:

number is less than 15>