cohara
cohara

Reputation: 111

How to generate a random number between two limits in bash without using shuf or sort -R

I need to generate a random number between 1981 and 2012 (inclusive) in bash. I don't have access to shuf or sort -R, and I have tried:

floor=1981
range=2012
while [ "$number" -le $floor ]; 
do 
number=$RANDOM; 
let "number %= range"; 
done

and

while [ "$number" -le $floor ]; 
do 
number=$(( ( RANDOM % 2012 )  + 1 )); 
done

However these always returns 1992:

echo $number
1992

Has anyone got any other suggestions. Ideally, just for your information, and it may not be possible, I would like it to return each number between 1981 and 2012 exactly once within a loop. For the moment though I just need to know how to generate a random number between two limits in bash, without using shuf or sort -R.

Thanks in advance

Upvotes: 0

Views: 387

Answers (1)

Bruce K
Bruce K

Reputation: 769

$ echo $(( (RANDOM % 32) + 1981 ))
1991
$ echo $(( (RANDOM % 32) + 1981 ))
2000
$ echo $(( (RANDOM % 32) + 1981 ))
1998

To emit each only once, you need an array:

  declare -A emitted
  ${emitted[$number]:-false} || {
    emitted[$number]=true
    echo $number
  }

so if that first expression is not working for you, you have a BASH problem. A "few" details left as an exercise for the reader.

Upvotes: 3

Related Questions