使用shell建立一個簡單的選單bash select用法
寫指令碼的時候會碰到建立互動式選單的情況,比如碰到寫一個lnmp一鍵安裝指令碼的時候會讓使用者選擇安裝mysql的版本或者選擇安裝各種元件,總之在建立選單是很常見的。
而select是bash的一種擴充套件應用,讓使用者可以在一組不同的值中選擇,類似下面
This is a menu Test Please Choose what you want 1) bugger 2) linux: #?
之後你就輸入前面的選單選擇就是了
例項程式碼
上面要注意幾個地方,select這個迴圈內容裡面包含的是選擇之後要執行的東西REPLY這個變數就是你選擇的選單的號碼,其實不難,比如再比如下面
#!/bin/bash ubuntu(){ echo "This is ubuntu func" } fedora(){ echo "This is fedora func" } centos(){ echo "This is centos func" } arch(){ echo "This is arch func" } echo "Please select your favorite linux distribution" linux_distributions="Ubutnu Fedora Centos Arch" select linux_distribution in $linux_distributions: do case $REPLY in 1) ubuntu ;; 2) fedora ;; 3) centos ;; 4) arch ;; *) echo "please choose 1-4" ;; esac done
執行結果
Please select your favorite linux distribution 1) Ubutnu 2) Fedora 3) Centos 4) Arch: #? 1 This is ubuntu func #? 2 This is fedora func #? 3 This is centos func #? 4 This is arch func #? 5 please choose 1-4 #? 6 please choose 1-4 #?
要注意的地方
select可能有的shell會報錯,比如zsh
./test.sh: 9: ./test.sh: select: not found
其實只要指定shell去執行就可以
bash + 要執行的指令碼
歡迎關注Bboysoul的部落格www.bboysoul.com
Have Fun