用於 grep 字串並將其放入數組的 Bash 腳本

用於 grep 字串並將其放入數組的 Bash 腳本

我正在尋找製作bash 腳本的方法,該腳本可以grep 命令輸出並將字串放入數組中,並且能夠從數組中隨機選擇1 個字串(例如每分鐘)並將其放置為變量,隨機選擇的時間需要是可設定的。

Command output:
string
string2
string3

將所有這些字串放入數組中,並隨機選擇其中一個並將其作為變量

desired result:
strings -> array <- randomly selecting from array every 1 minute and placing string selected as variable for further use 

答案1

在 bash 中,您可以使用readarray命令替換來將換行符號分隔的輸出捕獲到陣列中;例如:

readarray -t outputs < <(seq 10)

我曾經用來seq 10產生一些輸出的地方。這導致:

$ declare -p outputs
declare -a outputs='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5" [5]="6" [6]="7" [7]="8" [8]="9" [9]="10")'

每分鐘偽隨機選出其中一個元素:

while :
do
  element=$(( RANDOM % ${#outputs[@]} ))
  var=${outputs[$element]}
  sleep 60
done

請注意,bash 數組從索引零開始,$(( ))算術表示使用數組$RANDOM中元素數量的模值outputs

相關內容