如何从shell中的数组中选择随机项目 [英] How to select a random item from an array in shell

查看:36
本文介绍了如何从shell中的数组中选择随机项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a bot in 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).谁能帮我吗?谢谢

I want that it prints a random item from the expressions every second. I tried this but it does not work. It only prints the first one (Ploink Poink) every time. Can anyone help me out? Thanks

推荐答案

将您定义 selectedexpression 的行更改为

Change the line where you define selectedexpression to

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

您希望 expression 的索引是一个从 0 到 expression 数组长度的随机数.这将做到这一点.

You want your index into expression to be a random number from 0 to the length of the expression array. This will do that.

这篇关于如何从shell中的数组中选择随机项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