多条件判断语句case

一、case语句的基本格式:

case 变量 in
    模式1)
        语句块1
         ;;
    模式2)
        语句块2
        ;;
    ......
        ;;
esac

上面的格式中,每个模式后面的两个分号“;;”是模式结束标记。系统执行模式后面的语句时,不会越过此标记。

二、利用case语句处理选项参数

[root@localhost shell]# cat use_case_deal_with_option.sh 
#!/bin/bash

#Use case to deal with options.
#2012.12.20

OPTION_L=1
OPTION_H=1
OPTION_A=1
OPTION_D=1
FILE_NAME="."
CMD="ls"

while [ $# -gt 0 ]
 do
        case “$1” in
                -l)
                        OPTION_L=0
                        shift
                        ;;
                -h)
                        OPTION_H=0
                        shift
                        ;;
                -a)
                        OPTION_A=0
                        shift
                        ;;
                -d)
                        OPTION_D=0
                        shift
                        ;;
                *)
                        FILE_NAME=$1
                        shift
                        ;;
        esac
done

if [ $OPTION_H = "0" ] && [ $OPTION_L = "1" ]
 then
        OPTION_H=1
fi

if [ $OPTION_H = "0" ] && [ $OPTION_L = "0" ]
 then
        CMD=$CMD" -hl"
fi

if [ $OPTION_L = "0" ] && [ $OPTION_H = "1" ]
 then
        CMD=$CMD" -l"
fi

if [ $OPTION_A = "0" ]
 then
        CMD=$CMD" -a"
fi

if [ $OPTION_D = "0" ]
 then
        CMD=$CMD" -d"
fi

$CMD $FILE_NAME
[root@localhost shell]# ./use_case_deal_with_option.sh -l /root
total 101904
-rw-------  1 root root     1020 Nov 13 00:07 anaconda-ks.cfg
drwxr-xr-x  3 root root     4096 Sep 30  2011 Blue
-rw-r--r--  1 root root   223118 Sep 30  2011 Blue-1.8.tar.bz2
drwxr-xr-x  2 root root     4096 Dec 17 15:01 Desktop
-rw-------  1 root root  2427054 Dec 16 21:29 initrd-2.6.18-53.el5.img
-rw-r--r--  1 root root    29086 Nov 13 00:06 install.log
-rw-r--r--  1 root root     3325 Nov 13 00:04 install.log.syslog
-rwxr-xr-x  1 root root    88749 Dec 14 09:44 lbzip2-2.1-1.el5.rf.i386.rpm
-rw-r-----  1 root root 90951680 Dec  2 21:01 linux.iso
-rw-------  1 root root    45170 Dec 13 10:03 mbox
drwxrwxr-x 33 1000 1000     4096 Dec 14 14:45 MPlayer-1.0rc4
-rw-r--r--  1 root root 10351350 Jan 30  2011 MPlayer-1.0rc4.tar.bz2
-rw-r--r--  1 root root     1285 Dec  5 10:49 ping.txt
-rw-r--r--  1 root root      128 Dec 12 17:19 root_cron
drwxr-xr-x  2 root root     4096 Dec 10 17:01 test
[root@localhost shell]# ./use_case_deal_with_option.sh -l -d /root
drwxr-x--- 23 root root 4096 Dec 20 09:22 /root

三、利用case语句处理用户输入

......
while true
 do
    echo -n "Please enter yes or no?[yes|no]"
    read ANS
    case “$ANS” in
        y|Y|yes|Yes)
            echo "You enter yes"
            ......
            break
            ;;
        n|N|no|No)
            echo "You enter no"
            ......
            break
            ;;
        *)
            echo "Please enter yes or no."
            continue
            ;;
    esac
done
......
posted @ 2013-12-20 09:32  ITtecman  阅读(3842)  评论(0编辑  收藏  举报