Bash shell 中,select 使用舉例

2021-09-16 13:50:13 字數 1945 閱讀 5584

2.2 結合 case 使用

三 總結

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

select 表示式是 bash 的一種擴充套件應用,擅長於互動式場合。使用者可以從一組不同的值中進行選擇。格式如下:

select var in

... ;

do...

done

#!/bin/bash

hostname=

('host1'

'host2'

'host3'

)select host in$;

doif[[

"$/}"

!="$"]]

;then

echo

"you select 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!

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

#!/bin/bash

hostname=

('host1'

'host2'

'host3'

)ps3=

"please input the number of host: "

select host in$;

docase$in

'host1'

)echo

"this host is: $. ";;

'host2'

)echo

"this host is: $. ";;

'host3'

)echo

"this host is: $. ";;

*)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 中判斷值是否在陣列中的用法。

bash shell 中if的用法

條件判斷的寫法 條件表示式 條件表示式 注意這裡在中開始和結尾需要空格,不然執行會出錯 例子 bin bash a 0b 1 a eq b echo a不等於b 片這裡提一下bash shell中一些需要注意的東西 1整數比較 eq 表示 ne 表示 gt 表示 lt 表示 ge 表示 le表示 2...

Bash Shell中Shift用法分享

這篇文章主要介紹了bash shell中shift的使用方法,需要的朋友可以參考下 shift可以用來向左移動位置引數。shell的名字 0 第乙個引數 1 第二個引數 2 第n個引數 n 所有引數 或 引數個數 shift預設是shift 1 例 輸出文字 開始 bin bash filename...

Bash shell 中,select 使用舉例

在最近的運維工作中,寫了很多指令碼,在寫這些指令碼時發現了一些高效的用法,現將 select 的用法簡單介紹一下。select 表示式是 bash 的一種擴充套件應用,擅長於互動式場合。使用者可以從一組不同的值中進行選擇。格式如下 select var in do done bin bash hos...