≡ Menu

Linux: Random Number Generation in BASH

Question – I need pick random files from a directory of 10 files. How do I generate a random number between 0 and 9 (inclusive) in a BASH shell script on CentOS Linux?

The shell BASH contains a random number generator called $RANDOM. The value of this variable is a random number between 0 and 32767. The generated numbers are 15 bits in length (32767 = 2^15 – 1).

For example, I will echo $RANDOM three times and it will output a different number each time:

[root@server ~]# echo $RANDOM
14692
[root@server ~]# echo $RANDOM
30589
[root@server ~]# echo $RANDOM
25171
[root@server ~]#

Now, you can do the same thing in a shell script 10 times:

#!/bin/bash
for((i=0;i<10;i++))
do
        echo $RANDOM
done

The output of the above code is as follows:

[root@server ~]# ./random.sh
3397
13514
25747
10617
24487
21328
23232
9587
10389
25166
[root@server ~]#

To get a random number between 0 and 9, simple use the % operator:

$RANDOM % 10

Doing this 10 times:

#!/bin/bash
for((i=0;i<10;i++))
do
        echo $(($RANDOM % 10))
done

The above code will output a random number in the range [0,10) 10 times:

[root@server ~]# ./random.sh
3
1
9
1
8
3
0
8
7
7

Note that the random numbers generated are pseudo-random numbers which means that given a particular value of the seed, the numbers follow a deterministic path. Given a seed, the random number generator will generate the same list of numbers!

To set the seed for the random number generation, just set the RANDOM variable with some number.

For example, the following script seeds the random number generation with a number (100):

#!/bin/bash
RANDOM=100
for((i=0;i<5;i++))
do
        echo $(($RANDOM % 10))
done

Running the above code multiple times will generate the same sequence of random numbers!

[root@server ~]# ./random.sh
2
5
5
3
9
[root@server ~]# ./random.sh
2
5
5
3
9

That was a quick tutorial on how to generate pseudo-random numbers in the BASH shell. Note that this way of generating random numbers is not suitable for generating keys for cryptography applications!

{ 0 comments… add one }

Leave a Comment