Bash shell 中,select 使用舉例

Bash shell 中,select 使用舉例

一 背景

在最近的運維工作中,寫了很多腳本,在寫這些腳本時發現了一些高效的用法,現將 select 的用法簡單介紹一下。

二 使用舉例

select 表達式是 bash 的一種擴展應用,擅長於交互式場合。用戶可以從一組不同的值中進行選擇。格式如下:

select var in ... ; do
    ...
done

2.1 單獨使用 select

#!/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

運行結果展示:

[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!

腳本中增加了一個判斷,如果選擇的主機不在指定範圍,那麼結束本次執行。

2.2 結合 case 使用

#!/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

運行結果展示:

[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 的值是:"#?"。

三 總結

3.1 select 看起來似乎不起眼,但是在交互式場景中卻非常有用,各種用法希望大家多多總結。

3.2 文章中還涉及到了 bash shell 中判斷值是否在數組中的用法。

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