FUNDAMENTALS A Complete Guide for Beginners
Generating random number in Bash is required for many applications. This is particularly useful for data encryption and simulation purposes. There are several ways to generate random numbers in Bash. In this article, I will talk about the various commands and variables for random number generation.
What is Random Number?
A random number is nothing but a number that is chosen randomly from a set of numbers. Randomness is the quality of picking a number with higher unpredictability without following any pattern or principle. Every physical phenomenon is some sort of random in nature. Despite its abundance, it was not easy to generate random numbers at scale. The RAND Corporation first created an application that can generate random numbers using a random pulse generator.
But nowadays most computers generate random numbers using mathematical formulas which are predictable by that formula. So computer-generated random numbers are often referred to as pseudorandom numbers. Sometimes pseudorandom number generators take a seed value. A seed in Random Number Generation (RNG) is like a starting point that controls the sequence of pseudo-random numbers. Setting the seed ensures reproducibility so that users can use the same sequence of random numbers again and again for a simulation or any other task. RNG uses default values, often from the system clock if the seed is not set.
7 Easy Ways to Generate Random Number in Bash
Bash has its own built-in RANDOM variable for generating random numbers. One can also use external tools like awk for generating random numbers in Bash. In addition, scripts of other languages can be executed in Bash to generate random numbers. Let’s explore all the techniques one by one.
1. Using “RANDOM” Environment Variable
The RANDOM variable is a special variable that can generate pseudorandom integers in the range 0 to 32767. For example:
echo $RANDOM
You can also set a range to generate a random integer within that specified range. Now, let’s generate a random integer within the range of 0 to 100:
#!/bin/bash
# Get user input for minimum and maximum values
read -p "Enter the minimum value: " min
read -p "Enter the maximum value: " max
# Generate and print the random number
random_number=$(($RANDOM % ($max - $min + 1) + $min))
echo "Random number between $min and $max: $random_number"
This script first prompts the user using read -p
command to provide a minimum and a maximum value and store them in the min and max variables respectively. These values are used to determine the range within which a random number will be generated.
Then the script generates a random integer using the $RANDOM variable. The modulo % operator finds the remainder when the generated integer is divided by ($max - $min + 1)
. Adding the minimum value with the remainder ensures that the final random number falls within the specified range.
Here, the lower value of the range is 0 and the upper value of the range is 100. The program generates a random integer 46 that falls within the given range.
Here’s a cool trick to get a random number with a specific number of digits. You can use parameter expansion for this purpose. For instance, ${RANDOM:0:3}
generates a three-digit random number. RANDOM gives a random number between 0 and 32767. Whatever it generates, 0:3 extracts the first three digits of the generated number, which is also random. Let’s say:
echo ${RANDOM:0:3}
In the first execution, the command generated 110 and the next time it generated 120. Both are three-digit numbers.
2. Using “SRANDOM” Variable
The SRANDOM variable can be an alternative to the RANDOM variable. It generates random integers using the system’s entropy engine. With this variable, you can generate random integers within a specified range with reasonable randomness. For instance:
echo $((0 + SRANDOM % 100))
The expression 0 + SRANDOM % 100
generates a random integer using SRANDOM, and the modulo operator ensures that the result falls within the range of 0 to 99. Adding 0 is for keeping the random number within this range. You are open to replacing 0 and 100 with your intended minimum and maximum values of the range. I ran the command two times in the terminal. The first time, it generates 7 and the second time it generates 37.
3. Using “dev/urandom” System File
The dev/urandom is not a regular file rather it is a character device according to POSIX naming. Whenever a program reads the file a driver in the kernel determines the appropriate result. The driver uses various sources of random data to interact with the program and generate a return. When reading the file with the od command it returns a random number. Check the following command:
od -An -N2 -d /dev/urandom
The “-An” option in the od command displays the result without any offset information. “-N2” option extracts 2 bytes of random data from the /dev/urandom
device and prints them in unsigned decimal format using “-d” option.
Since the generated output is two bytes, the range of possible values is from 0 to 65535 (2^16 – 1) inclusive.
You can see the random numbers in the image generated by the above code. You can also adjust the option “-N” to change the range.
4. Utilizing “shuf” Command
The shuf command, short for shuffle, is primarily used to randomly reorder a list of numbers provided after the -e option. Here, the -e option allows to provide inputs directly on the command line.
shuf -e 1 2 20 4 12
Moreover, it can also be used to choose or generate random numbers within a specified range. You can easily define the range using the -i option. Besides, the -n option is used to define the count of random integers within the specified range. Look at the following script for a clear idea:
#!/bin/bash
# Get user input for minimum and maximum values
read -p "Enter the minimum value: " min
read -p "Enter the maximum value: " max
# Generate and print the random number
random_number=$((shuf -i "$min"-"$max" -n 1))
echo "Random number between $min and $max: $random_number"
The script takes the maximum and minimum values of the range for generating a random integer within that range. Then it uses the shuf command with the -i option to define the range utilizing the user’s entered minimum and maximum values. The -n 1 specifies to generate only one random number in that range.
If your task requires to generate random integers more than one, you can specify that after the -n option. Look at the following two commands where I will generate 2 and 6 random integers respectively within the 0 to 100 range:
shuf -i "$min"-"$max" -n 2
shuf -i "$min"-"$max" -n 6
The first command generates two random numbers 83 and 93. Similarly, the second command generates six random numbers within the range of 0 to 100 as you can see in the image.
5. Using “awk” Command
The awk command is a popular text-processing utility. However, it supports a wide variety of functions. The rand function in awk can be used to generate random numbers. Moreover one can set different seed values to reproduce the same sequence of random numbers using this command.
To generate random numbers using the awk command check the below script:
#!/bin/bash
# Get user input for minimum and maximum values
read -p "Enter the minimum value: " min
read -p "Enter the maximum value: " max
# Generate and print the random number using awk
random_number=$(awk "BEGIN{srand(); print int(rand()*($max-$min+1))+$min}")
echo "Random number between $min and $max: $random_number"
This script prompts the user to input minimum and maximum values to specify a range. It utilizes the srand() and rand() functions within the BEGIN block to initialize the random number generator and return a random integer within the user-defined range.
The generated random number is then stored in a variable and later displayed using the echo command.
#!/bin/bash
# Get user input for minimum and maximum values
read -p "Enter the minimum value: " min
read -p "Enter the maximum value: " max
# Generate and print the random number using awk
random_number=awk -v seed=$RANDOM "BEGIN{srand(seed); print int(rand()*($max-$min+1))+$min}"
echo "Random number between $min and $max: $random_number"
The script randomly takes the seed value in the srand function using the RANDOM variable with the -v option. The awk command generates a random number using the rand() function. Then the int() function converts the generated random number into the nearest integer.
Now let’s learn to create a non-integer random number using the awk command:
#!/bin/bash
# Get user input for minimum and maximum values
read -p "Enter the minimum value: " min
read -p "Enter the maximum value: " max
# Generate and print the random number using awk
random_number=$(awk "BEGIN{srand(); print min + rand() * (max - min)}")
echo "Random number between $min and $max: $random_number"
This time the script didn’t convert the generated random number into the nearest integer. So it will be a floating point number within the given range.
6. Using Python “random” Library in Bash
Python random library can generate random numbers with higher randomness. Fortunately you can use the library as well as other Python functionality in Bash using the python2 or python3 command. To create random numbers using the random() function of the random library:
python3 -c "import random; print(random.random())"
By default, the random() function creates random numbers in the range of 0 to 1. If you want to generate random integers you can use randint() function of the random library. Moreover, you can provide a range in the randint function. Let’s try to create a random integer within the range of 1 to 10:
python3 -c "import random; print(random.randint(1, 10))"
Here the randomly generated integers are 10 and 4 respectively. Keep in mind that the random integers created in this way include range values.
There is another function in the random library called randrange. It takes three arguments start, stop, and step to generate random numbers. One can generate random numbers from a uniformly distributed list using this function. Now, I am creating a random number from the list of 0 to 100 with a stepsize 5:
python3 -c "import random; print(random.randrange(0, 100, 5))"
Here the generated random numbers are 45 and 85. Both numbers are within the range of 0 to 100 and also comply with the given step size.
7. Using “perl” Code in Bash Shell
One can use perl code in Bash shell using the perl command. The -e option is useful to execute perl code in a Bash shell. The rand function in perl can generate random numbers within a given range. Look at the following example:
perl -e "print rand(), \"\n\""
Like Python, the rand() function in perl generates a random number between 0 to 1. But one can define the range within the function. For instance, rand(100) will create a random number within the range of 0 to 100:
perl -e "print rand(100), \"\n\""
Each time the rand() function generates floating-point random numbers. To generate integer random numbers use the int() function to convert the floating point numbers into integers.
perl -e "print int(rand(100)), \"\n\""
Here, the generated random number is converted to an integer by the int function. The generated random integer is 96.
Furthermore, the rand function can take the lower limit of a range as well. Look at the following script where the user can provide range values:
#!/bin/bash
# Get user input for minimum and maximum values
read -p "Enter the minimum value: " min
read -p "Enter the maximum value: " max
# Run the Perl code to generate and print a random number
random_number=$(perl -e "print int(rand($max-$min+1)) + $min")
echo "Random number between $min and $max: $random_number"
The script takes the maximum and minimum values of the range for generating a random integer within that range.
The rand function creates a random floating point number between 0
and $max-$min+1
(inclusive). The int function rounds down the floating-point number to the nearest integer. The minimum value of the range adds to the result to keep the random within the range.
The user provides 0 and 100 as the minimum and maximum of the range. The generated random number within the given range is 56.
How to Get an Array of Random Numbers in Bash
For a proper simulation sometimes it needs to generate a huge array of random numbers. To create an array of random numbers one can use any method of generating random numbers with a for loop. However, it may not ensure high-quality randomness as it pulls numbers from the same sample on each iteration. Check out the below script for the practical overview:
#!/bin/bash
# Specify the length of the array
array_length=10
# Initialize an empty array
random_numbers=()
# Populate the array with random numbers
for ((i = 0; i < array_length; i++)); do
random_numbers+=("$((RANDOM % 100))")
done
# Print the generated array
echo "Random Numbers: ${random_numbers[@]}"
The script has a predefined array length which is 10. Then it initializes a for loop for generating random numbers using RANDOM variable within the range of 0 to 99.
It then stores the random numbers in an array called random_numbers and displays the entire array using array expansion ${random_numbers[@]}
.
I executed the script twice for a better visualization. Each time it printed an array of random numbers from 0 to 99 which contained 10 elements.
Conclusion
In conclusion, generating random numbers in Bash is fairly simple. You can adapt various functionality and generate random numbers within a range with random seed values. Hope this article helped to understand the ways of generating random numbers in Bash.
People Also Ask
What are the applications of random numbers?
Random numbers have many practical uses, especially in security. They’re essential for creating secure encryption keys and generating random passwords. Additionally, random numbers help system admins to distribute workloads across servers, a process known as load balancing.
How to randomly shuffle a string in Bash?
To randomly shuffle a string in Bash use the shuf command. For instance, take the string "hidden_message"
. The following command can randomly shuffle the characters of the string.
echo "$(echo "hidden_message" | grep -o . | shuf | tr -d '\n')"
The grep command is used to match each character of the string then it is passed to the shuf command. The shuf command shuffles the characters randomly. Finally, the tr command removes any newline characters.
How to read N random characters from /dev/urandom?
Change the value of the -N option in the following code to read different numbers of characters from the /dev/urandom file. Here, N4 generates four bytes of unsigned random decimals:
od -vAn -N4 -tu4 < /dev/urandom
Moreover, the head command can be used to read a specific number of characters from the /dev/urandom
file. To read the first 10 characters use the following code:
head -c 10 /dev/urandom
How to randomly pick up lines from a file in Bash?
To randomly pick up lines from a file use the shuf command. Look at the following file which contains a few movie names each in a newline: Now, to randomly pick up two lines or two movie names use the following code:
shuf -n 2 movies.txt
Here, -n 2 tells the shuf command to randomly pick two lines from the movies.txt
file.
Are random numbers generated by RANDOM variable inclusive of range?
Yes. When someone defines a range to generate random numbers using the RANDOM variable, the generated random numbers can be the range values as well. Look at the following code to generate random numbers within the range of 80 to 100:
echo $(($RANDOM % (100 - 80 + 1) + 80))
This can generate numbers 80 or 100 along with the in-between integers. Let’s run the command until it returns one of the range values. In the 5-th run, the code generates 100 which is one of the range values.
Related Articles
- Performing Math Operations in Bash [12+ Commands Explained]
- How to Calculate in Bash [3 Practical Examples]
- How to Sum Up Numbers in Bash [Explained With Examples]
- How to Divide Two Numbers in Bash [8 Easy Ways]
- Division of Floating Point Numbers in Bash
- How to Use “Mod” Operator in Bash [5 Basic Usage]
- How to Format Number in Bash [6 Cases]
- How to Convert Hexadecimal Number to Decimal in Bash
- [Solved] “binary operator expected” Error in Bash
- [Fixed] “integer expression expected” Error in Bash
<< Go Back to Arithmetic Operators in Bash | Bash Operator | Bash Scripting Tutorial