Re: Environment variable not remembered outside a script?
- From: Chris Mattern <syscjm@xxxxxxxxxxxxxx>
- Date: Thu, 19 Feb 2009 13:26:23 -0600
On 2009-02-19, Sang-Ho Yun <Sang-Ho.Yun@xxxxxxxxxxxx> wrote:
The following is the contents of two files (.zshrc and foo.sh).This is a difference between running a script and sourcing it. .zshrc is
.zshrc:
export VAR1='test1'
foo.sh:
export VAR2='test2'
After executing the two files (.zshrc is already executed when I opened the
a terminal window), the following is echo results.
echo $VAR1test1
echo $VAR2
That is, VAR2 is blank. No value seem to be remembered in the command line.
Why does .zshrc have a lasting effect, whereas foo.sh doesn't? Is this a
normal behavior, or there is something wrong with my system?
sourced by your login process, and any environment variables it sets
are remembered. You run foo.sh, and any environment variables it sets are
forgotten. This is absolutely normal behavior.
On to the technical explanation as to why this is so. Environmental varaibles
themselves are not a shell feature but are actually part of the UNIX
process structure; every process has its environment, consisting of all the
environment variables it has defined. The $ syntax is simply the way the
shell process gives you access to its environment. Now, then, when you run
a shell script what happens is that the shell forks a new process (and the
new process inherits the environment the parent process had at the moment
of the fork, incidentally). The new process is the shell script's "child
process", while the shell script is the new process's "parent process" (the
PPID column in the ps command is showing you the process ID of the process's
parent process). The shell script is then run in the child process, with the
child process gaining control of your terminal while the shell waits. The
shell regains control when the child process ends. But changes in the child
process's environment CANNOT affect the parent process, so all the environment
variable changes are lost.
But when you source a script, the script commands are interpreted and run
in the shell process itself, so all the environment changes are remembered.
If you want to source your script, the syntax is ". foo.sh".
--
Christopher Mattern
NOTICE
Thank you for noticing this new notice
Your noticing it has been noted
And will be reported to the authorities
.
- References:
- Environment variable not remembered outside a script?
- From: Sang-Ho Yun
- Environment variable not remembered outside a script?
- Prev by Date: Re: Environment variable not remembered outside a script?
- Next by Date: Re: rsync with custom fixing of symlinks
- Previous by thread: Re: Environment variable not remembered outside a script?
- Next by thread: Decisions based on substrings in the Unix shell
- Index(es):
Relevant Pages
|