if
條件選擇,選擇執(zhí)行,可嵌套
單分支
if 判斷條件;then
條件為真的分支代碼
fi
雙分支
if 判斷條件;then
條件為真的分支代碼
else
條件為假的分支代碼
fi
多分支
if 判斷條件1;then
條件為真的分支代碼
elif 判斷條件2;then
條件為真的分支代碼
elif 判斷條件3;then
條件為真的分支代碼
else
以上條件都為假的分支代碼
fi
逐條件進行判斷,第一次遇為“真”條件時,執(zhí)行其分支,而后結束整個if語句
例子:根據命令的退出狀態(tài)來執(zhí)行命令
if ping -c1 -W2 station1 &> /dev/null; then
echo 'Station1 is UP'
elif grep "station1" ~/maintenance.txt &> /dev/null then
echo 'Station1 is undergoing maintenance‘
else
echo 'Station1 is unexpectedly DOWN!' exit 1
fi
[root@centos SC]#vim age.sh
#!/bin/bash
######輸入一個數
read -p "please input your age: " age
######判斷輸入的值是否為數字,如有不是,提示輸入數字并退出
[[ ! "$age" =~ ^[[:digit:]]+$ ]] && echo please input digital && exit 100
######對輸入的數進行判斷,從而執(zhí)行相應命令
if [ "$age" -le 18 ];then
echo "you are baby"
elif [ "$age" -gt 18 -a "$age" -le 60 ];then
echo you need work hard
elif [ "$age" -le 80 ];then
echo "you can enjoy life"
else
echo "you will be lucky"
fi
~
~
~
~
~
~
~
~
~
~
~
"age.sh" 12L, 331C written
[root@centos SC]#chmod +x age.sh
######測試結果
[root@centos SC]#./age.sh
please input your age: 2
you are baby
[root@centos SC]#./age.sh
please input your age: 18
you are baby
[root@centos SC]#./age.sh
please input your age: 19
you need work hard
[root@centos SC]#./age.sh
please input your age: 65
you can enjoy life
[root@centos SC]#./age.sh
please input your age: 85
you will be lucky
case
case語句:條件判斷
case 變量引用 in
PATH1)
分支1
;;
PATH2)
分支2
;;
...
*)
默認分支
;;
esac
case支持glob風格的通配符:
*:任意長度任意字符
?:任意單個字符
[]:指定范圍內的任意單個字符
a|b:a或b
例子:
[root@centos SC]#vim yesorno.sh
#!/bin/bash
#####提示輸入,讀取輸入的值
read -p "please input yes or no: " ans
#####將輸入轉換為小寫輸出
ans=`echo $ans |tr '[:upper:]' '[:lower:]'`
#####進行判斷,執(zhí)行相應命令
case $ans in
y|ye|yes)
echo this is yes
;;
n|no)
echo this is no
;;
*)
echo This is other information , please input yes or no
esac
~
~
~
~
~
~
~
~
~
~
######測試結果
[root@centos SC]#./yesorno.sh
please input yes or no: y
this is yes
[root@centos SC]#./yesorno.sh
please input yes or no: Ye
this is yes
[root@centos SC]#./yesorno.sh
please input yes or no: yeS
this is yes
[root@centos SC]#./yesorno.sh
please input yes or no: n
this is no
[root@centos SC]#./yesorno.sh
please input yes or no: No
this is no
[root@centos SC]#./yesorno.sh
please input yes or no: nO
this is no
[root@centos SC]#./yesorno.sh
please input yes or no: P
This is other information , please input yes or no