Last Updated: June 18, 2019
·
97.03K
· mwunsch

Random number generator in bash

My preferred random number generator is built right into my shell.

$ echo $RANDOM

$RANDOM is a bash function (not a constant) that returns a random signed 16 bit integer (from 0 through 32767).

You can use modulo to put some bounds on it. This line will output a random int between 0 - 9:

$ echo $(( $RANDOM % 10 ))

If you want to generate a random int between 1 - 10:

$ echo $(( $RANDOM % 10 + 1 ))

If you need something more, check out /dev/random or /dev/unrandom. From the manpage (man 4 random):

The random device produces uniformly distributed random byte values of potentially high quality.
To obtain random bytes, open /dev/random for reading and read from it.

/dev/urandom is a bunch of binary data, so you need to read it with od.

$ od -An -N4 -i < /dev/urandom

This outputs at max 4 bytes (the -N4 flag) signed decimal ints (-i) at no address (-An).

2 Responses
Add your response

Just want to note that if you take $RANDOM % 10000 the result is no longer random, but biased to the front. Since the top is 32767 (maximum positive signed integer), up to 30000 it will be even but then the first 2767 options will get used a fourth time and the last 7233 will only get used three times. Destroying whatever randomness you had from /dev/urandom.

over 1 year ago ·

Im sharing my very simplistic script that always displays 5 digit random number. It will add Zero if the generated random numbers is less than 5 characters.

function Random5digit {
unset R1
unset R2
unset R3
R1=${RANDOM}
R2=${#R1}
N4=0
N3=00
N2=000
N1=0000
case $R2 in
5)
echo $R1
;;
4)
# Concatenate Zero to make a 5 digit Random number with trailing 0
R3+=$N4$R1
echo $R3
;;
3)
R3+=$N3$R1
echo $R3
;;
2)
R3+=$N2$R1
echo $R3
;;
1)
R3+=$N1$R1
echo $R3
;;
esac
}

over 1 year ago ·