嵌套的 if 语句可能很好,但是当您需要处理几种不同的可能操作时,它们往往会让人困惑。 对于更复杂的条件,请使用 case 语法
case表达式inCASE1) 命令列表;;CASE2) 命令列表;; ...CASEN) 命令列表;; esac
每个 case 都是一个匹配模式的表达式。 第一个匹配项的 命令列表 中的命令将被执行。 "|" 符号用于分隔多个模式,")" 运算符终止模式列表。 每个 case 及其相应的命令称为一个子句。 每个子句必须以 ";;" 终止。 每个 case 语句都以 esac 语句结束。
在示例中,我们演示了使用 case 来发送更具选择性的警告消息,通过以下disktest.sh脚本
anny ~/testdir> cat disktest.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 nonexistent amount of disk space..." ;; esac echo $Message | mail -s "disk report `date`" anny anny ~/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:" 标头行的像样的邮件。
在您系统的 init 脚本目录中可以找到更多使用 case 语句的示例。 启动脚本使用 start 和 stop case 来运行或停止系统进程。 可以在下一节中找到一个理论示例。
Initscript 经常使用 case 语句来启动、停止和查询系统服务。 这是启动 Anacron 的脚本摘录,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 |
在每个 case 中要执行的任务,例如停止和启动守护程序,都在函数中定义,这些函数部分来源于/etc/rc.d/init.d/functions文件。 有关更多说明,请参见第 11 章。