I am trying to identify some more options that I can use with $RANDOM to generate the random number from specific range and not able to find one. can some one please help me with it. echo $RANDOM generates the number from shell but its random and not specific to my range. I want to generate random in the range from 1 to 100.
5 Answers
Try doing this using a shell function :
intrandfromrange() { echo $(( ( RANDOM % ($2 - $1 +1 ) ) + $1 )); }
intrandfromrange 1 100
EXPLANATIONS
foo() { }is a skeleton for shell functions.$((...))gives the result of the enclosed arithmetic expression.%stands for modulo, the remainder of a division operation.$1&$2are the first and the second arguments of the function.- The rest is just simple arithmetic.
3 Comments
devnp
Thanks Sputnick, can you provide some explanation on the snip.
devnp
Thanks for reply. So ( RANDOM % ($2 - $1 +1 ) will be take one random number and it will do MOD with ($2-$1 +1) output, in my case its 100-1+1?
erickson
This won't give uniform results. You're more likely to get values 1-68 than 69-100 (because $RANDOM isn't evenly divisible by 100). In effect, it's a weighted die.
If you're open to 3rd generation languages :
python -c 'import random; print(random.randint(1, 100))'
1 Comment
devnp
yeah PHP is also easy, it has rand function where you can specify the range but the device that I am testing with doesn't have that facility.
You don't need "shuf | head -1". "shuf -n 1"
Also:
seq 1 100 | shuf -n 1
A similar function could be:
rnd () {
seq $1 $2 | shuf -n ${3:-1}
}
So rnd 1200 5000 5 will output 5 random numbers between 1200 and 5000. For whenever one needs some. No need to specify 1 if you need just one and you're in a hurry.