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

if [ 判斷條件 ]
then
command1
...
fi
if [ 條件 ]
then
...
else
...
fi
if [ 條件1 ]
then
...
elif [ 條件2 ]
then
...
else
...
fi
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)。