在最近的運維工做中,寫了不少腳本,在寫這些腳本時發現了一些高效的用法,現將 select 的用法簡單介紹一下。shell
select 表達式是 bash 的一種擴展應用,擅長於交互式場合。用戶能夠從一組不一樣的值中進行選擇。格式以下:數組
select var in ... ; do ... done
#!/bin/bash Hostname=( 'host1' 'host2' 'host3' ) select host in ${Hostname[@]}; do if [[ "${Hostname[@]/${host}/}" != "${Hostname[@]}" ]] ; then echo "You select host: ${host}"; else echo "The host is not exist! "; break; fi done
運行結果展現:bash
[root@gysl ~]# sh select.sh 1) host1 2) host2 3) host3 #? 1 You select host: host1 #? 2 You select host: host2 #? 3 You select host: host3 #? 2 You select host: host2 #? 3 You select host: host3 #? 1 You select host: host1 #? 6 The host is not exist!
腳本中增長了一個判斷,若是選擇的主機不在指定範圍,那麼結束本次執行。運維
#!/bin/bash Hostname=( 'host1' 'host2' 'host3' ) PS3="Please input the number of host: " select host in ${Hostname[@]}; do case ${host} in 'host1') echo "This host is: ${host}. " ;; 'host2') echo "This host is: ${host}. " ;; 'host3') echo "This host is: ${host}. " ;; *) echo "The host is not exist! " break; esac done
運行結果展現:ide
[root@gysl ~]# sh select.sh 1) host1 2) host2 3) host3 Please input the number of host: 1 This host is: host1. Please input the number of host: 3 This host is: host3. Please input the number of host: 4 The host is not exist!
在不少場景中,結合 case 語句使用顯得更加方便。上面的腳本中,從新定義了 PS3 的值,默認狀況下 PS3 的值是:"#?"。code
3.1 select 看起來彷佛不起眼,可是在交互式場景中卻很是有用,各類用法但願你們多多總結。input
3.2 文章中還涉及到了 bash shell 中判斷值是否在數組中的用法。it