shell 中select 的用法

shell中的select用法

 分享 

select也是循環的一種,它比較適合用在用戶選擇的情況下。
比如,我們有一個這樣的需求,運行腳本後,讓用戶去選擇數字,選擇1,會運行w命令,選擇2運行top命令,選擇3運行free命令,選擇4退出。腳本這樣實現:

  1. #!/bin/bash
  2. echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
  3. echo
  4. select command in w top free quit
  5. do
  6.     case $command in
  7.     w)
  8.         w
  9.         ;;
  10.     top)
  11.         top
  12.         ;;
  13.     free)
  14.         free
  15.         ;;
  16.     quit)
  17.         exit
  18.         ;;
  19.     *)
  20.         echo "Please input a number:(1-4)."
  21.         ;;
  22.     esac
  23. 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即可,再次修改腳本如下:

  1. #!/bin/bash
  2. PS3="Please select a number: "
  3. echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
  4. echo
  5.  
  6. select command in w top free quit
  7. do
  8.     case $command in
  9.     w)
  10.         w
  11.         ;;
  12.     top)
  13.         top
  14.         ;;
  15.     free)
  16.         free
  17.         ;;
  18.     quit)
  19.         exit
  20.         ;;
  21.     *)
  22.         echo "Please input a number:(1-4)."
  23.     esac
  24. done

如果想要腳本每次輸入一個序號後就自動退出,則需要再次更改腳本如下:

  1. #!/bin/bash
  2. PS3="Please select a number: "
  3. echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
  4. echo
  5.  
  6. select command in w top free quit
  7. do
  8.     case $command in
  9.     w)
  10.         w;exit
  11.         ;;
  12.     top)
  13.         top;exit
  14.         ;;
  15.     free)
  16.         free;exit
  17.         ;;
  18.     quit)
  19.         exit
  20.         ;;
  21.     *)
  22.         echo "Please input a number:(1-4).";exit
  23.     esac
  24. 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 語句的最後。

取值將檢測匹配的每一個模式。一旦模式匹配,則執行完匹配模式相應命令後不再繼續其他模式。如果無一匹配模式,使用星號 * 捕獲該值,再執行後面的命令。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章