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

EmailPermalink
Tags
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))

Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

 


 Last 50 Posts
Change Theme...
  • Users » 66
  • Posts/Pages » 25
  • Comments » 4
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight