从数组中选择一个随机项

时间:2010-03-05 17:01:54

标签: arrays shell random

我在Shell脚本中创建一个机器人:

# 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)。谁能帮我吗? 感谢

3 个答案:

答案 0 :(得分:73)

将您定义selectedexpression的行更改为

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

您希望expression的索引是从0到expression数组长度的随机数。这样就可以了。

答案 1 :(得分:16)

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]}

答案 2 :(得分:4)

这是另一种解决方案,可能比雅各布·马蒂森的解决方案更加随机(很难从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]}