0

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

cohara
  • 111
  • 3
  • 19
  • Does this answer your question? [Random number between range in shell](https://stackoverflow.com/questions/4673830/random-number-between-range-in-shell) – Peter O. Feb 23 '21 at 21:41

1 Answers1

3
$ 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.

devnull
  • 118,548
  • 33
  • 236
  • 227
Bruce K
  • 749
  • 5
  • 15