曲径通幽论坛

标题: case 语句 [打印本页]

作者: beyes    时间: 2008-12-31 23:37
标题: case 语句
格式:
case 值 in
模式1)
     命令1
       ;;
模式2)
     命令2
       ;;
esac                      //结束标志(反过来写)
----------------说明--------------
case 取值后面必须为单词 in,每一模式必须以右括号结束。
取值可以变量或常数
匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;
模式匹配符 * 表示任意字符,? 表示任意单字符,[..]表示类或范围中任意字符。
作者: beyes    时间: 2009-1-1 00:53
标题: case 应用举例
#!/bin/bash

echo -n "please input a select number:(1-3)"

read NO

case $NO in
        1) echo "number 1 enter"
        ;;
        2) echo "number 2 enter"
        ;;
        3) echo "number 3 enter"
        ;;
        *) echo "`basename $0`: not between 1-3">&2        //输出信息到标准错误
           exit;
           ;;
esac

作者: beyes    时间: 2009-1-18 01:07
标题: case 举例-2
代码(一般写法)
#!/bin/bash

echo "Is it moring? Please answer yes or no"
read timeofday

case "$timeofday" in
         yes) echo "Good Morning";;
         no ) echo "Good Afternoon";;
         y  ) echo "Good Morning";;
         n  ) echo "Good Afternoon";;
         *  ) echo "Sorry, answer not recognized";;

esac

exit 0

简明写法
#!/bin/bash

echo "Is it moring? Please answer yes or no"
read timeofday

case "$timeofday" in
         yes | y | Yes | YES ) echo "Good Morning";;
         n* |  N* )            echo "Good Afternoon";;
         * )                   echo "Sorry, answer not recognized";;

esac

exit 0

下面例子展示了另一种的书写格式,即匹配项使用 [] 括号括起来,另外也演示了在匹配行中调用函数的形式:
[Bash shell] 纯文本查看 复制代码
#!/bin/sh

function sayhw() {
         echo "hello world"
}

function sayhl() {
         echo "hello linux"
}

function sayhu() {
         echo "hello unix"
}


echo "which do you want to?input the number."
echo "1. say hello world"
echo "2. say hello linux"
echo "3. say hello unix"
read num

case "$num" in
[1] ) (sayhw);;
[2] ) (sayhl);;
[3] ) (sayhu);;
*) echo "nothing,exit";;
esac

运行输出:
[beyes@beyes   shell]$ sh case.sh
which do you want to?input the number.
1. say hello world
2. say hello linux
3. say hello unix
1
hello world





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2