Rate this page

Flattr this

Set the value of an environment variable

Tested on

Debian (Etch, Lenny, Squeeze)
Ubuntu (Hardy, Intrepid, Jaunty, Karmic, Lucid, Maverick, Natty, Oneiric, Precise)

Objective

To set the value of an environment variable within a POSIX-compatible shell

Background

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:

DISPLAY the local or remote X Window display that should be used by default
PATH the list of paths to search when looking for an executable
PWD the current working directory
TERM the terminal type
TZ 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.

Scenario

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 GMT.

Method

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 TZ='GMT'

The 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.

Testing

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'

or the printf command if not:

sh -c 'printf "%s\n" "$TZ"'

Troubleshooting

If an environment variable assignment is not having the desired effect then it may be helpful to ask some of the following questions:

See also

Tags: environment | shell