case語句格式
# vi test.sh : echo "input : " read num echo "the input data is $num" case $num in 1) echo "January";; 雙分號結束 2) echo "Feburary";; 5) echo "may" 每個case可以有多條命令 echo "sdfd" echo "sdf";; 但最後一條命令一定是雙分號結束 *) echo "not correct input";; *)是其他值、default的意思 esac |
# sh ./test.sh input : 2 the input data is 2 Feburary # sh ./test.sh input : ter the input data is ter not correct input |
case 語句如果某個選項沒有任何語句,也要加;; 否則會出下邊錯誤
test: line 166: syntax error near unexpected token `)'
test: line 166: `"system hostname config")'
爲什麼輸入no,仍不匹配到[no]
原來[]是專門針對單字符的值,如果用[no],就是n和o之一
case $yn in [no]) return 1;; * ) echo "only accept Y,y,N,n,YES,yes,NO,no" >&2;; |
[macg@mac-home ~]$ sh test.sh enter y/n : no only accept Y,y,N,n,YES,yes,NO,no |
改正
case $yn in no) return 1;; NO) return 1;; * ) echo "only accept Y,y,N,n,YES,yes,NO,no" >&2;; esac |
[macg@mac-home ~]$ sh test.sh enter y/n : no |
一個getyn()函數的例子
getyn( ) { while echo "enter y/n :" do read yn case $yn in [Yy]) return 0 ;; yes) return 0 ;; YES) return 0 ;; [Nn]) return 1 ;; no) return 1;; NO) return 1;; * ) echo "only accept Y,y,N,n,YES,yes,NO,no" ;; esac done } |
if getyn 調用函數 以函數作爲if條件,必須用if command法 then 注意0爲真 echo " your answer is yes" else echo "your anser is no" fi |
if, case,匹配字符串最常見,但如何匹配一段很長的輸出,一堆文字?最好方法,用“*”,如:*"command not found"*
[macg@machome ~]$ vi test.sh var=$(ls -l $1) $()取命令輸出,$1是命令行參數 echo "output is $var" case $var in "-rw-rw-r--"*) echo "this is not a execute file";; "-rwxrwxr-x"*) echo "this is a execute file"; 注意*在雙引號外邊 esac |
[macg@machome ~]$ sh test.sh 22.txt output is -rw-rw-r-- 1 macg macg 15 Jun 9 19:00 22.txt this is not a execute file [macg@machome ~]$ chmod +x 22.txt [macg@machome ~]$ sh test.sh 22.txt output is -rwxrwxr-x 1 macg macg 15 Jun 9 19:00 22.txt this is a execute file |
例2.匹配file命令輸出的一堆文字,以獲知文件類型
用’ ’ 取輸出,然後用CASE+*對輸出做修飾處理.
[macg@machome ~]$ vi test.sh var=`file $1` ` `和$( )作用相同,是取命令輸出 echo "output is $var" case $var in "$1: ASCII text"*) echo "this is a text file";; "$1: directory"*) echo "this is a directory";; 注意*在雙引號外邊 esac |
[macg@machome ~]$ sh test.sh 22.txt output is 22.txt: ASCII text this is a text file [macg@machome ~]$ sh test.sh test-dir output is test-dir: directory this is a directory |
最典型的shell case命令匹配命令行,用於sys v啓動腳本的start|stop|restart|status處理
case "$@" in
($@ 字符串數組:以"參數1" "參數2" ... 的字符串數組形式保存所有參數
對於單個參數的情況,$@就是一個字符串)
start)
echo -n "Starting firewall..."
。。。
echo "OK!"
exit 0
;;
stop)
echo -n "Stopping firewall..."
。。。
exit 0
;;
restart)
$0 stop $0即執行原始程序
$0 start
;;
status)
clear
echo ">------------------------------------------"
iptables -L
echo ">------------------------------------------"
iptables -t nat -L POSTROUTING
exit 0
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
esac