case $變數名稱 in "變數內容1") 程式段 ;; ###兩個分號 (;;) 來代表該程式段落的結束 "變數內容2") 程式段 ;; *) 不包含變數內容1與變數內容2的其他程式執行段 exit 1 ;; esac
[dywang@dywmac zzz]$ cat sh08.sh #!/bin/bash case $1 in "hello") echo "Hello, how are you?" ;; "") echo "You MUST input parameters, ex> $0 someword" ;; *) echo "Usage $0 {hello}" ;; esac
[dywang@dywmac zzz]$ sh sh08.sh You MUST input parameters, ex> sh08.sh someword [dywang@dywmac zzz]$ sh sh08.sh someword Usage sh08.sh {hello} [dywang@dywmac zzz]$ sh sh08.sh hello Hello, how are you?
if, case
都可以做條件判斷,就看使用哪種方式腳本可讀性、維護性比較高。以下例題使用 if 判斷星期幾?以決定使用的練習虛擬機,使用 case 判斷外部第 1 個參數,決定要在虛擬機執行什麼程式?
[dywang@dywmac zzz]$ cat sh09.sh rhce #!/bin/bash k=$(date +%u) if [ "$k" -eq "4" ]; then kvm=kvm3 elif [ "$k" -eq "1" ]; then kvm=kvm5 else kvm=kvm6 fi kvm="${kvm}.deyu.wang" case $1 in 'lpvar'|'rhcsa'|'rhce'|'mysql'|'py') cmd="sh /tmp/$1.sh" ;; 'halt'|'reboot') cmd="$1" ;; 'hello') cmd="cd ~/zzz && ./hello" ;; 'ntp') cmd="ntpdate -u 192.168.1.140" ;; *) cmd="exit" echo "Nothing to do!" ;; esac echo "ssh $kvm \"$cmd\""
[dywang@dywmac zzz]$ sh sh09.sh rhce ssh kvm6.deyu.wang "sh /tmp/rhce.sh" [dywang@dywmac zzz]$ sh sh09.sh py ssh kvm6.deyu.wang "sh /tmp/py.sh" [dywang@dywmac zzz]$ sh sh09.sh halt ssh kvm6.deyu.wang "halt" [dywang@dywmac zzz]$ sh sh09.sh ntp ssh kvm6.deyu.wang "ntpdate -u 192.168.1.140" [dywang@dywmac zzz]$ sh sh09.sh Nothing to do! ssh kvm6.deyu.wang "exit"