BASH: Is “export” needed, when setting a variable

2020-08-10 07:31发布

问题:

I wonder if there is a need to use "export" when setting a variable in .bashrc.

In my tests editing .bashrc there was no difference between

foo=bar

and

export foo=bar

In both cases, after login "echo $foo" outputs "bar".

I am using Debian Squeeze, if that matters.

Thank you guys in advance.

回答1:

Try creating a shell script that accesses the foo variable.

If foo was export'ed, it will be visible in the shell script, otherwise it won't.



回答2:

SuperUser has this covered.

Short answer: export makes sure the environment variable is set in child processes. If you don't export, it's only available in the same process/interactive session.



回答3:

It's preferable because exported variables get passed to child processes (programs launched from that shell). Without the export command those variables only apply to the shell itself and not processes launched from the shell