Transfered from Linux Config Disqus comments:
Hi, How can I generate random number, preferably integer to be used within my bash script. Is there also a way to test whether random numbers are generated properly?
The easiest way on how to generate random number in bash is to use bash’s $RANDOM function. $RANDOM is an internal Bash function that returns an integer in the range 0 - 32767.
For example the following line will generate 10 random integers in range from 1 to 10:
NOTE: +1 will simply shift result numbers from range 0 - 9 to 1 -10
$ for i in $( seq 1 10 ); do echo int $i = $[ ( $RANDOM % 10 ) +1 ]; done
Very basic test can be performed to see whether $RANDOM function creates a uniformly distributed random numbers. For this we would need more than 10 randomly generated numbers in order to see uniform distribution.
Therefore, we can create 100 000 random numbers from range 0 - 10 with modulus %11 and store them into file random.txt.
$ for i in $( seq 1 100000 ); do echo $[ ( $RANDOM % 11 ) ] >> random.txt; done
Using octave we can than generate a histogram with 11 bins to see whether bash $RANDOM internal function created uniformly distributed random numbers :
$ octave octave:1> rand=csvread('~/random.txt'); octave:2> hist(rand,nbins=11);