如何从 shell 中的数组中选择一个随机项

我正在用 Shell Script 创建一个机器人:

# Array with expressions
expressions=("Ploink Poink" "I Need Oil" "Some Bytes are Missing!" "Poink Poink" "Piiiip Beeeep!!" "Hello" "Whoops! I'm out of memmory!")


# Seed random generator
RANDOM=$$$(date +%s)


# Loop loop loop loop loop loop ...
while [ 1 ]
do
# Get random expression...
selectedexpression=${expressions[$RANDOM % ${#RANDOM[*]}]}


# Write to Shell
echo $selectedexpression




# Wait an half hour
sleep 1 # It's one second for debugging, dear SOers
done

我要它每秒从 expressions上打印一个随机项目。我试过这个,但它不工作。它每次只打印第一个(Ploink Poink)。有人能帮帮我吗? 谢谢

62578 次浏览

将定义 selectedexpression的行更改为

selectedexpression=${expressions[ $RANDOM % ${#expressions[@]} ]}

您希望 expression中的索引是一个从0到 expression数组长度的随机数。这个可以。

下面是另一个可能比 Jacob Mattison 的解决方案更随机的解决方案(很难从 jot手册中说出来) :

declare -a expressions=('Ploink' 'I Need Oil' 'Some Bytes are Missing' 'Poink Poink' 'Piiiip Beeeep' 'Hello' 'Whoops I am out of memory')
index=$( jot -r 1  0 $((${#expressions[@]} - 1)) )
selected_expression=${expressions[index]}
arr[0]="Ploink Poink"
arr[1]="I Need Oil"
arr[2]="Some Bytes are Missing!"
arr[3]="Poink Poink"
arr[4]="Piiiip Beeeep!!"
arr[5]="Hello"
arr[6]="Whoops! I'm out of memmory!"
rand=$[$RANDOM % ${#arr[@]}]
echo $(date)
echo ${arr[$rand]}

使用 shuf 的解决方案:

expressions=("Ploink Poink" "I Need Oil" "Some Bytes are Missing!" "Poink Poink" "Piiiip Beeeep!!" "Hello" "Whoops! I'm out of memmory!")
selectedexpression=$(printf "%s\n" "${expressions[@]}" | shuf -n1)
echo $selectedexpression

或者可能更好:

select_random() {
printf "%s\0" "$@" | shuf -z -n1 | tr -d '\0'
}


expressions=("Ploink Poink" "I Need Oil" "Some Bytes are Missing!" "Poink Poink" "Piiiip Beeeep!!" "Hello" "Whoops! I'm out of memmory!")
selectedexpression=$(select_random "${expressions[@]}")
echo "$selectedexpression"

随机的

1.

rand=("q" "w")
r=$(shuf -i 0-${#jndi[@]} -n 1)
echo ${rand[$r]}
echo `$((1 + $RAND % 5))` // **for number between 1..5**