第八章 流程控制之case语句

1 语法

  1. case 变量 in
  2. 模式1)
  3. 代码1
  4. ;;
  5. 模式2)
  6. 代码2
  7. ;;
  8. 模式3)
  9. 代码3
  10. ;;
  11. *)
  12. 无匹配后命令序列
  13. esac

2 案例

2.1 案例1 猜数字

  1. [root@xujun1270 ~]# cat case-1.sh
  2. #!/bin/bash
  3. read -p "qing shu ru shu zi:" num
  4. case "$num" in
  5. 1)
  6. echo "zhe ge shu zi shi 1"
  7. ;;
  8. 2)
  9. echo "zhe ge shu zi shi 2"
  10. ;;
  11. 3)
  12. echo "zhe ge shu zi shi 3"
  13. ;;
  14. *)
  15. echo "bi xu you shu zi"
  16. exit 2
  17. esac

2.2 案例2 根据水果的不同,打印出对应的颜色

  1. [root@xujun1270 ~]# cat case-2.sh
  2. #!/bin/bash
  3. RED_COLOR='\E[1;31m'
  4. GREEN_COLOR='\E[1;32m'
  5. YELLOW_COLOR='\E[1;33m'
  6. BLUE_COLOR='\E[1;34m'
  7. RES='\E[0m'
  8. menu(){
  9. cat <<EOF
  10. ==================
  11. 1.apple
  12. 2.pear
  13. 3.banana
  14. 4.cherry
  15. =================
  16. EOF
  17. }
  18. menu
  19. read -p "pls select color:" num
  20. case $num in
  21. 1)
  22. echo -e "${RED_COLOR}apple${RES}"
  23. ;;
  24. 2)
  25. echo -e "${GREEN_COLOR}pear${RES}"
  26. ;;
  27. 3)
  28. echo -e "${YELLOW_COLOR}banana${RES}"
  29. ;;
  30. 4)
  31. echo -e "${BLUE_COLOR}cherry${RES}"
  32. ;;
  33. *)
  34. echo "$0 be {1|2|3|4}"
  35. esac

2.3 案例3 nginx启动脚本

  1. [root@xujun1270 init.d]# cat nginx.sh
  2. #!/bin/bash
  3. #chkconfig: 2345 40 80
  4. #description:starts,stop and saves iptables firewall
  5. . /etc/init.d/functions
  6. pidfile=/application/nginx/logs/nginx.pid
  7. start_nginx (){
  8. if [ -f $pidfile ];then
  9. echo "nginx is running"
  10. else
  11. /application/nginx/sbin/nginx &>/dev/null
  12. action "nginx is started" /bin/true
  13. fi
  14. }
  15. stop_nginx (){
  16. if [ -f $pidfile ];then
  17. /application/nginx/sbin/nginx -s stop &>/dev/null
  18. action "nginx is stopped" /bin/true
  19. else
  20. action "nginx is stopped" /bin/false
  21. fi
  22. }
  23. reload_nginx (){
  24. if [ -f $pidfile ];then
  25. /application/nginx/sbin/nginx -s reload &>/dev/null
  26. action "nginx is reloaded" /bin/true
  27. else
  28. echo "cat't open $pidfile,no such file or directory"
  29. fi
  30. }
  31. case $1 in
  32. start)
  33. start_nginx
  34. RETVAL=$?
  35. ;;
  36. stop)
  37. stop_nginx
  38. RETVAL=$?
  39. ;;
  40. restart)
  41. stop_nginx
  42. sleep 3
  43. start_nginx
  44. RETVAL=$?
  45. ;;
  46. reload)
  47. reload_nginx
  48. RETVAL=$?
  49. ;;
  50. *)
  51. echo "$0 {start|stop|restart}"
  52. exit 1
  53. esac
  54. exit $RETVAL

3 case语句小结

1、case语句就相当于多分支的if语句,但是case语句优势更规范、易读

2、case语句适合变量的值少,且为固定的数字或字符串集合

3、系统服务启动脚本一般都是用case语句