### Generating a random number in bash

07 Jun 2013 @ 3:56 PM

Hi Guys,

It has been a long time since we did make an entry…

And today will be a short one.

How to generate a random number in Bash.

There is a variable called “\$RANDOM”. It provides a random number :

echo \$RANDOM
27652

Thus, if you want to generate a random number between two barriers, you can use :

\$((\$RANDOM % (<higher barrier>-(<lower  barrier>-1)) + <lower barrier>))

e.g.

echo \$((\$RANDOM % 100 + 1))
54

And, if you want to get a random line in a file :

echo \${RANDOM} >/dev/null;cat AA_AA | sed -n “\$(( \${RANDOM} % `cat AA_AA | wc -l` + 1)) p”

The first “echo \${RANDOM} is to force the re-assignement of the \${RANDOM} value, that, for some reason, does not get updated when used in the formula.

Have a good day !

Update : Updated based on KenS comment. Thank you.

Posted By: Dimi
Last Edit: 13 May 2014 @ 06:53 AM Categories: Bash, Snippets

### Responses to this post » (3 Total)

1. KenS says:

If you want to generate a number between two barriers, I assume you mean something like [N, M). In that case it should be

echo \$((\$RANDOM % (M – N) + N))

echo \$((\$RANDOM % (100 – 1) + 1))

• Dimi says:

Yep, you are closer to reality that what I said in the article (i’ll update it later).
I tried a few things, and the following works :
echo \$((\$RANDOM % (20-17) + 18))
This gives a number between 18 and 20. So I think the correct formula would look like \$((\$RANDOM % (B-(A-1)) + A)) for a number between A and B.

• Dimi says:

Updated now based on your comment. Thanks !    Last 50 Posts  Back  Back  Back  Change Theme...
• Users » 67
• Posts/Pages » 25
• Void « Default
• Life
• Earth
• Wind
• Water
• Fire
• Light 