In this article we will discuss how to generate a random number from the Linux command line. There are several methods which provide different results. We will explore how to generate a random number within a range and also a specific length. In addition we will touch on seeding and a fun example of how to use random numbers in shell scripts.
Using the Builtin Bash Variable RANDOM
In the past we have discussed builtin shell variables like SECONDS. Bash also provides a shell variable named RANDOM for the express purpose of generating a random integer.
Each time this parameter is referenced, a random integer between 0 and 32767 is generated. Assigning a value to this variable seeds the random number generator.
- Bash Manual
You can seed the generator by assigning a value. This value can be the time in epoch, the PID of the current shell, or anything you like.
Example of using epoch to seed the generator:
RANDOM=$(date +%s)
Example of using the process ID of your Bash shell to seed the generator:
RANDOM=$$
Generate Random Number in Specific Range
By default the RANDOM shell variable will generate a random integer between 0 and 32767. It would not be uncommon to need to use a smaller range. If you want a user defined range, you can use the modulo operator.
To generate a random number between 0 and ten:
[savona@putor ~]$ x=$(( $RANDOM % 11 ))
[savona@putor ~]$ echo $x
2
To generate a random number between 0 and 128:
[savona@putor ~]$ x=$(( $RANDOM % 129 ))
[savona@putor ~]$ echo $x
7
Using the shuf Command to Generate a Random Number
Another way to generate a random number is by using the shuf command. The shuf command is available through the core-utils package. This should be installed by default on most moderns systems.
The shuf command accepts the -i (--input-range) option to set the low and high of a range. For example, if you wanted a number between 0 and 999 you can use -i like so:
shuf -i 0-999 -n1
The -n1 tells shuf to only return one number. Without this option, shuf would write a random permutation for each number in the range, in this case 1000 lines.
Using dev urandom to Generate a Random Number
We used /dev/urandom in our past article "5 Methods to Generate a Random Password from the Command Line". Here we will use the same method, but selecting only digits. You can use /dev/urandom with many different commands. Most of these commands are limited because there is no easy way to specify ranges. But, a different benefit is you can specify length (number of digits).
Using the tr Command with urandom
Here we are using the tr command to pull only digits from the /dev/urandom stream. We can pipe this to head and use the -c to specify the length, or amount of digits. For example, if we wanted a random number that is 6 digits long:
$ tr -cd "[:digit:]" < /dev/urandom | head -c 6
401336
Using the od Command with urandom
We can use the od command to pull randomization from /dev/urandom. This works, but is limited. We can not really specify a range or length, but we can specify the number of bytes. A single byte can be represented by a decimal number between 0-255. So we are limited to using byte decimal sizes as ranges.
$ od -A n -t d -N 1 /dev/urandom
46
Using the RANDOM Shell Variable in Bash Script
Here is an example of how to use this in a bash script.
Guess My Number Bash Script
Here is a fun exercise for those trying to learn scripting. It touches on a bunch of concepts like variables, while loops, if statements, arrays and uses a random number.
#!/bin/bash
RANDOM=$(date +%s)
MyNum=$(( $RANDOM % 51 ))
D='^[0-9]+$'
clear
echo "I have chosen a number between 0 and 50, can you guess it?"
echo -n "Enter your guess: "
while [ "$g" != "$MyNum" ]; do
read g
guessed+=("$g")
if [ "$g" = "" ] || [ "$g" -gt "50" ]; then
echo -n "Please enter a number between 0 and 50: "
elif [ "$g" == "$MyNum" ]; then
echo "You got it in ${#guessed[@]} guesses!"
elif [ "$g" -gt "$MyNum" ]; then
clear
echo "PAST GUESSES: " ${guessed[@]}
echo "Lower…"
echo -n "Try again: "
else
clear
echo "PAST GUESSES: " ${guessed[@]}
echo "Higher…"
echo -n "Try again: "
fi
done
Conclusion
We discussed several ways to generate a random number to be used in your scripts. Just as a note, these should never be used for security related processes like generating an encryption key.
If you enjoyed this article be sure to follow us on Twitter and Facebook, and subscribe to our YouTube channel.
Resources
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
3 Comments
Join Our Newsletter
Categories
- Bash Scripting (17)
- Basic Commands (50)
- Featured (7)
- Just for Fun (5)
- Linux Quick Tips (98)
- Linux Tutorials (65)
- Miscellaneous (15)
- Network Tools (6)
- Reviews (2)
- Security (32)
Don't forget please: /dev/urandom is a PSEUDO random generator.
If you need a real random number, then use /dev/random instead of it. (That could much slower than urandom)
I think that was debunked...
https://www.2uo.de/myths-about-urandom
> $ tr -cd "[:digit:]" < /dev/urandom | head -c 6
This is a nice quick way to generate random numbers in /bin/sh bourne shell, thank you.
If leading zeroes are a problem a quickndirty fix is to omit zeroes alltogether with
tr -cd '123456789'
or filter them out with piping to
sed 's/^0*//'