嵌套 if 语句可能比较美观,但是只要你面临可能采取的一系列的不同动作时,你可能会迷惑。要处理复杂条件时,使用 case 语法:
case
EXPRESSION
in CASE1
) COMMAND-LIST;; CASE2
) COMMAND-LIST;; ... CASEN
) COMMAND-LIST;; esac
每个分支是一个符合pattern的表达式。在 COMMAND-LIST 中首先符合的的命令就执行。 “|” 符号用来分割多个pattern, “)” 操作符中断一个pattern。每个分支加上他们的后继命令称作一个 子句 。每个 子句 必须以 “;;” 结尾。每个 case 语句以 esac 语句结束。
在这个例子中,我们使用 disktest.sh
脚本的分支来发送一个更有选择性的警告信息:
anny ~/testdir>
catdisktest.sh
#!/bin/bash # This script does a very simple test for checking disk space. space=`df -h | awk '{print $5}' | grep % | grep -v Use | sort -n | tail -1 | cut -d "%" -f1 -` case $space in [1-6]*) Message="All is quiet." ;; [7-8]*) Message="Start thinking about cleaning out some stuff. There's a partition that is $space % full." ;; 9[1-8]) Message="Better hurry with that new disk... One partition is $space % full." ;; 99) Message="I'm drowning here! There's a partition at $space %!" ;; *) Message="I seem to be running with an nonexitent amount of disk space..." ;; esac echo $Message | mail -s "disk report `date`" annyanny ~/testdir>
You have new mail.anny ~/testdir>
tail-16
/var/spool/mail/anny
From anny@octarine Tue Jan 14 22:10:47 2003 Return-Path: <anny@octarine> Received: from octarine (localhost [127.0.0.1]) by octarine (8.12.5/8.12.5) with ESMTP id h0ELAlBG020414 for <anny@octarine>; Tue, 14 Jan 2003 22:10:47 +0100 Received: (from anny@localhost) by octarine (8.12.5/8.12.5/Submit) id h0ELAltn020413 for anny; Tue, 14 Jan 2003 22:10:47 +0100 Date: Tue, 14 Jan 2003 22:10:47 +0100 From: Anny <anny@octarine> Message-Id: <200301142110.h0ELAltn020413@octarine> To: anny@octarine Subject: disk report Tue Jan 14 22:10:47 CET 2003 Start thinking about cleaning out some stuff. There's a partition that is 87 % full.anny ~/testdir>
当然你可以打开你的邮件程序来检查结果;这只是为了证明脚本发送一个包含 “To:”, “Subject:” 和 “From:” 头信息的正式邮件。
更多使用 case 语句的例子可以在你系统的初始脚本目录找到。初始化脚本使用 start 和 stop 分支来启动和停止系统进程。可以在下一节找到一个更具理论性的例子。
初始脚本通常利用 case 语句来启动,停止和查询系统服务。以下摘录启动 Anacron 的脚本,一个周期性频繁运行命令的守护程序。
case "$1" in start) start ;; stop) stop ;; status) status anacron ;; restart) stop start ;; condrestart) if test "x`pidof anacron`" != x; then stop start fi ;; *) echo $"Usage: $0 {start|stop|restart|condrestart|status}" exit 1 esac
任务在每个分支执行,比如停止和启动守护进程。定义在函数中,部分源自 /etc/rc.d/init.d/functions
文件。参见 第 11 章 函数 得到更多的解释。