GB | BIG5
|
| 首頁 > 編程技術 > Shell > 正文 |
 |
| Linux程式設計-11.Shell Script(bash)--(6)流程控制case |
| http://www.openchess.org/noitatsko/programming/ (2001-05-25 13:04:01) |
case word in [ pattern [ | pattern ] ... ) list ;; ] ... esac
case/esac的標準用法大致如下:
case $arg in
pattern | sample) # arg in pattern or sample
;;
pattern1) # arg in pattern1
;;
*) #default
;;
esac
arg是您所引入的參數,如果arg內容符合pattern項目的話,那麼便會執行pattern以下的程式碼,而該段程式碼則以兩個分號";;"做結尾。
可以注意到"case"及"esac"是對稱的,如果記不起來的話,把"case"顛倒過來即可。
--------------------------------------------------------------------------------
例一 : paranoia
#!/bin/sh
case $1 in
start | begin)
echo "start something"
;;
stop | end)
echo "stop something"
;;
*)
echo "Ignorant"
;;
esac
執行
[foxman@foxman bash]# chmod 755 paranoia
[foxman@foxman bash]# ./paranoia
Ignorant
[foxman@foxman bash]# ./paranoia start
start something
[foxman@foxman bash]# ./paranoia begin
start something
[foxman@foxman bash]# ./paranoia stop
stop something
[foxman@foxman bash]# ./paranoia end
stop something
--------------------------------------------------------------------------------
例二 : inetpanel
許多的daemon都會附上一個管理用的Shell Script,像BIND就附上ndc,Apache就附上apachectl。這些管理程式都是用shell script來寫的,以下示一個管理inetd的shell script。
#!/bin/sh
case $1 in
start | begin | commence)
/usr/sbin/inetd
;;
stop | end | destroy)
killall inetd
;;
restart | again)
killall -HUP inetd
;;
*)
echo "usage: inetpanel [start | begin | commence | stop | end | destory | restart | again]"
;;
esac
--------------------------------------------------------------------------------
例三 : 判斷系統
有時候,您所寫的Script可能會跨越好幾種平台,如Linux、FreeBSD、Solaris等等,而各平台之間,多多少少都有不同之處,有時候需要判斷目前正在那一種平台上執行。此時,我們可以利用uname來找出系統資訊。
#!/bin/sh
SYSTEM=`uname -s`
case $SYSTEM in
Linux)
echo "My system is Linux"
echo "Do Linux stuff here..."
;;
FreeBSD)
echo "My system is FreeBSD"
echo "Do FreeBSD stuff here..."
;;
*)
echo "Unknown system : $SYSTEM"
echo "I don't what to do..."
;;
esac
(http://www.fanqiang.com)
進入【UNIX論壇】
|
|
| 相關文章 |
Linux程式設計-31.工作群資訊管理(grp) (2001-05-27 22:08:00) Linux程式設計-30.使用者資訊管理(pwd) (2001-05-27 21:04:00) Linux程式設計-29.時間處理 (2001-05-27 20:10:01) Linux程式設計-28.GNU Make (2001-05-27 19:00:00) Linux程式設計-27.GNU Debugger (2001-05-27 18:08:01) Linux程式設計-26.PIPE (2001-05-27 17:04:00) Linux程式設計-25.Message Queues (2001-05-27 16:10:00) Linux程式設計-24.Semaphores (2001-05-27 15:00:00) Linux程式設計-23.共享記憶體(Shared Memory) (2001-05-27 14:08:00) Linux程式設計-20.getopt (2001-05-27 13:04:00)
|
===更多相關=== |
|
|
 |
★ 樊強制作 歡迎分享 ★ |