views:

173

answers:

1

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

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

+2  A: 

Change the line where you define selectedexpression to

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

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

JacobM
Thanks ^^ it worked great
Time Machine
Note that that code will still be biased towards the lower array indexes.
Joey
True. However, unless your list of expressions is very long, the effect is minor. $RANDOM is a number between 0 and 32767. Say you had 100 items in your list. The first 67 items would have a 328/32767 (.01001) chance, while the last 33 would have a 327/32767 (.00998) chance. For a shorter list the difference would be even less. Still, you make a good point, and the shell RANDOM function is not suitable for situations where you must have truly random numbers, such as cryptography.
JacobM