Posted about 8 years ago. Visible to the public. Linked content.

Bash: How to generate a random number within given boundaries

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

Copy
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:

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

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

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 8 years ago
Keywords:
ubuntu, linux, unix
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more