Bash Variables – Difference Between Environment Variable and Shell Variable

bashenvironment-variables

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

Best Answer

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'

$
Related Question