Monday, February 16, 2009

Environment variables

Environment Variables

Every instance of a shell, and every process that is running, has its own “environment" settings that give it a particular look, feel, and, in some cases, behavior. These settings are
typically controlled by environment variables. Some environment variables have special meanings to the shell, but there is nothing stopping you from defining your own and using them for your own needs. It is through the use of environment variables that most shell scripts are able to do interesting things and remember results from user inputs as well as program outputs.

Printing Environment Variables

To list all of your environment variables, use the printenv command. For example,

[yyang@fedora-serverA ~]$ printenv
HOSTNAME=fedora-serverA.example.org
SHELL=/bin/bash
TERM=xterm
HISTSIZE=1000
......

To show a specific environment variable, specify the variable as a parameter to printenv. For example, here is the command to see the environment variable TERM:

[yyang@fedora-serverA ~]$ printenv TERM
xterm

Setting Environment Variables

To set an environment variable, use the following format:
[yyang@fedora-serverA ~]$ variable = value

where variable is the variable name and value is the value you want to assign the variable. For example, to set the environment variable FOO to the value BAR, type
[yyang@fedora-serverA ~]$ FOO=BAR

Whenever you set environment variables in this way, they stay local to the running shell. If you want that value to be passed to other processes that you launch, use the
export built-in command. The format of the export command is as follows:

[yyang@fedora-serverA ~]$ export variable
where variable is the name of the variable. In the example of setting the variable FOO,
you would enter this command:
[yyang@fedora-serverA ~]$ export FOO

TIP You can combine the steps for setting an environment variable with the export command, like
so: [yyang@fedora-serverA ~]$ export FOO=BAR.

If the value of the environment variable you want to set has spaces in it, surround the variable with quotation marks. Using the preceding example, to set FOO to “Welcome to the BAR of FOO.”, you would enter

[yyang@fedora-serverA ~]$ export FOO="Welcome to the BAR of FOO."

You can then use the printenv command to see the value of the FOO variable you just set by typing
yang@fedora-serverA ~]$ printenv FOO
Welcome to the BAR of FOO.

Unsetting Environment Variables

To remove an environment variable, use the unset command. The syntax for the unset command is
yyang@fedora-serverA ~]$ unset variable

where variable is the name of the variable you want to remove. For example, the command to remove the environment variable FOO is

[yyang@fedora-serverA ~]$ unset FOO

No comments:

Post a Comment