萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux Shell 腳本中 if 條件判斷完整語法與範例

Bourne Shell 的 if 語句用於條件判斷,支援單層、if-else、elif 多重條件與巢狀結構,掌握語法可撰寫健壯的自動化腳本。

基本語法

if [ 判斷條件 ]
then
  command1
  ...
fi

if-else

if [ 條件 ]
then
  ...
else
  ...
fi

if-elif-else

if [ 條件1 ]
then
  ...
elif [ 條件2 ]
then
  ...
else
  ...
fi

巢狀 if

if [ 條件1 ]
then
  ...
else
  if [ 條件2 ]
  then
    ...
  else
    ...
  fi
fi

實戰範例

#!/bin/bash
number=150
if [ $number -eq 150 ]; then
  echo "Number is 150"
fi

if [ $number -gt 250 ]; then
  echo "Number is greater"
else
  echo "Number is smaller"
fi

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

注意:[ ] 內兩側需有空格;數值比較用 -eq/-ne/-gt/-lt/-ge/-le;字串比較用 =/!=;邏輯運算用 -a(AND)/-o(OR)。

copyright © 萬盛學電腦網 all rights reserved