1. 程式人生 > >【shell】Linux shell 之 case 詳解

【shell】Linux shell 之 case 詳解

shell linux 運維 腳本 case

總的來說,case是一個判斷語句 ,比if更加容易理解一點。

case 語句格式

case in 變量 
值1)
    內容 ;;
值2)
    內容 ;;
esac

註意:每個內容後面都需要添加 ;; ,可以跨行也可以同行寫。

實例:根據用戶輸入的選擇執行語句。

#!/bin/bash -
# 打印選擇菜單
cat <<EOF
        Option:
        1) restart networking service.
        2) start networking service.
        3) stop networking service.
        *) exit.
EOF
read -p "Please enter a option:" number

# 使用case語句對參數進行判斷
case $number in
1)
        echo "The Networking service is restart,wait......" ;;
2)
        echo "The Networking service is start,wait......" ;;
3)
        echo "The Networking service is stop,wait......" ;;
*)
        echo "exit."  ;;
esac

[root@XiaoPeng scripts]# bash case.sh
Option:
1) restart networking service.
2) start networking service.
3) stop networking service.
*) exit.
Please enter a option:1
The Networking service is restart,wait......

版權所有:arppinging

【shell】Linux shell 之 case 詳解