devnp
devnp

Reputation: 101

Shell script to generate random number between two number or range using echo $RANDOM

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.

Upvotes: 1

Views: 4834

Answers (5)

the dsc
the dsc

Reputation: 11

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.

Upvotes: 0

Gilles Quénot
Gilles Quénot

Reputation: 184955

Another solution using :

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

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246744

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.

Upvotes: 2

Gilles Quénot
Gilles Quénot

Reputation: 184955

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.

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 184955

If you're open to 3rd generation languages :

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

Upvotes: 0

Related Questions