Friday, May 27, 2011

Chapter 3. Environment Variables

Chapter Syllabus

3.1 Environment and Shell Variables

3.2 Setting and Displaying Variables

3.3 Predefined Environment Variables

3.4 Exporting Shell Variables

3.5 Setting the Command Prompt

3.6 The PATH Variable

As soon as a user logs into HP-UX, the shell is invoked and waits for commands from the user. To execute these commands, the shell needs to know some information about the environment being used. For example, to correctly display a file, the shell needs to know which type of terminal is attached to the system. Similarly, when a user issues an extrinsic command, the shell needs to know in which directories it should look for the command. In UNIX terminology, we call this type of information the shell environment.

The shell stores environment information in environment variables. Usually, many types of variables are set in the system startup file (/etc/profile) managed by the system administrator. The users can also set environment variables through the use of a user startup file kept in the home directory (.profile).

Any program that needs environment variables checks the existence and value of these variables at the startup time. For example, the editor program vi needs your terminal information to correctly display and scroll text. When you start the vi editor, it will check the TERM variable. If it understands the terminal type set by the TERM variable, it will start in full screen mode; otherwise, it will start in line editing mode, where you can edit or display only one line of text at a time.

Similarly, the more command needs the TERM variable to display a particular number of text lines, depending on the type of terminal being used.

You can modify and change environment variables set by the system administrator. The system administrator usually sets the PATH variable that shows the search path for the executable commands. But as you start using the UNIX system, you also create your own programs and scripts, and you want the shell to look into the directories containing your own programs as well. For this purpose, you can add your own directory names in the PATH variable.

In this chapter, you will see the difference between environment and shell variables and how to set and display variables. There are many predefined environment variables, and the most important of these will be discussed. Then you will learn how to increase the visibility of a shell variable by exporting it. The default HP-UX command prompt shows little information, and you will see how to add some useful information to it using variables. Since PATH is an important variable, you will learn more about it at the end of the chapter.

3.1 Environment and Shell Variables

When a shell executes a command, UNIX creates a process in memory for that command. This process is called the child process of the shell. Because the shell created this process, the shell is called the parent process of the command process.

You can also invoke a shell within another shell. The newly created shell is the child shell. You will be writing shell scripts when you move to the fourth section of the book. These shell scripts are executed within the parent shell as child processes.

All child processes inherit environment variables from their parent (the shell). On the other hand, shell variables are set locally by the shell and are not visible to any child process. Each child gets a copy of the environment variables and is allowed to make changes to these variables. But it should be kept in mind that

these changes are local to the child process and can't reflect back. This means that changes made to the environment variables are lost as soon as the child process finishes. Or you can say that a child process can't make changes to the parent variables. The differences between shell and environment variables are presented in Table 3-1.

Table 3-1. Comparison of Shell and Environment Variables

Environment Variables

Shell Variables

Also called global variables

Also called local variables

Inherited by all child processes

Not inherited by children

Usually contain system-specific information

Usually used to keep temporary values in shell programs

3 2 Setting and Displaying Variables

When using the POSIX shell, you can set a variable at the command prompt just by entering a variable name followed by an "=" sign and the value you want to assign to the variable. It is a convention to name all user-created variables with uppercase letters, but lowercase letters can be used if needed. Also, a variable name can start with characters of the alphabet only, not with numbers. For example, VAR3 is a legal name for a variable while 3VAR is not. Below is the process of setting a variable.

$ VAR3=TestVar

$

The command prompt appears without any message. Note that there is no space character on either side of the "=" symbol. If you place a space around the = sign, the shell interprets it as a command and displays an error message, as no command with the name VAR3 exists on HP-UX.

The echo command is used to view the value of a particular shell variable. To view the value of our newly created shell variable, use the following method.

$ echo $VAR3

TestVar

$

