shell中的case判断

2019-08-21  本文已影响0人  哆来咪发都不会
格式
case  变量名 in 
    value1)
        command
        ;;
    value2)
        command
        ;;
    value3|value4)
        command
        ;;
    *)
        command
        ;;
esac
举例
"$1"表示输入的第1个参数
"$2"表示第2个参数
#!/bin/bash
case  $1 in 
    start)
        echo "starting..."
        ;;
    stop)
        echo "stopping..."
        ;;
    reboot|restart)
        echo "restarting..."
        ;;
    *)
        echo "Usage:{start|stop|restart|reboot}"
        ;;
esac
[root@localhost wang]# sh -x case.sh
+ case $1 in
+ echo 'Usage:{start|stop|restart|reboot}'
Usage:{start|stop|restart|reboot}
[root@localhost wang]# sh -x case.sh start
+ case $1 in
+ echo starting...
starting...
[root@localhost wang]# 

[root@localhost wang]# sh -x case.sh
+ case $2 in
+ echo 'Usage:{start|stop|restart|reboot}'
Usage:{start|stop|restart|reboot}
[root@localhost wang]# sh -x case.sh start
+ case $2 in
+ echo 'Usage:{start|stop|restart|reboot}'
Usage:{start|stop|restart|reboot}
[root@localhost wang]# sh -x case.sh start stop
+ case $2 in
+ echo stopping...
stopping...
[root@localhost wang]# 
case后面也可以直接跟参数
[root@localhost wang]# sh -x case.sh
+ case "start" in
+ echo starting...
starting...
[root@localhost wang]# sh -x case.sh stop
+ case "start" in
+ echo starting...
starting...
[root@localhost wang]# 
上一篇下一篇

猜你喜欢

热点阅读