Linux generate random number

How to Generate a Random Number in Linux

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:

Example of using the process ID of your Bash shell to seed the generator:

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:

[[email protected] ~]$ x=$(( $RANDOM % 11 )) [[email protected] ~]$ echo $x 2

To generate a random number between 0 and 128:

[[email protected] ~]$ x=$(( $RANDOM % 129 )) [[email protected] ~]$ 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:

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).

Читайте также:  Linux check usb devices

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:

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='^7+$'
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 $ guesses!"
elif [ "$g" -gt "$MyNum" ]; then
clear
echo "PAST GUESSES: " $
echo "Lower…"
echo -n "Try again: "
else
clear
echo "PAST GUESSES: " $
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

Источник

Generate a random number in bash

The number that is changed in each script execution is called a random number, and it is unpredictable. The random numbers are used in the programming for various purposes, such as testing data, generating lottery tickets, generating a password, etc. The integer number or floating number can be used to generate a random number in bash. The random number of a specific range or a size can be generated using a bash script. Different ways to generate random numbers in bash have been shown in this tutorial.

Читайте также:  Lib64 ld linux x86 64 so 2 no such file or directory

Use of random generator:

The random number or a range of random numbers can be generated using the $RANDOM variable. It generates a random number between 0 and 32767 by default. But you can set the range of numbers for generating random numbers by dividing the value of $RANDOM with a specific value. Different uses of the $RANDOM variable to generate random numbers are shown in the tutorial’s next part.

Random number generation using $RANDOM variable:

The ways to generate the random number in the terminal and execute a script file are shown here.

A. Generate Random numbers from the terminal

Run the following command to generate a random number within the range 0 to 32767.

You can generate a random number of a specific range by dividing the $RANDOM variable with a particular value and getting the remainder value. Run the following command to generate a random number within the range of 1 to 50. Here, double first brackets with $ have been used.

Run the following command to generate a random number within the range of 10 to 40. Here, the third bracket with $ has been used.

B. Generate Random numbers using the script

Create a bash file with the following script to generate a random number of the specific range where the minimum and maximum range values will be taken from the user. An error message will be displayed if the taken maximum value is smaller than the minimum value. If the difference between the maximum and the minimum value is 1, another error message will be displayed. A random number will be generated in each execution of this script if the valid minimum and maximum values will be taken as input.

#!/bin/bash
# Generate a randomly based range defined by the user

#Take the lower and the upper value from the user
echo «Enter the minimum value:»
read minimum
echo «Enter the maximum value:»
read maximum

#Check the taken values are valid
if [ [ $maximum < $minimum ] ] ; then
echo «Maximum value can’t be lower than minimum value»
exit 1
fi

#Find out the difference between the numbers
diff =$ ( ( $maximum — $minimum ) )

#Check the difference value
if [ [ $diff == 1 ] ] ; then
echo «The range of numbers must be more than 1»
exit 1
fi

#Generate the random number
randomNumber =$ ( ( $minimum + $RANDOM % $maximum ) )
#Print the generated number
echo «The generated random number is: $randomNumber «

The following output will appear if the script is executed multiple times. Here, the above script has been executed three times. The error message has been printed for the first two executions for invalid input, and a random number has been generated for the last execution.

Random number generation using `shuf` command:

Using the `shuf` command is another way to generate the random number of a specific range. The ways to generate a random number from the terminal and use a script have been shown in this tutorial.

Читайте также:  Centos linux отличие от centos stream

A. Generate Random numbers from the terminal

Run the following command to generate a random number between 0 to 50 using the `shuf` command.

According to the following output, the above command has been executed three times, and three random numbers have been generated.

B. Generate Random numbers using the script

Create a bash file with the following script to generate a list of random numbers based on the input value. The `for` loop has been used to execute the `shuf` command multiple times to generate the list of random numbers between 1 to 100 and print the numbers.

#!/bin/bash
# Generate a random using `shuf` command
echo «How many random numbers do you want to generate?:»
read number

#Print the generated random numbers
echo «The generated random numbers are:»
for n in ` seq » $number » `
do
randomNumber =$ ( shuf -i 1 — 100 -n1 )
echo $randomNumber
done

The following output shows that 5 has been taken as the input value, and 5 random numbers have been generated, which are not more than 100 and not less than 1.

Random number generation using /dev/urandom:

The /dev/urandom can be used with different commands to generate different types of random values. It can’t be used to specify the range values like the `shuf` command and $RANDOM variable. But the number of the digits of the random number can be defined in command with /dev/urandom. The use of the `od` command with /dev/urandom has shown in the next part of this tutorial. This command can be used to specify the number of bytes where each byte can be defined by a decimal number within 0 to 255.

Run the following command to generate a random number between 0 and 255.

The output shows that the above command has been executed three times, and three different random numbers have been generated here where the values are not more than 255.

Conclusion:

Three different ways to generate random numbers have been explained in this tutorial by using various examples. The coder can generate a specific range of random numbers by using the $RANDOM variable or `shuf` command in bash. The coder can use /dev/urandom with any other command to generate a random number of particular bytes or lengths. Generating random numbers is a very common requirement for programming, and I hope the readers will be able to generate a random number based on their requirements after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью
Adblock
detector