7

I've been using $((1 + RANDOM % 1000)) to generate a random number.

Is it possible to do something similar but provide a seed?

So that given the same seed the same random number will always be output?

13

Assign a seed value to RANDOM

$ bash -c 'RANDOM=640; echo $RANDOM $RANDOM $RANDOM'
28612 27230 24923
$ bash -c 'RANDOM=640; echo $RANDOM $RANDOM $RANDOM'
28612 27230 24923
$ bash -c 'RANDOM=640; echo $RANDOM $RANDOM $RANDOM'
28612 27230 24923
$ 

Notice that single quotes are used; double quotes run afoul shell interpolation rules:

$ bash -c 'RANDOM=42; echo $RANDOM $RANDOM $RANDOM'
19081 17033 15269
$ RANDOM=42
$ bash -c "RANDOM=640; echo $RANDOM"
19081
$ bash -c "RANDOM=640; echo $RANDOM"
17033
$ bash -c "RANDOM=640; echo $RANDOM"
15269
$ 

because $RANDOM is being interpolated by the parent shell before the child bash -c ... process is run. Either use single quotes to turn off interpolation (as shown above) or otherwise prevent the interpolation:

$ RANDOM=42
$ SEED_FOR_MY_GAME=640
$ bash -c "RANDOM=$SEED_FOR_MY_GAME; echo \$RANDOM"
28612
$ bash -c "RANDOM=$SEED_FOR_MY_GAME; echo \$RANDOM"
28612
$ 

This feature of RANDOM is mentioned in the bash(1) manual

   RANDOM Each time this parameter is referenced, a random integer between
          0 and 32767 is generated.  The sequence of random numbers may be
          initialized by assigning a value to RANDOM.  If RANDOM is unset,
          it loses its special properties,  even  if  it  is  subsequently
          reset.
  • If I run random=$(bash -c "RANDOM=640; echo $RANDOM") shouldn't it return the same each time? Or is it because the $(bash ... isn't treated as a new instance of bash? – Philip Kirkbride Nov 17 '17 at 17:47
  • 1
    doublequotes is probably not what you want there – thrig Nov 17 '17 at 17:55
  • 1
    Watch what happens if you do: set -x; FOO=42; bash -c "FOO=999; echo $FOO". The double-quotes are allowing the outer shell to replace $RANDOM with the outer shell's random; the inner bash shell is simply echoing an integer. – Jeff Schaller Nov 17 '17 at 17:56
  • @thrig I need double quotes because in my case it is actually random=$(bash -c "RANDOM=$mac; echo $RANDOM") – Philip Kirkbride Nov 17 '17 at 17:56
  • Of course it should be bash -c 'RANDOM=42; echo "$RANDOM" "$RANDOM" "$RANDOM"'. – G-Man Nov 18 '17 at 0:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.