[ACCEPTED]-Pick and print one of three strings at random in Bash script-random

Accepted answer
Score: 30

To generate random numbers with bash use 8 the $RANDOM internal Bash function:

arr[0]="2 million"
arr[1]="1 million"
arr[2]="3 million"

rand=$[ $RANDOM % 3 ]
echo ${arr[$rand]}

From bash manual 7 for RANDOM:

Each time this parameter is referenced, a 6 random integer between 0 and 32767 is 5 generated. The sequence of random numbers 4 may be initialized by assigning a value 3 to RANDOM. If RANDOM is unset,it loses 2 its special properties, even if it 1 is subsequently reset.

Score: 9

Coreutils shuf

Present in Coreutils, this function works well if 5 the strings don't contain newlines.

E.g. to 4 pick a letter at random from a, b and c:

printf 'a\nb\nc\n' | shuf -n1

POSIX eval array emulation + RANDOM

Modifying 3 Marty's eval technique to emulate arrays (which 2 are non-POSIX):

a1=a
a2=b
a3=c
eval echo \$$(expr $RANDOM % 3 + 1)

This still leaves the RANDOM non-POSIX.

awk's 1 rand() is a POSIX way to get around that.

Score: 5

64 chars alpha numeric string

randomString32() {
    index=0
    str=""

    for i in {a..z}; do arr[index]=$i; index=`expr ${index} + 1`; done
    for i in {A..Z}; do arr[index]=$i; index=`expr ${index} + 1`; done
    for i in {0..9}; do arr[index]=$i; index=`expr ${index} + 1`; done
    for i in {1..64}; do str="$str${arr[$RANDOM%$index]}"; done

    echo $str
}

0

Score: 1
~.$ set -- "First Expression" Second "and Last"
~.$ eval echo \$$(expr $RANDOM % 3 + 1)
and Last
~.$ 

0

Score: 0

Want to corroborate using shuf from coreutils 4 using the nice -n1 -e approach.

Example usage, for 3 a random pick among the values a, b, c:

CHOICE=$(shuf -n1 -e a b c)
echo "choice: $CHOICE"

I looked 2 at the balance for two samples sizes (1000, and 1 10000):

$ for lol in $(seq 1000); do shuf -n1 -e a b c; done > shufdata
$ less shufdata | sort | uniq -c
    350 a
    316 b
    334 c
$ for lol in $(seq 10000); do shuf -n1 -e a b c; done > shufdata
$ less shufdata | sort | uniq -c
   3315 a
   3377 b
   3308 c

Ref: https://www.gnu.org/software/coreutils/manual/html_node/shuf-invocation.html

More Related questions