1. 程式人生 > >Linux 下的 shell 程式設計之 if-else選擇結構

Linux 下的 shell 程式設計之 if-else選擇結構

 Linux 中 shell 中if else 的使用方式比較簡單,. 相關的關鍵字有: if, elif , else, fi, 等.

  1. if 的判斷表示式是 []

  2. if 的範圍確定不是依靠 {} ,而是if  fi

一 if-else 常用結構

    1. if - else 結構

# 第一種寫法: 需要寫, 要注意縮排
if [ 條件判斷表示式 ] ; then
    程式塊兒
else 
    程式塊兒
fi

# 第二中寫法: 不需要寫, 要注意縮排
if [ 條件判斷表示式 ]
 then
   程式塊兒
else 
   程式塊兒
fi


    2. if - elif - else 結構:

# 第一種寫法: 需要寫, 要注意縮排
if [ 條件判斷表示式 ] ; then
    程式塊兒
elif [ 條件表示式 ] ; then
    程式塊兒
else 
    程式塊兒
fi

# 第二中寫法: 不需要寫, 要注意縮排
if [ 條件判斷表示式 ]
 then
   程式塊兒
elif [ 條件表示式 ]
   then
   程式塊兒
else 
   程式塊兒
fi

二  if 常用舉例

    1. 判斷分割槽佔用率是否超過80%

#!/bin/bash
#Desc	統計跟分割槽使用率
#Auth	zonggf
#Date	2016-07-02 10:39:13

#獲取分割槽使用率
rate=$(df -h | grep "/dev/sda5" | awk '{print $5}' | cut -d "%" -f1)

#如果分割槽使用率超過80%,提示警告資訊
if [ $rate -gt 80 ] 
  then
    echo Warning! The boot is nearly full! It is already $rate% !    
  else
    echo The boot area is safe! It is $rate%
fi

    2. 測試if -elif -else

#!/bin/bash
#Desc	for test if-else-if
#Auth	zonggf
#Date	2016-07-02 11:21:01

read -p "請輸入一個數字:" num

if [ $num -eq 20 ] ; then
  echo "$num > 20"
elif [ $num -eq 100 ] ; then
  echo "$num > 100"
else
  echo "$num < 20"
fi