Generating Random Numbers via Linux Terminal

Generating random numbers is very useful in different scenarios such as when trying to create a password. In Linux, there are different methods to generate random numbers with some scripts.

Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Linux System queries.

In this context, we shall look into the different ways to generate random numbers through Linux terminals.


1. Using $RANDOM variable

You can use the $RANDOM variable to generate random numbers within the range of 0 and 32767. It is a built-in shell variable to generate the random number. To create random numbers, run the below command:

$ echo $RANDOM


2. Generate random number between the chosen range

With the small tweak on a command, you are able to generate random numbers between the chosen range. To generate a random number between the range 0 to 30, you have to run the below command:

$ a=$(( $RANDOM % 31 ))
$ echo $a

Another way to generate a random number between 0 to 100, you have to run the below command:

$ echo $(( $RANDOM % 101 ))


3. Generate random number using the script

With the use of bash scripting, random numbers can also be easily generated. It is also a bit fun to write the script for such a purpose. An example of a script to generate a random number is shown below:

$ sudo vim randomnumber.sh
#!/bin/bash
echo "Enter the smallest number:"
read smallest
echo "Enter the largest number:"
read largest
if [[ $largest < $smallest ]]; then
echo "Your provided numbers is not valid"
exit 1
fi
change=$(( $largest-$smallest ))
if [[ $change == 1 ]]; then
echo "Range between the numbers must be more than 1"
exit 1
fi
randomnumber=$(( $RANDOM % $largest + 1))
echo "The random number is: $randomnumber"

You can run this script with the below command:

$ ./randomnumber.sh

With such a script, you are able to generate random numbers between the range provided by you.


4. Using the shuf command

shuf command provide a way to generate random numbers between the ranges. 

To generate the random number between the range 7 and 57, run the below command:

$ shuf -i 7-57 -n1


5. Using tr command with urandom

To generate the random number with "n" number of digits, you can pull numbers from the /dev/urandom stream with the use of tr command. Suppose to generate a random number with 3 and 7 digits, you have to run the below command:

$ tr -cd "[:digit:]" < /dev/urandom | head -c 3
$ tr -cd "[:digit:]" < /dev/urandom | head -c 7


[Need help in fixing Linux system issues ? We can help you. ]

This article covers how to generate random numbers with a small command on the terminal or by creating the script.

Related Posts