Shell script random number generating

15,576

Solution 1

If you already have your random number, you can say

var=$RANDOM
var=$[ $var % 13 ]

to get numbers from 0..12.

Edit: If you want to produce numbers from $x to $y, you can easily modify this:

var=$[ $x + $var % ($y + 1 - $x) ]

Solution 2

Between 0 and 12 (included):

echo $((RANDOM % 13))

Edit: Note that this method is not strictly correct. Because 32768 is not a multiple of 13, the odds for 0 to 8 to be generated are slightly higher (0.04%) than the remaining numbers (9 to 12).

Here is shell function that should give a balanced output:

randomNumber()
{
  top=32768-$((32768%($1+1)))
  while true; do
    r=$RANDOM
    [ r -lt $top ] && break
  done
  echo $((r%$1))
}

Of course, something better should be designed if the higher value of the range exceed 32767.

Solution 3

An alternative using shuf available on linux (or coreutils to be exact):

var=$(shuf -i0-12 -n1)

Solution 4

Here you go

echo $(( $RANDOM % 12 ))

I hope this helps.

Solution 5

This document has some examples of using this like RANGE and FLOOR that might be helpful: http://tldp.org/LDP/abs/html/randomvar.html

Share:
15,576
thetux4
Author by

thetux4

Updated on June 07, 2022

Comments

  • thetux4
    thetux4 almost 2 years

    var=$RANDOM creates random numbers but how can i specify a range like between 0 and 12 for instance?

  • Hai Vu
    Hai Vu almost 13 years
    Correction: $(( $RANDOM % 13 ))
  • shellter
    shellter almost 13 years
    yes, agreed, thanks. I was so excited to get to answer an easy one first, I didn't test closely enough! Thanks for the 2 up-votes (whoever you are) ;-)
  • jlliagre
    jlliagre almost 13 years
    Note the inner $ is optional as non numeric strings found there cannot be but variable names.
  • Edward Falk
    Edward Falk almost 8 years
    Meh. Then your script isn't portable.
  • Edward Falk
    Edward Falk almost 8 years
    Mac OS X has jot too. But not Linux, so this isn't portable.