條件判斷式的使用
if then
只有一個判斷式
if [條件判斷式];then
...... //符合if條件的在這裏執行
fi //返回來寫結束if判斷之意
多個條件
放在一個[ ]裏
[a -o b] [a -a b]
-o or
-a and
放在多個[ ]裏
[a] && [b]
[a] || [b]
&& 代表 and
|| 代表 or
read -p "please input (Y/N):" yn
if [ "$yn" == "Y" -o "$yn" == "y" ];then
echo -e "OK,Continue"
exit 0
fi
if [ "$yn" == "N" -o "$yn" == "n" ];then
echo -e "OK,Interrupt"
exit 0
fi
echo -e "I dont't know what your choices" && exit 0
注意:
[ ]中兩側和各個條件之間加 空格
if 需要結束符號 fi 倒寫過來
多重、複雜條件判斷
一個條件的判斷
#一個條件判斷,分成功與失敗進行
if []; then
...... 條件成立時,執行的程序
else
...... 條件失敗時,執行的程序
fi
多個條件的判斷
#更多條件參與判斷,分多種情況執行
if [1]; then
...... 符合1,執行
elif [2]; then
...... 符合2,執行
else
...... 1和2都不符合,執行
fi
實驗代碼
if [ "$1" == "hello" ];then
echo -e "Hello,How are you?"
elif [ "$1" == "" ];then
echo -e "You must input parameters,ex> {$0 someword}"
else
echo -e "The only parameter is hello, ex> {$0 hello}"
fi
利用case
#使用方式
case $變量名 in
"1")
...... #滿足第一個條件
;;
"2")
...... #滿足第二個條件
;;
"*")
exit 1 #不滿足上述任何條件
;;
esac
實驗代碼
case $1 in
"one")
echo " your choice is one"
;;
"two")
echo "your choice is two"
;;
"three")
echo "your choice is three"
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac
使用function的功能
#語法
function fname(){
......
}
實驗代碼
function printit(){
echo -n "Your choice is ";
}
# read -p "Input your choice:" choice
# case $choice in
echo "This program will print your selection !"
case $1 in
"one")
printit;echo $1 | tr 'a-z' 'A-Z'
;;
"two")
printit;echo $1 | tr 'a-z' 'A-Z'
;;
"three")
printit;echo $1 | tr 'a-z' 'A-Z'
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac
注意,
shell是自上而下,自左而右執行的,所以function的聲明必須放在最前面,否則會在調用的時候報找不到function的錯誤。
function的內建參數
和shell腳本的默認參數類似
$0代表函數名,$1,$2,#依次類推
使用的時候,不能和shell腳本的默認參數混淆
實驗代碼
function printit(){
echo "Your choice is $1";
}
# read -p "Input your choice:" choice
# case $choice in
echo "This program will print your selection !"
case $1 in
"one")
printit 1
;;
"two")
printit 2
;;
"three")
printit 3
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac
注意:
case 後面的 $1 指執行腳本的時候緊跟的第一個參數
printit 裏面的$1 指調用它緊跟的參數,這裏指 1 2 3