首页 > 代码库 > bash脚本编程之case语句

bash脚本编程之case语句

case语句用于简化复杂的if语句

#!/bin/bash
while true; do
  read -p "Enter your score:" score
  if [ "$score" == "quit" ]; then
          exit 0
  elif [ $score -lt 60 ]; then
          echo "stupid"
          break
  elif [[ $score -ge 60 && $score -lt 70 ]]; then
          echo "C"
          break
  elif [[ $score -ge 70 && $score -lt 80 ]]; then
          echo "B"
          break
  elif [[ $score -ge 80 && $score -lt 90 ]]; then
          echo "A"
          break
  elif [ $score -ge 90 ]; then
          echo "A+"
          break
  else 
          continue  
  fi
done


case 语句的语法格式:

case expression in
pattern1)
    suite1
    ;;
pattern2)
    suite2
    ;;
...
patternn)
    suiten
    ;;
*)
    other_suiten
    ;;
esac

case中的pattern可以使用的模式:

    a|b: a或者b

    *: 任意长度的任意字符

    ?: 任意单个字符

    []: 指定范围

使用case语句改写以上代码,如下:

#!/bin/bash
while true; do
  read -p "Enter your score:" score
  case $score in
  [1-5][0-9])
          echo "stupid"
          ;;
  6[0-9])
          echo "C"
          ;;
  7[0-9])
          echo "B"
          ;;
  8[0-9])
          echo "A"
          ;;
  9[0-9])
          echo "A+"
          ;;
  100)
          echo "excelent"
          ;;
  quit)
          exit 0
          ;;
  *)
          continue
          ;;
  esac
done


本文出自 “虎虎生威” 博客,请务必保留此出处http://tobeone.blog.51cto.com/817917/1550314

bash脚本编程之case语句