thetux4
thetux4

Reputation: 1633

Shell script random number generating

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

Upvotes: 7

Views: 16967

Answers (6)

Tigger
Tigger

Reputation: 9120

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.

Upvotes: 1

pixelbeat
pixelbeat

Reputation: 31708

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

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

Upvotes: 7

jlliagre
jlliagre

Reputation: 30803

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.

Upvotes: 8

bitmask
bitmask

Reputation: 34618

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) ]

Upvotes: 12

Adam Driscoll
Adam Driscoll

Reputation: 9483

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

Upvotes: 1

shellter
shellter

Reputation: 37248

Here you go

echo $(( $RANDOM % 12 ))

I hope this helps.

Upvotes: 3

Related Questions