Pick and print one of three strings at random in Bash script

To generate random numbers with bash use 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 for RANDOM:

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


Coreutils shuf

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

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

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

POSIX eval array emulation + RANDOM

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

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

This still leaves the RANDOM non-POSIX.

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


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
}

Tags:

Shell

Bash

Random