Set the value of an environment variable
|Debian (Etch, Lenny, Squeeze)|
|Ubuntu (Hardy, Intrepid, Jaunty, Karmic, Lucid, Maverick, Natty, Oneiric, Precise)|
To set the value of an environment variable within a POSIX-compatible shell
Environment variables are name-value pairs that can be used to communicate information from a process to its descendants. They are typically used to provide programs with information about the environment in which they are executing (hence the name). Notable ones include:
||the local or remote X Window display that should be used by default|
||the list of paths to search when looking for an executable|
||the current working directory|
||the terminal type|
||the default timezone|
Environment variables are inherited from parent to child when new processes are created. Processes can freely alter their own environment variables but not those of other processes. In particular, changes made by a child process do not propagate back to its parent.
Suppose that you have used SSH to connect to a host located in Quito, which has been configured to use ECT as its local time zone (UTC-05:00). You yourself are located in London, and for the duration of your current session you would prefer to see any times displayed using GMT (UTC±00:00). You know that this can be achieved by setting the
TZ environment variable to
A variable assignment for a POSIX-compatible shell consists of the variable name followed by an equals sign followed by the value. This can be combined with the
export command to ensure that the assignment will be visible to subprocesses:
export command is unnecessary if the variable already exists and has been marked for export, however there is no harm in including it routinely as a precaution. Similarly, the quotation marks on the right hand side are unnecessary in this instance because the value within them contains no special characters.
You can check that the environment variable has been exported with the intended value by inspecting it from within a subshell. This can be done using the
printenv command if it is available:
sh -c 'printenv TZ'
printf command if not:
sh -c 'printf "%s\n" "$TZ"'
If an environment variable assignment is not having the desired effect then it may be helpful to ask some of the following questions:
- Is the variable being set by the intended process or by a subprocess?
- Is the process that is reading the variable a descendant of the one that set it?
- If the variable needs to be marked for export then is that happening?
- Is the shell making unintended changes to the right hand side of the assignment?