Bash: How to generate a random number within given boundaries

Posted . Visible to the public.

$RANDOM on bash returns a random integer between 0 and 32767.

echo $RANDOM
9816
echo $RANDOM
30922

If you want to limit that to a certain maximum, you can just compare against the modulus of that maximum + 1. \
For example, the following will yield results between 0 and 9:

echo $(($RANDOM % 10))
5
echo $(($RANDOM % 10))
9

Note that this skews random numbers to the lower regions of your boundaries in most cases.

Arne Hartherz
Last edit
Keywords
ubuntu, linux, unix
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2013-07-15 09:12)