var=$RANDOM creates random numbers but how can i specify a range like between 0 and 12 for instance?
6 Answers
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
An alternative using shuf available on linux (or coreutils to be exact):
var=$(shuf -i0-12 -n1)
1 Comment
Here you go
echo $(( $RANDOM % 12 ))
I hope this helps.
3 Comments
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
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.