Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script random number generating

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

like image 256
thetux4 Avatar asked May 13 '11 13:05

thetux4


People also ask

How do you generate random numbers in Shell?

Example: echo $(($RANDOM%10)) #This will display a random integer between 0 and 9. echo $(($RANDOM%11)) #This will display a random integer between 0 and 10.

How do I randomize in Bash?

$RANDOM is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. $RANDOM should not be used to generate an encryption key. Jipe points out a set of techniques for generating random numbers within a range. # Generate random number between 6 and 30.


1 Answers

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) ]
like image 119
bitmask Avatar answered Nov 10 '22 18:11

bitmask