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

1

1 Answer 1

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.

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

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.