shell中的select用法

來源:互聯網
上載者:User

標籤: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              [email protected]   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. select command in w top free quit

  6. do

  7. case $command in

  8. w)

  9. w

  10. ;;

  11. top)

  12. top

  13. ;;

  14. free)

  15. free

  16. ;;

  17. quit)

  18. exit

  19. ;;

  20. *)

  21. echo "Please input a number:(1-4)."

  22. esac

  23. 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. select command in w top free quit

  6. do

  7. case $command in

  8. w)

  9. w;exit

  10. ;;

  11. top)

  12. top;exit

  13. ;;

  14. free)

  15. free;exit

  16. ;;

  17. quit)

  18. exit

  19. ;;

  20. *)

  21. echo "Please input a number:(1-4).";exit

  22. esac

  23. done


  shell中的select用法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.