Environment Variables

What Are Environment Variables?

Pieces of information specific to:

  • the specific physical computer,
  • the shell that’s active, and
  • the current user.

At the bash prompt, type:

declare

and note the long list.

 

Another shell

The bash shell itself is one of the choices you set in your environment variables. You could be using a different shell, if you want.

Type:

tcsh
or
ksh
or
zsh

You’re in a new and different shell! Now try:

declare

What happens?

Now type

exit

to escape.

 

Back in Bourne/bash…

Notice some of the useful environment variables:

HOME

PATH

PS1

 

Use these in scripts and commands like this:

$HOME

 

Look at your environment variables

Notice how you call these. Type:

echo HOME

Now try:

echo $HOME

 

Create your own environment variables

Suppose you refer to a particular file often in your admin duties. You can create a new variable to refer to that file:

MYLOG=/var/user.log; export MYLOG

This var will be TEMPORARY, and will disappear after you log out.

 

About export

Notice that export command above. We need it because a declared variable actually is available only to the current shell. If you start another shell, or some program you run starts one, that shell can’t access the variable or its value.

The export command takes care of this problem: it “exports” the variable and its value to your larger environment, where it’s available to any program you run.

 

Permanent environment variables

To add permanent environment variables, edit the .bashrc file in your home directory:

vi .bashrc

and add your variable name and value:

MYVAR=/var/users.log

Then, either in-line or on another line, don’t forget to export the variable:

export MYVAR

 

A Critical Difference Between Bourne and bash: Exporting Variables

bash allows you to define and export a variable in a single line:

export MYCOLOR=”yellow”

Bourne requires that you do this in two lines:

MYCOLOR=”yellow”

export MYCOLOR

Don’t be fooled by a command series like this:

MYCOLOR=yellow; export MYCOLOR

This is two lines! The “;” character is an “inline return,” that is, a new line.

 

Using environment variables

Often in scripts or commands, you’ll need to use environment variables in text without spaces. This can confuse the shell.

Place the variable in braces to protect it:

MYCOLOR=yellow; export MYCOLOR

echo “My dog is ${MYCOLOR}ish.”

 

Environment Commands

Commands related to environment variables differ from one Unix or Linux distro to another. Debian distros, for instance, respond differently than Red Hat distros. Try all of these:

printenv shows all variables

declare– shows all variables (local and exported)

env – shows environment variables

export – shows exported variables

set – assigns values to system options, for instance noclobber

unset – removes variables

 

Resources

See this excellent page: http://www.faqs.org/docs/linux_intro/sect_07_02.html