Notice that we have used a $ symbol to start the variable name. If we don't use the $ symbol, the echo command displays whatever it gets on the command line as is. The $ symbol tells the echo command that the argument is a variable, not a simple text string. The result of using the above command without $ is as follows.

$ echo VAR3

VAR3

$

As you can see, the echo command has displayed its argument text, not the variable value.

Listing All Variables

If you want to list all variables known to your current shell, use the set command.

$ set

EDITOR=vi

EPC_DISABLED=TRUE

ERASE=^H

FCEDIT=/usr/bin/ed

HISTFILE=/home/root/.sh_history

HISTSIZE=400

HOME=/home/boota

INTR=^C

LINENO=1

LOGNAME=boota

MAIL=/var/mail/boota

MAILCHECK=600

MANPATH=/usr/share/man/%L:/usr/share/man:/usr/contrib/man:/

u

sr/local/man/%L:/usr/local/man

NAME=12

OPTIND=1

PATH=/usr/sbin:/baan/bse/bin:/usr/bin:/usr/ccs/bin:/usr/

contrib/bin:/usr/bin/X11:/usr/contrib/bin/X11:/opt/perf/

bin:/u

sr/sbin:/sbin

PPID=26709

PS1='boota on myhp $PWD => '

PS2='> '

PS3='#? '

PS4='+ '

PPID=26709

SHELL=/sbin/sh

TERM=vt100

TMOUT=0

TZ=EST5EDT

VAR3=TestVar

_=set

$

This list will change from system to system. It also depends on what applications

are running on the system, as applications also set their environment variables. We will discuss some of the common variables in the next pages.

Variable Containing More Than One Word

Often a variable has a value that contains space characters in it. If you try to set a variable containing spaces in the normal way, you will get an error message as follows.

$ NAME=Mike Ron

sh: Ron: not found.

$

The shell thought that you were setting a variable NAMEwith value Mike while Ron is a UNIX command. The shell then tried to execute this command and failed. To set variables containing multiple words, we use single or double quotes.

$ NAME="Mike Ron"

$

$ echo $NAME

Mike Ron

$

Single quotes may also be used.

$ NAME='Mike Ron'

$

There is a slight difference between single- and double-quote characters that I will soon elaborate on.

The echo command can be used to display a variable and additional text at the same time. For example, just after displaying the NAME variable, we want to display the number 7. What if we use command echo $NAME7?

$ echo $NAME7

sh: NAME7: Parameter not set.

$

The shell actually started looking for a variable name NAME7 instead of NAME but could not find it. To avoid this ambiguity, we use {} to separate a variable from the rest of the text as follows.

$ echo ${NAME}7

Mike Ron7

$

Many UNIX users put {} around variable names to avoid any ambiguity. The curly brackets must be used any place a shell variable is used with some other text.

Modifying a Variable

Assigning a new value to the same variable name modifies the previous value of the variable. It can be done in two ways. If we just assign a new value, the old value of the variable is destroyed. We can also append to the old value by putting the variable name on the right-hand side of the = symbol at the time of assignment. For example, if we want to add a third part to the NAME variable, it can be done as follows.

$ NAME="$NAME Junior"

$

$ echo $NAME

Mike Ron Junior

$

Note

This is a very useful way to add your own directories to the PATH variable. The PATH variable set by the system administrator contains a list of directories where command files are located. When finding a command, if you want the shell to also search in your own directories, you can use the above method to append your own directory names to the PATH variable.

Single- and Double-Quote Characters

Now we come to the difference between single and double quotes. Consider the above command example by replacing the double quotes with single quotes and watch the result carefully.

$ NAME='$NAME Junior'

$

$ echo $NAME

$NAME Junior

$

This is not what we wanted! What happens is that single-quote characters do not expand any variable name inside them to its value. Instead, anything inside the

single quotes is taken as is and assigned to the variable. One must be careful when using single quotes! The same rule applies when you use single and double quotes with other commands. See the results of two echo commands.

$ NAME= "Mike Ron"

$

$ echo "$NAME Junior"

