Generating random strings in Bash
I needed to generate some random strings in a Bash script, here’s how I ended up doing it.
As with all Bash tricks, one line gets the job done:
$ tr -dc [:alnum:] < /dev/urandom | head -c "${len}"
This command gets random bits from /dev/urandom
and deletes (-d
) all
characters that are not (-c
) in a letters and digits set ([:alnum:]
). The
head
command is to limit the output to $len
bytes (characters in this
case).
Before getting to this solution, I used a more pedestrian script:
alphabet="abcdefghijklmnopqrstuvwxyz1234567890"
len=5
str=""
for i in $(seq 1 ${len}); do
char="${alphabet:${RANDOM} % ${#alphabet}:1}"
str="${str}${char}"
done
We first define all characters to choose from, then pick one randomly as many times as the length of the final string.
The trick is picking the random character. Here we use
substring expansion
(${variable:offset:length}
) to select only one character from our alphabet
(the length
is 1
). The offset
is calculated as a random number
(${RANDOM}
) modulo our alphabet
length (${#alphabet}
).
In substring expansions, both offset
and length
are arithmetic expressions,
that’s why we can calculate RANDOM % #alphabet
in there.