Setting Linux environment variables
This is an excerpt from the Bash man page:
export [-fn] [name[=word]] ...
export -p
The supplied names are marked for automatic export to the environment of subsequently executed commands. If the -f option is given, the names refer to functions...
If you only need the variable in the current environment, it's not necessary to use export.
var=value
Edit:
Without export: current environment only. With export: current environment and child environments.
Here's a demonstration of the affect of export on availability of a variable in a child environment and that changes in the child environment don't affect the parent:
$ var1=123
$ export var2=456
$ echo "parent [$var1] [$var2] [$var3]"
parent [123] [456] []
$ var3=789 bash -c 'echo "child [$var1] [$var2] [$var3]"; var1=111; var2=222; var3=333; echo "child [$var1] [$var2] [$var3]"'
child [] [456] [789]
child [111] [222] [333]
$ echo "parent [$var1] [$var2] [$var3]"
parent [123] [456] []
After the first echo (echo "parent..."
) you see "123" and "456" because both var1
and var2
are active in the current environment. You don't see a value for var3
because it's not set yet.
After the line that starts "var3=...
" you don't see a value for var1
because it wasn't exported. You do see a value for var2
because it was exported. You see a value for var3
because it was set for the child environment only.
(bash -c
is equivalent to running a script with the contents of the argument to the -c
option. A script or other executable or, in this case, the argument to bash -c
becomes a child of the current environment which, as a result is, of course, the child's parent.)
In the "script" the values of the variable are changed. It now outputs those new values.
Once the "script" is finished, execution returns to the parent environment (the command line in this case). After the last echo, you see the original values because the changes made in the child environment do not affect the parent.
You say that
I am always using export command to set environment variable
By the way you worded that, it sounds like you are really trying to ask how do you make an environmental variable persists. To do that would require you to place your export VAR="foo"
statement in your $HOME/.bash_profile file (if you are using bash). If you want that environmental variable to persist for all users but root, then add it to /etc/profile. If you want it added for the root user too, then set it in /root/.bash_profile .
This will work for all login shells where bash is the shell of choice. For non login shells, you need to use .bashrc. I have no insights to offer for other shells :D