Mi

ke Ron Junior $ echo '$NAME Junior'

$NAME Junior

$

Removing a Variable

A shell variable can be removed by the unset command on HP-UX. Please note that this command is not available in all UNIX shells.

$ NAME="Mike Ron"

$ echo $NAME

Mike Ron

$ unset NAME

$ echo $NAME

sh: NAME: Parameter not set.

$

Assigning Output of a Command to a Variable

On most keyboards, the back quote character is displayed when you press the "~" key without the SHIFT key. It is used to assign the result of a command to a variable. If you want to assign your login name to a variable NAME, you can use the following command.

$ NAME=`whoami`

$

$ echo $NAME

boota

$

You can also use the back quote character anywhere that you want to substitute the result of a command. In the following example, it is used with echo command.

$ echo "My login name is `whoami`"

My login name is boota

$

3.3 Predefined Environment Variables

There are some standard variables that many HP-UX commands use. These are called predefined because their names are standard. Here are some of these variables and their use by different commands.

PATH is the most commonly used environment variable. It contains the command search path or name of directories where your shell searches for a command when you issue it. Usually it is set up through the system startup file (/etc/profile) and can be modified by a user to add personal directories through the user startup file (.profile). Each directory in the PATH variable is separated by a colon.

HOME is automatically set when a user logs into HP-UX. It contains the path of the user's home directory. To refer to the .profile file in your home directory, you can use $HOME/.profile as the complete path to the file. Please note that there is another way to refer to your home directory in HP-UX, and that is the ~/ combination.

PWD shows the current directory. It is also set automatically whenever you use the cd command. It always has the value of the current directory.

SHELL shows the absolute path of your login shell. It is automatically set at the login time.

TERM contains the name or type of your terminal. It is usually set through the /etc/profile shell startup file using the tset or ttytype command.

PS1 contains the primary command prompt string. This string is displayed in your shell prompt. If $ is displayed as your command prompt, the value of PS1 is a $ symbol.

PS2 contains the secondary command prompt string. That is, if you issue a command that is incomplete, you will see a prompt by the shell with a value of PS2.

MANPATH contains the list of directories where the man command looks for manual pages. A colon separates each directory in the list.

TZ contains the local time zone that was set at the time of HP-UX installation. Commands such as date read this variable.

EDITOR contains the name of the editor you want to use for command line editing or for typing mail messages. You can set this variable in your shell startup file with your favorite editor.

HISTFILE contains the name of the history file where your command history is kept. All of the commands you use go to the history file.

HISTSIZE variable shows how many commands are kept in the history file.

Study Break

Predefined Environment Variables

Knowledge of shell variables is very helpful in understanding the behavior of some commands. Use the command:

echo "Incomplete command test

You will see a ">" symbol in the next line. You get back neither the command prompt nor any other display. You may be wondering what happened to the command. Actually, you issued an incomplete command, missing the closing double quotes. The symbol ">" is the value of the PS2 environment variable that is displayed whenever you use an incomplete command. Just complete the remaining part of the command and press the key at this prompt.

Change this variable so that it gives a more meaningful message, such as "Incomplete command>" and again use the same command to check if it works. Using the set command, see which variables are set on your system. To find out more about an environment variable, get help with the man sh-posix command.

3.4 Exporting Shell Variables

Earlier I mentioned that the shell variables are not visible in child processes whereas environment variables are. We can export shell variables so that they are available in the child processes. The export command is used for this purpose. In our previous example of setting the NAME variable, we can export it to make it visible for other processes that our shell creates.

In the next example, I demonstrate the difference between exported and nonexported variables. First we create a variable NAME and then start a child shell by executing the sh command. When we use the echo command in the child shell for the NAME variable, it is empty. Now we use the exit command to return to the parent shell and export the NAME variable. We start the child shell again, and now the variable is visible in the child shell. Finally, we use exit again to return to the parent shell.

$ NAME="Mike Ron"

