The case statement is used to simplify complex if statements.
#!/bin/bashwhile 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 fidone
Syntax format of the case statement:
case expression inpattern1) suite1 ;;pattern2) suite2 ;;...patternn) suiten ;;*) other_suiten ;;esac
Pattern in case:
A | B: A or B
*: Any character of any length
? : Any single character
[]: Specified range
Use the case statement to rewrite the above Code:
#!/bin/bashwhile 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 ;; esacdone
This article from the "Tiger, tiger, shengwei" blog, please be sure to keep this source http://tobeone.blog.51cto.com/817917/1550314
Case statement for Bash Script Programming