Random elements from array

Hi
I wanted to print random elements from an array at bash shell
I use the following code, but I always see first element getting printed

#!/bin/bash
c=1
expressions=(pink red white yellow purple)
while [[ $c -le 9 ]]; do
echo "The value of RANDOM is $RANDOM"
selectedexpression=${expressions[$RANDOM % ${#RANDOM
[*]}]};
echo "***** The option is $selectedexpression"
sleep 1
((c++))
 done

The output as follows:

The value of RANDOM is 10813
***** The option is pink
The value of RANDOM is 30688
***** The option is pink
The value of RANDOM is 9752
***** The option is pink
The value of RANDOM is 2170
***** The option is pink
The value of RANDOM is 4010
***** The option is pink
The value of RANDOM is 31161
***** The option is pink
The value of RANDOM is 2046
***** The option is pink
The value of RANDOM is 5365
***** The option is pink
The value of RANDOM is 26738
***** The option is pink

I tried changing the sleep values till 7 but still only first element gets printed..
Please help:confused:

Hi.

For ${#RANDOM[*]} , where do you define array RANDOM?

Best wishes ... cheers, drl

Is it possible your intention was sth like

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

?

Since your modifiying the $RANDOM with the length(count) of its array items, and since $RANDOM has only one, only the first items is displayed.

Hope this helps

I have used date command to seed random value

#!/bin/bash
c=1
RANDOM=$$$(date +%s)
expressions=(pink red white yellow purple)
while [[ $c -le 9 ]]; do
echo "The value of RANDOM is $RANDOM"
selectedexpression=${expressions[$RANDOM % ${#RANDOM
[*]}]};
echo "***** The option is $selectedexpression"
sleep 1
((c++))
 done

Hi Priya,
You still need to change:

selectedexpression=${expressions[$RANDOM % ${#RANDOM[*]}]};

to:

selectedexpression=${expressions[$RANDOM % ${#expressions[*]}]};

And, note that $RANDOM is reevaluated each time it is expanded. So the value printed by:

echo "The value of RANDOM is $RANDOM"

and the value used in:

selectedexpression=${expressions[$RANDOM % ${#expressions[*]}]};

have a VERY small chance of being the same value. If you want to print and use the same pseudo-random number, you need something more like:

rn="$RANDOM"
echo "The value of RANDOM is $rn"
selectedexpression=${expressions[$rn % ${#expressions[*]}]};