I ran into this problem and I'm so confused.
I am using $RANDOM in bash as a test string at the very beginning of the linux bootup process. Very interestingly, I observed that $RANDOM will be the same every time linux booted up. In my case, it's 18869.
I was simply echoing $RANDOM to a file. I observed the same number in every boot up. After that, $RANDOM seems to return "real" random numbers.
echo "$RANDOM is a test string" >> /tmp/test
Can anyone explain the reason in this?
Here is the the initial seed algorithm from
variables.c
in the Bash 4.2 source code:In other words, it generates the seed based on pid and current time in seconds and microseconds (with a system accuracy of ~1/100th second).
If you check
$RANDOM
on a small, predictable system, before the system clock is initialized, you're likely to see the same value every time.Because the seed is always the same at the startup. You can always assign a value
to seed the RANDOM manually, perhaps with the PID
Trying to find your seed, I wrote this small script
and found:
See that this script has lots of
$RANDOM
but still is fully deterministic, it'll result always the same if you call it. This link has more information about$RANDOM
and this other link has information on how to use/dev/random
and/dev/urandom
, as an alternative. Another way to generate a random number without the seed issue is to get some information about the actual time in nanoseconds.