寫腳本的時候會碰到建立交互式菜單的狀況,好比碰到寫一個lnmp一鍵安裝腳本的時候會讓用戶選擇安裝mysql的版本或者選擇安裝各類組件,總之在建立菜單是很常見的。mysql
而select是bash的一種擴展應用,讓用戶能夠在一組不一樣的值中選擇,相似下面linux
This is a menu Test Please Choose what you want 1) bugger 2) linux: #?
以後你就輸入前面的菜單選擇就是了sql
#!/bin/bash echo "Please select your favorite linux distribution" linux_distributions="Ubutnu Fedora Centos Arch" select linux_distribution in $linux_distributions: do echo "you selected $REPLY $linux_distribution" done
上面要注意幾個地方,select這個循環內容裏面包含的是選擇以後要執行的東西REPLY這個變量就是你選擇的菜單的號碼,其實不難,好比再好比下面shell
#!/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
執行結果ubuntu
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
centos
其實只要指定shell去執行就能夠bash
bash + 要執行的腳本
code
歡迎關注Bboysoul的博客www.bboysoul.com Have Funblog