Shell 编程基础之 Case 练习

一、语法

case  $变量 in
  "第一个变量内容")   # 每个变量内容建议用双引号括起来,关键字则为小括号 )
    # 执行内容
    ;;              # 每个类别结尾使用两个连续的分号来处理!
  "第二个变量内容")
    # 执行内容
    ;;
  *)                # 最后一个变量内容都会用 * 来代表所有其他值,但不包含第一个变量内容与第二个变量内容的其他程序运行段
    # 执行内容
    ;;
esac                # 最终的以反写的 case 结尾 

二、练习

  1. 模拟 Linux 启动脚本
    status=0 # 0: start; 1:stop
    case "$1" in
    "start")
        echo "* program is running"
      ;;
    "stop")
        echo "* Stopping  program"
      ;;
    "status")
        echo "* program is running"
      ;;
    "restart")
        echo "* Stopping program"
        echo "* program is running"
      ;;
    *)
        echo "Plz input [start|stop|status|restart]"
       ;;
    esac
    user@ae01:~$ ./test.sh start
    * program is running
    user@ae01:~$ ./test.sh stop
    * Stopping  program
    user@ae01:~$ ./test.sh status
    * program is running
    user@ae01:~$ ./test.sh restart
    * Stopping program
    * program is running
    user@ae01:~$ ./test.sh
    Plz input [start|stop|status|restart]
    user@ae01:~$
原文地址:https://www.cnblogs.com/tannerBG/p/4057182.html