Bash: How to Generate Random Number in Range


Often you may want to use Bash to generate a random number in a range.

The easiest way to do so is by using the shuf command, which “shuffles” the values provided as input.

You can use the following syntax to use the shuf command to generate a random integer between the range of 1 and 100 (inclusive):

shuf -i 1-100 -n 1

Feel free to change the number after -n to generate more than one random integer.

You can also store the random number in a variable by using the following syntax:

my_values=$(shuf -i 1-100 -n 1)

This particular example will store a random integer between 1 and 100 in the variable named my_value.

Here is what the various commands do:

  • -i: Specifies the input (i.e. the range of values)
  • -n: Specifies the number of random integers to choose

The following example shows how to use this syntax in practice.

Example: How to Generate Random Number in Range Using Bash

Suppose that we would like to generate a random integer between 1 and 10 in Bash.

We can use the following syntax to do so:

shuf -i 1-10 -n 1

The following screenshot shows how to use this syntax in practice:

Bash generate random number in range

Notice that each time we run the code, a random number between 1 and 10 is returned.

We can also generate more than one random number in the range by specifying a number greater than 1 after the -n command.

For example, we can use the following syntax to generate four random numbers in the range of 1 to 10:

shuf -i 1-10 -n 4

The following screenshot shows how to use this syntax in practice:

Bash generate multiple random numbers between range

Notice that this returns the integers 8, 9, 2 and 1.

If we’d like, we can use the following syntax to store a list of random integers between 1 and 10 in a variable named my_values and then retrieve the values from the variable:

my_values=($(shuf -i 1-10 -n 4))
echo "${my_values[@]}"

The following screenshot shows how to use this syntax in practice:

Bash generate array of random values between range

Notice that when we use the echo command, we’re able to retrieve the list of random integers that we generated.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Extract First Number from a String
Bash: How to Check if String Starts with Specific Value
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String

Leave a Reply