Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

It is said that environment variables are inherited in child processes but shell variables are not. However the following test shows shell variables are seen in child process just as environment variables. What is the difference?

> bash --version
GNU bash, version 3.2.39(1)-release (x86_64-suse-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.
> export TEST="ENV_TEST"    #env var
> sh -c "echo \$TEST"
ENV_TEST
> TEST="SHELL_TEST"         #shell var
> sh -c "echo \$TEST"       #shell var is seen in child process
SHELL_TEST
share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

Your second assignment TEST="SHELL_TEST" doesn't un-export the variable. It's still marked as "to be inherited by children". And the value inherited by the child is the value currently set in the parent.
In other words, your second assignment doesn't revert the status of TEST to a shell variable, it's still an environment variable according to that terminology.

You'd have to un-export it for it to become unset in children processes:

$ typeset +x TEST
$ sh -c 'echo $TEST'

$
share|improve this answer
    
Hi Mat, thank you for your answer. So my understanding (there are two variables named TEST, one for environment variable and one for shell variable, shell var TEST shadows env var TEST.) is incorrect, there is only one variable in Bash, it is always a shell variable and can be set to be exported and acts as an environment variable. Is this specific to Bash and implementation-dependent, or it is universal in all shells. Thank you. –  ning Dec 10 '12 at 9:08
    
Not sure about "universal", but it works the same with bash, ksh and zsh at least. –  Mat Dec 10 '12 at 9:13
    
Thank you for your clear answer. –  ning Dec 10 '12 at 9:15
1  
@ning This is how all modern POSIX/Bourne-style shells work (ash, ksh, bash, zsh). There were ancient versions of the Bourne shell where changing an exported shell variable didn't change the value in the environment, but you're unlikely to encounter them any more. Csh works differently, you might still encounter that in old-fashioned environments but it too has been obsolete for a while. –  Gilles Dec 10 '12 at 23:03
    
@Gilles Thank you for making it clear what's going on and why. As someone said, every Unix developer should also be a historian. –  ning Dec 11 '12 at 0:09
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.