When coding Bash scripts - especially when developing scripts for functionality testing - we sometimes need to generate a random number or random input. These numbers may also need to be within a specific range. This article will teach you how to perform random number generation in Bash.
In this tutorial you will learn:
- How to generate random numbers in Bash
- How to generate random numbers is a specific range
- Examples demonstrating random number generation in Bash
Software requirements and conventions used
|Category||Requirements, Conventions or Software Version Used|
|Software||Bash command line, Linux based system|
|Conventions||# - requires linux-commands to be executed with root privileges either directly as a root user or by use of |
$ - requires linux-commands to be executed as a regular non-privileged user
Example 1: Generating a random number using the random generator
Let’s generate a random number in Bash:
$ echo $RANDOM 24758 $ echo $RANDOM 13
That was simple wasn’t it?
There are a few challenges with this approach though; it is not very usable as it stands: the random number could be
32000. Also noteworthy is that whilst the returned number seems random, it is actually influenced by how the random entropy variable (
RANDOM=) is initialized. This will be the focus for another article. A quick example of how you can make it more random would be;
$ RANDOM=1 $ echo $RANDOM 16807 $ RANDOM=1 $ echo $RANDOM 16807 $ RANDOM=$(date +%s%N | cut -b10-19) $ echo $RANDOM 18991 $ RANDOM=$(date +%s%N | cut -b10-19) $ echo $RANDOM 11045
Note that the random number
16807 is not really that random, as the random generator was seeded with the same
RANDOM=$(date +%s%N | cut -b10-19) command is a much better random generator entropy seeder based on second and nanosecond time.
Example 2: Numbers in a range
Selecting random numbers in a range is simple. Let’s generate a random number between 1 and 113:
$ echo $(( $RANDOM % 113 + 1 )) 50 $ echo $(( $RANDOM % 113 + 1 )) 17 $ echo $(( $RANDOM % 113 + 1 )) 95
And we can also use an alternative syntax/command. This time we will generate a random number between 1 and 117:
$ echo $[ $RANDOM % 117 + 1 ] 113 $ echo $[ $RANDOM % 117 + 1 ] 71 $ echo $[ $RANDOM % 117 + 1 ] 10
To increase the minimum of a given range, you can simply increase the
+1 to a higher number.
Please consider the following example, generating a random number between 11 and 30:
$ echo $[ $RANDOM % 20 + 11 ] 21
In this article, we learned how to generate a random number in Bash, in any preferred range. We also touched briefly on how randomness in Bash works via an entropy seed initialized random generator.
Show us some of your
$RANDOM creations in the comments below! Enjoy!