shell中的select用法
分享
select也是循環的一種,它比較適合用在用戶選擇的情況下。
比如,我們有一個這樣的需求,運行腳本後,讓用戶去選擇數字,選擇1,會運行w命令,選擇2運行top命令,選擇3運行free命令,選擇4退出。腳本這樣實現:
- #!/bin/bash
- echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
- echo
- select command in w top free quit
- do
- case $command in
- w)
- w
- ;;
- top)
- top
- ;;
- free)
- free
- ;;
- quit)
- exit
- ;;
- *)
- echo "Please input a number:(1-4)."
- ;;
- esac
- done
執行結果如下:
sh select.sh
Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit
1) w
2) top
3) free
4) quit
#? 1
16:03:40 up 32 days, 2:42, 1 user, load average: 0.01, 0.08, 0.08
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 61.135.172.68 15:33 0.00s 0.02s 0.00s sh select.sh
#? 3
total used free shared buffers cached
Mem: 1020328 943736 76592 0 86840 263624
-/+ buffers/cache: 593272 427056
Swap: 2097144 44196 2052948
#?
我們發現,select會默認把序號對應的命令列出來,每次輸入一個數字,則會執行相應的命令,命令執行完後並不會退出腳本。它還會繼續讓我們再次輸如序號。序號前面的提示符,我們也是可以修改的,利用變量PS3即可,再次修改腳本如下:
- #!/bin/bash
- PS3="Please select a number: "
- echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
- echo
- select command in w top free quit
- do
- case $command in
- w)
- w
- ;;
- top)
- top
- ;;
- free)
- free
- ;;
- quit)
- exit
- ;;
- *)
- echo "Please input a number:(1-4)."
- esac
- done
如果想要腳本每次輸入一個序號後就自動退出,則需要再次更改腳本如下:
- #!/bin/bash
- PS3="Please select a number: "
- echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
- echo
- select command in w top free quit
- do
- case $command in
- w)
- w;exit
- ;;
- top)
- top;exit
- ;;
- free)
- free;exit
- ;;
- quit)
- exit
- ;;
- *)
- echo "Please input a number:(1-4).";exit
- esac
- done
補充:
case ... esac 與其他語言中的 switch ... case 語句類似,是一種多分枝選擇結構。
case 語句匹配一個值或一個模式,如果匹配成功,執行相匹配的命令。case語句格式如下:case 值 in
模式1)
command1
command2
command3
;;
模式2)
command1
command2
command3
;;
*)
command1
command2
command3
;;
esac
case工作方式如上所示。取值後面必須爲關鍵字 in,每一模式必須以右括號結束。取值可以爲變量或常數。匹配發現取值符合某一模式後,其間所有命令開始執行直至 ;;。;; 與其他語言中的 break 類似,意思是跳到整個 case 語句的最後。
取值將檢測匹配的每一個模式。一旦模式匹配,則執行完匹配模式相應命令後不再繼續其他模式。如果無一匹配模式,使用星號 * 捕獲該值,再執行後面的命令。