淺談case語句與select語句

case語句與select語句


case語句:

多分支if語句:

if CONDITION1;then

分支1

elif CONDITION2;then

分支2

...

else CONDITION;then

分支n

fi


例如下面這段代碼,我們可以使用while語句內嵌套if語句實現,

#!/bin/bash

cat << EOF

cpu) display cpu information

mem) display memory information

disk) display disks information

quit) quit

==================================

EOF


read -p "Entwer your option: " option


while [ "$option" != "cpu" -a "$option" != "mem" -a "$option" != "disk" -a "$option" != "quit" ]; do

echo "cpu,mem,disk,quit"

read -p "Entwer your option: " option

done


if [ "$option" == "cpu" ];then

lscpu

elif [ "$option" == "mem" ];then

free -m

elif [ "$option" == "disk" ];then

fdisk -l /dev/[hs]d[a-z]

else

echo "quit"

exit 0

fi


不難看出,語句有些陳雜,下面我們看一下case語句的語法格式,


case語句的語法格式:


case $VARAIBLE in

PAT1)

分支1

;;

PAT2)

分支2

;;

...

*)

分支n

;;

esac

利用case我們將上面的代碼修改一下,結果如下:

#!/bin/bash

cat << EOF

cpu) display cpu information

mem) display memory information

disk) display disks information

quit) quit

==================================

EOF


read -p "Entwer your option: " option


while [ "$option" != "cpu" -a "$option" != "mem" -a "$option" != "disk" -a "$option" != "quit" ]; do

echo "cpu,mem,disk,quit"

read -p "Entwer your option: " option

done


case $option in

cpu)

lscpu ;;

men)

free -m ;;

disk)

fdisk -l /dev/[hs]d[a-z] ;;

*)

echo "quit"

exit 0 ;;

esac

是不是比if語句更直觀,更有條理性

最後我們在說一下與case類似的select語句


select 循環與菜單

select variable in list

do

循環體命令

done


select循環主要用於創建菜單,按數字順序排列的菜單項將顯示在標準錯誤上,並顯示PS3提示符,等待用戶輸入

用戶輸入菜單列表中的某個數字,執行相應的命令

用戶輸入被保存在內置變量REPLY中

select是個無限循環,因此要記住用break命令退出循環,或用exit命令終止腳本。也可以按ctrl+c退出循環

select 經常和case聯合使用

與for循環類似,可以省略 in list ,此時使用位置參量


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章