I just ran into a problem that shows me I'm not clear on the scope of shell variables.
I was trying to use bundle install
, which is a Ruby command that uses the value of $GEM_HOME
to do its work. I had set $GEM_HOME
, but the command ignored that value until I used export
, as in export GEM_HOME=/some/path
.
I read that this makes the variable somehow "global" (also known as an environment variable), but I don't understand what that means. I know about globals in programming, but not across distinct programs.
Also, given that my setting such variables applies only to the current shell session, how would I set them for, say, a daemonized process?
What scopes can shell variables have?
Best Answer
The processes are organized as a tree: every process has a unique parent, apart from
init
whichPID
is always 1 and has no parent.The creation of a new process goes generally through a pair of
fork
/execv
system calls, where the environment of the child process is a copy of the parent process.To put a variable in the environment from the shell you have to
export
that variable, so that it is visible recursively to all children. But be aware that if a child change the value of a variable, the changed value is only visible to it and all processes created after that change (being a copy, as previously said).Take also into account that a child process could change its environment, for example could reset it to default values, as is probably done from
login
for example.