Random number with BASH Scripting

BASH includes a variable called $RANDOM wich generates a random (or more like pseudorandom) integer number between 0 and 32767. Its use is fairly simple:

echo $RANDOM
188

If you need the random number to be within a range use the modulo operator like this:

echo $[($RANDOM % 100)]
17

You can also give the number an offset. The above command gives a number between 0 and 99, but it could be between 1 and 100:

echo $[($RANDOM % 100) + 1]
100

As you see, giving an offset you can have a random number between two bounds. Defining the bounds may be simpler by doing this, to get a random number between 5 and 10:

lowest=5
highest=10
echo $[($RANDOM % ($[$highest - $lowest] + 1)) + $lowest]
7

Now go crazy generating your random numbers, but keep in mind $RANDOM should not be used to generate an encryption key, for that you should use another random number generator.

0 comments

Please insert the result of the arithmetical operation from the following image
Enter the result of the arithmetical operation from this image