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?
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?
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.
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?
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.
random=$(bash -c "RANDOM=$mac; echo $RANDOM")
bash -c 'RANDOM=42; echo "$RANDOM" "$RANDOM" "$RANDOM"'.
I came here late, but I have to say something about "So that given the same seed the same random number will always be output?" I don't comprehend that.
If that's what you want, you do not want a random number. You can skip the seeding and use the "same random number" you wanted. The stuff about single and double quotes may be persiflage.
I would hesitate to say that some of the comments are mockery. The hesitation would take too long.
RANDOM=$(date +%s);echo $RANDOM; echo $RANDOM; echo $(($RANDOM%1000))
That's about as good as you can get for randomness, I think. But 420 comes up too many times.