case 語句通常用于簡化具有多種不同選擇的復(fù)雜條件語句,使 Bash 腳本更具可讀性,并更易于維護(hù)。
語法:
case expression in
pattern_1)
statements
;;
pattern_2)
statements
;;
pattern_3|pattern_4|pattern_5)
statements
;;
pattern-n)
statements
;;
*)
statements
;;
esac
注:
- 可以運(yùn)用|
分隔的多個(gè)模式運(yùn)算符,運(yùn)算符指示模式列表的終止。
-pattern) statements
這樣的模式語句被稱為子句,須以;;
終止。
-*
用于定義默認(rèn)情況下的最終模式。當(dāng)用作最后一種匹配模式時(shí),它作為默認(rèn)匹配。
運(yùn)作規(guī)則:
;;
結(jié)束。case
以最后執(zhí)行的語句的退出狀態(tài)終止。case
的退出狀態(tài)為零。*
模式,那么在匹配其他項(xiàng)失敗后將執(zhí)行它。示例:
#!/bin/bash
echo "Which Operating System are you using?"
echo "Windows, Android, Chrome, Linux, Others?"
read -p "Type your OS Name:" OS
case $OS in
Windows|windows|window|win)
echo "That's common. You should try something new."
echo
;;
Android|android)
echo "This is my favorite. It has lots of applications."
echo
;;
Chrome|chrome)
echo "Cool!!! It's for pro users. Amazing Choice."
echo
;;
Linux|linux)
echo "You might be serious about security!!"
echo
;;
*)
echo "Sounds interesting. I will try that."
echo
;;
esac
執(zhí)行后得到以下結(jié)果:
which Operating System are you using?
Windows, Android, Chrome, Linux, Others?
Type your OS Name:linux
You might be serious about security!!
更多建議: