Shell语法—— case 条件语句

case 条件语句语法

case 条件语句语法格式为:

case  " 变量 " in
                    值 1)
                                    指令 1
                    ;;
                    值 2)
                                    指令 2
                    ;;
                    \* )
                                    指令 3
                    ;;
esac
了解即可

给字体加颜色的命令:
例:echo -e "\E[1;31m 红颜色 hello world \E[0m"

  1. \E 等同于 \033
  2. "[1" 数字 1 表示加粗显示
  3. 31m 表示红色字体
  4. "[0m" 表示关闭所有属性
  5. "[1m" 表示设置高亮度
  6. "[4m" 表示下划线
  7. "[5m" 表示闪烁
  8. "[7m" 表示反显
  9. "[8m" 表示消隐
  10. \33[30m -- \33[37m 表示设置前景色
  11. \33[40m -- \33[47m 表示设置背景色
    案例一:
    编写 Nginx 启动 停止服务。
    此处仅为做逻辑与 case 语法练习所用,脚本本身并没有什么用途
#!/bin/bash
RETVAL=0
pid=/var/run/nginx.pid
. /etc/init.d/functions
start(){
if [ ! -f $pid ];then
        service nginx start
        RETVAL=$?
        if [ $RETVAL -eq 0 ];then
                action "nginx is started" /bin/true
                return $RETVAL
        else
                action "nginx is started" /bin/false
                return $RETVAL
        fi
else
        echo "nginx is running"
        return 0
fi
}

stop(){
if [ -f $pid ];then
        service nginx stop
        RETVAL=$?
        if [ $RETVAL -eq 0 ];then
                action "nginx is started" /bin/true
                return $RETVAL
        else
                action "nginx is started" /bin/false
                return $RETVAL
        fi
else 
        echo "nginx is stop"
        return 0
fi
}

restart(){
        stop
        start
}

case $1 in
  start|yes)
        start
        RETVAL=$?
        ;;
  stop|no)
        stop
        RETVAL=$?
        ;;
  restart|or)
        restart
        RETVAL=$?
        ;;
  \*)
        echo "Usage:$0{start(yse)|stop(on)|restart(or)}"
        exit 1
esac
exit $RETVAL

猜你喜欢

转载自blog.51cto.com/12384628/2294211