$ echo $NAME

Mike Ron

$ sh

$ echo $NAME

$

$ exit

$ export NAME

$ sh

$ echo $NAME

Mike Ron

$ exit

$

Note

If you make a change to an environment variable, always export it. This is necessary so that the correct value of the variable is inherited by the child processes.

3.5 Setting the Command Prompt

The PS1 variable controls the appearance of the user command prompt. A user can modify the command prompt by setting a desired value of PS1. If you want to change your command prompt from a simple $ sign to "My Computer =>", you can use the following command.

$ PS1="My Computer =>"

My Computer =>

As you notice, the command prompt changes as soon as you change the value of PS1. Just to remind you, you also have to export the PS1 variable to make this change visible in the sub-shells.

Adding Useful Information to the Prompt

You can play some tricks with the command prompt to display useful information. For example, it is very handy if the prompt displays the current directory, as it can be hard to remember which directory you are in. We can make a slight change to PS1 to display the current directory path.

$ PS1="My Computer \$PWD =>"

My Computer /home/boota =>

As you can see, the prompt changes and the current directory is there. Now, whenever you use the cd command to change the current directory, the PWD environment variable changes, and your prompt also changes to show the new current directory. Similarly, it is possible to have your login name and the computer name in the command prompt along with the current directory, as shown in this example.

$ PS1= "`whoami` on `uname -n` \$PWD =>"

boota on myhp /home/boota =>

Note

This is very useful if you work in a network environment and often log into different machines with different names. It is the command prompt that tells you which machine you are on, which login name you are using, and what the current directory is. Does this seem interesting to you? You can also try to change your prompt to include the date and time, blinking characters, and so on, depending on the type of terminal you are using.

3.6 The PATH Variable

PATH is one of the most important variables a user has to deal with. It contains the names of the directories where the shell searches for commands. These directory names are separated by a colon.

/usr/bin:/usr/ccs/bin:/usr/contrib/bin:/bin

If you have placed your own commands in your home directory, you can add your home directory to the PATH variable with the following command.

$ PATH=$PATH:$HOME

$

Although you are free to add the HOME directory at the beginning or end of the PATH variable, it is always desirable to add your own directory names at the end. This is because, if you accidentally use a program or script name, the same as a standard HP-UX command, your program will be executed instead of the HP-UX command, as it will be found first by the shell.

Test Your Knowledge

1:

Just after login, you issue the command echo HOME. What will be the output of this command?

A. It displays the HOME directory name of the user.

B. It displays nothing, as the HOME variable is not yet defined.

C. It displays the word HOME.

D. none of the above

2:

What is not true about the PATH variable?

A. It shows the path of the current directory.

B. It shows the names of directories that are checked when searching for a command.

C. It is usually set in the /etc/profile by the system administrator.

D. The value of the PATH variable can be changed by a user.

3:

You have a variable "ABC" with value "Alphabets". You use the following command to change its value.

ABC='All $ABC'

What will be the new value of the variable?

A. All $ABC

B. All Alphabets

C. All ABC

D. The variable value can't be changed with this command. It remains "Alphabets".

4:

To assign the output of a command to a variable, we use:

A. double-quote characters

B. comma characters

C. single-quote characters

D. back-quote characters

5:

The value of the PS2 variable on your system is ">" (greater-than symbol). You issue an incomplete command. What will be the shell's response?

A. The shell will issue an error message showing that the command is incomplete.

B. The shell will display "PS2".

C. The shell will try to execute that part of the command that is supplied.

D. The shell will give a ">" prompt and wait for you to complete the command.

6:

What is wrong with the shell variable name 3Xyab2?

A. It is not a legal name, because a shell variable must contain only uppercase letters.

B. It is not legal, because variables can only have uppercase or lowercase letters, not a combination.

C. It starts with a digit, so it is not a legal name.

D. It ends with a digit, so it is not a legal name.

No comments:

Post a Comment