1824983 Members
3922 Online
109678 Solutions
New Discussion юеВ

Random # in ksh script

 
SOLVED
Go to solution
Ron Bombard
Frequent Advisor

Random # in ksh script

In KSH, there's a RANDOM parameter set by the shell. I'd like to use a random number in my script, but this parameter picks a number betwee 0 and 32767. I'd like a random number between 0 and 3000. Is there a way to force this RANDOM parameter to use a range? I wrote a little script to accomplish what I want, but it seems a bit klumzy:
======
guessed=3817
upper=3816
while [[ $guessed -ge $upper ]]
do
guessed=$RANDOM
done
echo $guessed
========
Is there a better way?

Thanks.

Meddle not in the affairs of dragons... for you are crunchy and taste like chicken.
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Random # in ksh script

How about this?

guessed=$((${RANDOM} % 3001))
If it ain't broke, I can fix that.
Ron Bombard
Frequent Advisor

Re: Random # in ksh script

Hmmm... your MOJO is wicked cool!
Worked great. Too bad I don't understand HOW... Guess I'll just "chalk it off" as magic.
Thanks!
Meddle not in the affairs of dragons... for you are crunchy and taste like chicken.
Tom Maloy
Respected Contributor

Re: Random # in ksh script

How about the modulo operator?

((num=guessed%3000))

Tom
Carpe diem!
Anonymous
Not applicable

Re: Random # in ksh script

not that much magic... you see this easily
echo ${RANDOM}
$((echo hello world))

...BTW man sh-posix ...