Bash: Get random number that belongs in a range 1


In case you need to create a random number that is between a certain range, you can do it in a very easy way in bash.

Bash has the $RANDOM internal function that returns a different (pseudo) random integer at each invocation. The nominal range of the results is 0 – 32767 (it is the range of a signed 16-bit integer).

We use the result of $RANDOM to create our number using the following script:

FLOOR=10;
CEILING=100;
RANGE=$(($CEILING-$FLOOR+1));
echo "You will generate a random number between $FLOOR and $CEILING (both inclusive). There are $RANGE possible numbers!"
RESULT=$RANDOM;
echo "We just generated the random number $RESULT, which might not be in the range we want";
let "RESULT %= $RANGE";
RESULT=$(($RESULT+$FLOOR));

echo "Congratulations! You just generated a random number ($RESULT) the is in between $FLOOR and $CEILING (inclusive)";

We use basic math operations on the variables to create the random number that is in the range we like without need-less loops.

What we do is:

  1. We compute the length of the range of valid numbers (ceiling-floor)
    Here we added the +1 because we want the ceiling to be included in the result set.
  2. We generate a random number that is between 0 and the length of range using modulo to limit the results.
  3. We add to the result the value of the floor and this create our final result which is a number equal or greater to the floor and equal or smaller to the ceiling

This post is also available in: Greek


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

One thought on “Bash: Get random number that belongs in a range