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

EmailPermalinkComments (3)
Tags
Categories: Bash, Snippets

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