15、bash編程
選擇執行:if單分支、if雙分支、if多分支;case語句
2、case語句:
語法格式:
case $VARIABLE in //$VARIABLE是變量引用,in是關鍵字
PAT1) //模式1
分支1
;; //以雙分號結束分支1語句
PAT2)
分支2
;;
...
*) //所有都不匹配,為*,類似else
分支n
;;
esca
註意:①、每個case中的模式語句必須以雙分號結尾,這裏的雙分號可以單獨成行,也可以放在每個分支的最後一條語句後面,PAT僅支持golb風格的通配符(*、?、[ ] 、[^ ])
②、case語句僅適用於一個變量與多個值分別做模式匹配時適用。
3、示例:顯示一個如下菜單給用戶
cpu) display cpu information
mem)display mem information
disk)display disk information
*) quit
要求:提示用戶給出自己的選擇
正確的選擇則給出相應的信息,否則,則提示重新選擇正確的選項。
if語句實現: [root@localhost sh]# cat men.sh #!/bin/bash cat << EOF cpu) display cpu information mem)display mem information disk)display disk information *) quit EOF read -p "enter your choice:" choice while [ "$choice" != "cpu" -a "$choice" != "mem" -a "$choice" != "disk" -a "$choice" != "*" ];do echo "please make sure your choice" read -p "enter your choice again:" choice done if [ "$choice" == "cpu" ];then lscpu elif [ "$choice" == "mem" ];then free elif [ "$choice" == "disk" ];then fdisk -l /dev/[hs]d[a-z] else echo "quit" exit 4 fi [root@localhost sh]# | case語句實現: [root@localhost sh]# cat case.sh #!/bin/bash cat << EOF cpu) display cpu information mem)display mem information disk)display disk information *) quit EOF read -p "enter your choice:" choice while [ "$choice" != "cpu" -a "$choice" != "mem" -a "$choice" != "disk" -a "$choice" != "*" ];do echo "please make sure your choice" read -p "enter your choice again:" choice done case $choice in cpu) lscpu;; mem) free ;; disk) fdisk -l /dev/[hs]d[a-z] ;; *) echo "quit" exit 4 esac [root@localhost sh]# |
15、bash編程