如何在shell中从数组中选择随机项

2lpgd968  于 2023-01-05  发布在  Shell
关注(0)|答案(5)|浏览(218)

我在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)。有人能帮我吗?谢谢

6mzjoqzu

6mzjoqzu1#

将定义selectedexpression的行更改为

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

你希望expression的索引是一个从0到expression数组长度的随机数,这就可以做到。

bz4sfanl

bz4sfanl2#

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

e0uiprwp3#

下面是另一个可能比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]}
dw1jzc5e

dw1jzc5e4#

使用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"
q43xntqr

q43xntqr5#

对于随机
1.

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

相关问题