7

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

6 Answers 6

12

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) ]
Sign up to request clarification or add additional context in comments.

Comments

8

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.

Comments

7

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

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

1 Comment

Meh. Then your script isn't portable.
3

Here you go

echo $(( $RANDOM % 12 ))

I hope this helps.

3 Comments

Correction: $(( $RANDOM % 13 ))
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) ;-)
Note the inner $ is optional as non numeric strings found there cannot be but variable names.
1

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

Comments

1

On FreeBSD and possibly other BSDs you can use:

jot -r 3 0 12

This will create 3 random numbers from 0 to 12 inclusively.

Another option, if you only need a single random number per script, you can do:

var=$(( $$ % 13 ))

This will use the PID of the script as the seed, which should be mostly random. The range again will be from 0 to 12.

1 Comment

Mac OS X has jot too. But not Linux, so this isn't portable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.