阅读(1707) (0)

Shell case...esac 语句

2021-08-31 09:16:52 更新

可以使用多个if...elif 语句执行多分支。然而,这并不总是最佳的解决方案,尤其是当所有的分支依赖于一个单一的变量的值。

Shell支持 case...esac  语句处理正是这种情况下,它这样做比 if...elif 语句更有效。

语法

case...esac 语句基本语法 是为了给一个表达式计算和几种不同的语句来执行基于表达式的值。

解释器检查每一种情况下对表达式的值,直到找到一个匹配。如果没有匹配,默认情况下会被使用。

case word in
  pattern1)
     Statement(s) to be executed if pattern1 matches
     ;;
  pattern2)
     Statement(s) to be executed if pattern2 matches
     ;;
  pattern3)
     Statement(s) to be executed if pattern3 matches
     ;;
esac

这里的字符串字每个模式进行比较,直到找到一个匹配。执行语句匹配模式。如果没有找到匹配,声明退出的情况下不执行任何动作。

没有最大数量的模式,但最小是一个。

当语句部分执行,命令;; 表明程序流程跳转到结束整个 case 语句。和C编程语言的 break 类似。

例子:

#!/bin/sh

FRUIT="kiwi"

case "$FRUIT" in
   "apple") echo "Apple pie is quite tasty." 
   ;;
   "banana") echo "I like banana nut bread." 
   ;;
   "kiwi") echo "New Zealand is famous for kiwi." 
   ;;
esac

这将产生以下结果:

New Zealand is famous for kiwi.

case语句是一个很好用的命令行参数如下计算:

#!/bin/sh

option="${1}" 
case ${option} in 
   -f) FILE="${2}" 
      echo "File name is $FILE"
      ;; 
   -d) DIR="${2}" 
      echo "Dir name is $DIR"
      ;; 
   *)  
      echo "`basename ${0}`:usage: [-f file] | [-d directory]" 
      exit 1 # Command to come out of the program with status 1
      ;; 
esac 

下面是一个示例运行这个程序:

$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$