shell 學習之case語句

通常建議變量用引號括起來bash

-v 顯示信息 ide

case 
shift
把剛纔的變量踢掉
oop

 

1、case語句:語法結構
case stitch in
value1)
    statement
    ...
    ;;
value2)
    statement
    ...
    ;;
*)
;;ui

esacspa

 

示例(給出選項讓用戶選擇,而後根據用戶所選顯示出相應的信息):orm

[root@lovelace case]# cat showmenu.sh
#!/bin/bash
#Version:0.1
#Auther:lovelace
#pragram:show menu and wait user choice
#
#difine an function to display the menu
showmenu(){
echo -n '+----------'
echo  -n -e "\033[1;32mshowmenu\033[0m"
echo '-----------+'
echo -e "| \033[31md|D) show disk information\033[0m  |"
echo -e "| \033[31mm|M) show memory usage\033[0m      |"
echo -e "| \033[31ms|S) show swap usage\033[0m        |"
echo -e "| \033[31mq|Q) quitting\033[0m               |"
echo -n '+-------------'
echo  -n -e "\033[5,33mEND\033[0m"
echo '--------------+'
}
#call showmenu function
echo
showmenu
echo
#read the argument for user input
read -p "Your choice is:" choice
#use while statement to loop
while [ "$choice" != "q" -o "$choice" != "Q" ];do
#jugement the choice values and dispaly the result
case $choice in
d|D)
echo "Disk information:"
df -h
;;
m|M)
echo "Memory information:"
free -m | grep "Mem"
;;
s|S)
echo "Swap information:"
free -m | grep "Swap"
;;
q|Q)
echo "quitting...."
exit 8
;;
*)
echo "Unknow argument."
;;
esac
#call showmenu function again
echo
showmenu
#read user input again
echo
read -p "Please select again:" choice
done

 

 

後記:這個好像就只是提了下case的語法結構,case在進行條件判斷的時候相對於if來說,我的更直觀一些,無論怎麼講,腳本注重的是實現的目的,而不是過程,因此無論黑貓白貓,只要能抓住老鼠,就是好貓。blog

相關文章
相關標籤/搜索