Linux bash provides different ways to generate random numbers. Random numbers can be used for different cases like security, selection, generating random content, etc. Linux bash can be used to generate random numbers by using the operating system devices, commands, etc.
Using the $RANDOM Environment Variable
The bash shell provides the
$RANDOM environment variable which returns a random number every time it is called. The echo command can be used to print random numbers using the $RANDOM variable like below.
$ echo $RANDOM
The generated random number can be assigned into a variable easily using the bash assignment operator. In the following example, we generate a random number using the $RANDOM variable and set it to the variable named “r”.
The $RANDOM environment variable returns a wide range of random numbers. We can limit the end of the random number using the module operator like below. In the following example, we limit the end of the random as “20”.
$ echo $(($RANDOM%20))
Using /dev/random Device
Linux provides the
/dev/random as a device that provides random data when consumed. This random device can be used to generate random data. But the generated data is in hexadecimal format and should be formatted into decimal values. The od command can be used to format generated random data into decimal format.
$ od -A n -t d -N 1 /dev/urandom
Using shuf Command
shuf command is used to shuffle provided list. The shuf command can be used to generate random numbers by providing the low and high limits about the list and select one of the values in a random way. In the following example, we generate a random number between “10” and “20”.
$ shuf -i 10-20 -n 1