1. case與if…elif…else
它們都是多分支條件句,不同的是,case語句只能判斷一種條件關係,而if語句可以判斷多種關係
2. 格式
case $變數名 in
"值1") 如果變數的值等於值1,則執行程式1;;
"值2") 如果變數的值等於值2,則執行程式2;;
......
*) 如果變數的值都不是以上的值,則執行此程式;;
esac
3. 練習1:判斷使用者輸入指令碼
#!/bin/bash
#判斷使用者輸入
read -p "please choose yes/no:" -t 30 cho
case $cho in
"yes") echo "your choose is yes";;
"no") echo "your chosse is no";;
*) echo "please input yes|no";;
esac
測試指令碼
[root@catyuan ~]# chmod 755 case1.sh
[root@catyuan ~]# ./case1.sh
please choose yes/no:yes
your choose is yes
[root@catyuan ~]# ./case1.sh
please choose yes/no:no
your chosse is no
[root@catyuan ~]# ./case1.sh
please choose yes/no:dv
please input yes|no
4. 練習2指令碼
[root@catyuan ~]# vim case2.sh
#!/bin/bash
#選擇你想去的城市
echo "shanghai:please input 1"
echo "xi'an:please input 2"
echo "beijing:please input 3"
read -t 30 -p "please input your choose:" cho
case $cho in
"1") echo "shanghai";;
"2") echo "xi'an";;
"3") echo "beijing";;
*) echo "please input 1|2|3"
esac
測試指令碼
[root@catyuan ~]# chmod 755 case2.sh
[root@catyuan ~]# ./case2.sh
shanghai:please input 1
xi'an:please input 2
beijing:please input 3
please input your choose:1
shanghai
[root@catyuan ~]# ./case2.sh
shanghai:please input 1
xi'an:please input 2
beijing:please input 3
please input your choose:2
xi'an
[root@catyuan ~]# ./case2.sh
shanghai:please input 1
xi'an:please input 2
beijing:please input 3
please input your choose:3
beijing
[root@catyuan ~]# ./case2.sh
shanghai:please input 1
xi'an:please input 2
beijing:please input 3
please input your choose:5
please input 1|2|3
Shell流程控制
case迴圈 if condition condition then statements if true 1 elif condition condition then statements if true 2 else statements if all else fails fi注 方括號中的...
Shell 流程控制
shell的流程控制不可為空,如果else分支沒有語句執行,就不要寫這個else。if 語句語法格式 if condition then command1 command2 commandn fi寫成一行 適用於終端命令提示符 if ps ef grep c ssh gt 1 then echo t...
Shell流程控制
shell 流程控制 if else if語法格式 if condition then command1 command2 fi 末尾的fi就是if倒過來拼寫 if else語法 if condition then command1 command2 else command1 fi if else...