开发者

Shell script random number generating

var=$RAN开发者_运维知识库DOM creates random numbers but how can i specify a range like between 0 and 12 for instance?


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


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.


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

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


Here you go

echo $(( $RANDOM % 12 ))

I hope this helps.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