Read more

Bash: How to generate a random number within given boundaries

Arne Hartherz
July 15, 2013Software engineer at makandra GmbH

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

echo $RANDOM
9816
echo $RANDOM
30922
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2013-07-15 11:12)