I know env
is a shell command, it can be used to print a list of the current environment variables. And as far as I understand, RANDOM
is also
a environment variable.
So why, when I launch env
on Linux, does the output not include RANDOM
?
environment-variablesshell
I know env
is a shell command, it can be used to print a list of the current environment variables. And as far as I understand, RANDOM
is also
a environment variable.
So why, when I launch env
on Linux, does the output not include RANDOM
?
Best Answer
RANDOM
is not an environment variable. It's a shell variable maintained by some shells. It is generally not exported by default. This is why it doesn't show up in the output ofenv
.Once it's been used at least once, it would show up in the output of
set
, which, by itself, lists the shell variables (and functions) and their values in the current shell session. This behaviour is dependent on the shell and usingpdksh
on OpenBSD,RANDOM
would be listed byset
even if not previously used.The rest of this answer concerns what could be expected to happen if
RANDOM
was exported (i.e. turned into an environment variable).Exporting it with
export RANDOM
would make it an environment variable but its use would be severely limited as its value in a child process would be "random but static" (meaning it would be an unchanging random number). The exact behaviour differs between shells.I'm using
pdksh
on OpenBSD in the example below and I get a new random value in eachawk
run (but the same value every time within the sameawk
instance). Usingbash
, I would get exactly the same random value in all invocations ofawk
.In
bash
, the exported value ofRANDOM
would remain static regardless of the use ofRANDOM
in the shell (where each use of$RANDOM
would still give a new value).This is because each reference to the shell variable
RANDOM
inbash
makes the shell access its internalget_random()
function to give the variable a new random value, but the shell does not update the environment variableRANDOM
. This is similar in behaviour as with other dynamicbash
variables, such asLINENO
,SECONDS
,BASHPID
etc.To update the environment variable
RANDOM
inbash
, you would have to assign it the value of the shell variableRANDOM
and re-export it:It is unclear to me if this would have the additional side effect of re-seeding the random number generator in
bash
or not (but an educated guess would be that it doesn't).