1

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 5

2

If you have GNU sort:

rand=$( seq $start $end | sort -R | head -1)

Calls external tools, so will be a few milliseconds slower than performing arithmetic with $RANDOM.

Sign up to request clarification or add additional context in comments.

Comments

1

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 & $2 are the first and the second arguments of the function.
  • The rest is just simple arithmetic.

3 Comments

Thanks Sputnick, can you provide some explanation on the snip.
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?
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.
1

Another solution using :

 printf '%s\n' {1..100} | shuf | head -1

1 Comment

This should give better results. +1
0

If you're open to 3rd generation languages :

python -c 'import random; print(random.randint(1, 100))'

1 Comment

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.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.