dcsimg

On the Right PATH

If you've ever spent any time writing MS-DOS batch files, you're probably familiar with the concept of "environment variables." However, if that term makes you wonder if we are talking about the weather, then this article is for you. This month we're going to look at environment variables under Linux, and the particular environment variable PATH, which facilitates access to software programs that are installed on your Linux system.

If you’ve ever spent any time writing MS-DOS batch files, you’re probably familiar with the concept of “environment variables.” However, if that term makes you wonder if we are talking about the weather, then this article is for you. This month we’re going to look at environment variables under Linux, and the particular environment variable PATH, which facilitates access to software programs that are installed on your Linux system.

When Environments Vary

As you can probably surmise from the term, an environment variable is nothing more than a name that can have an associated value. The following example shows how to create an environment variable and bind a value to it:


set steps=39

When issued at the Linux command prompt, this command creates an environment variable named steps and associates the value 39 with it. You can view the value of this environment variable by issuing the command:


echo $steps

which produces the output:


39

Notice that, when referencing the value of an environment variable, you prefix the name of the variable with a dollar sign ( $ ). Also notice that no dollar sign appears in the command used to set the value of the variable.

If you want to change the value associated with an environment variable, simply bind it to a different value:


set steps=10

Environment variables can be given non-numeric values as easily as they can be given numeric values. Simply enclose within quotes the text you want to assign as the value of the variable. For example:


set today=”Monday”

If you ever want to eliminate an environment variable, you can issue a command such as:


unset steps

This command destroys the environment variable steps . If, after issuing this command, you attempt to use echo to view the value of steps , you will receive an empty output line.




Environment Variables in Shell Expressions


In this column, we look at ways to assign a literal value to an environment variable. However, much more sophisticated assignments are possible. For instance, suppose you want the environment variable zero to hold the value 0 . The following assignment statement assigns the value 0 to the environment variable none :


none=$zero


Notice how the name of the referenced variable, zero , is prefixed with a dollar sign.


Still more sophisticated expressions are possible. For instance, the shell command:


x=$[1+2]


evaluates the arithmetic expression within the $[] construct and assigns the result, 3, to the environment variable x .


And, here’s a series of statements that calculate the area of a rectangle:


length=3
width=4
area=$[$length*$width]
echo $area


Note that calculations are performed using integer arithmetic. So, if you want to calculate the area of a circle, you’ll have to resort to some cleverness. Hint: scale the values by a power of ten corresponding to the number of decimal places you want.

Manipulating Your Environment

It’s worth pointing out that although we’ve been referring to environment variables as things that are used by “Linux,” it’s not actually Linux itself that makes use of them, but rather the shell (bash is the default Linux shell). For this reason, you may sometimes hear environment variables referred to as “shell variables.” For most purposes, they mean the same thing. For the sake of keeping this discussion simple however, and to avoid getting into a discussion of the relationship between the shell and Linux itself (which is beyond the scope of this article), we’ll continue to refer to environment variables as being used by Linux.

In any case, Linux uses environment variables to communicate data to programs. A host of environment variables serve this purpose. To see these variables and their associated values, issue the command set . The result should resemble Figure One, though you’ll likely see different variables and values. Table One describes some of the most important environment variables.




Table One: Important Environmental Variables



























Environment Variable
Description
BASH Path of the BASH executable file
BASH_ENV Path of the BASH environment file, which specifies BASH options
BASH_VERSION Version of BASH
COLUMNS Width, in characters, of console window
EUID Effective user ID
HISTFILE Path of the BASH command history file
HISTFILESIZE Maximum number of lines recorded in history file
HISTSIZE Maximum number of commands recorded in history file
HOME Path of user’s home directory
HOSTNAME Name of the host
IFS Field separator (white space) characters
LINES Length, in lines, of console window
LOGNAME User’s log in name
LS_COLORS Options for ls command
OSTYPE Operating system name (“Linux”)
PATH Program path
PPID Process ID of the shell’s parent process
PS1 Command prompt string
PS2 Continuation prompt string
PS4 Execution trace string
PWD Current working directory
SHELL Path of the shell executable
SHLVL Number of nested shell invocations
TERM Terminal type
UIDUser ID
USER User name




Figure One: Typical Environment Variables and Their Values


[bmccarty@home bmccarty]$ set
BASH=/bin/bash
BASH_ENV=/home/bmccarty/.bashrc
BASH_VERSION=1.14.7(1)
COLUMNS=85
EUID=2188
HISTFILE=/home/bmccarty/.bash_history
HISTFILESIZE=1000
HISTSIZE=1000
HOME=/home/bmccarty
IFS=
INPUTRC=/etc/inputrc
LINES=49
LOGNAME=bmccarty
LS_COLORS=
OPTERR=1
OPTIND=1
OSTYPE=Linux
PATH=/usr/bin:/bin:/usr/bin:/usr/X11R6/
bin:/usr/local/bin:/home/bmccarty/bin
PPID=26420
PS1=[\u@\h \W]\$
PS2=>
PS4=+
PWD=/home/bmccarty
SHELL=/bin/bash
SHLVL=1
TERM=vt102
UID=2188
USER=bmccarty
USERNAME=
_=bash

Perhaps the most important environment variable is PATH . Here’s a typical value for PATH :


/usr/bin:/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:/home/bmccarty/bin

Notice that the value consists of a series of paths, each separated from its neighbor by a colon. Each such path denotes a directory. When you run a program, you can specify the full (or “absolute”) path to the program file. For example, /bin/sort. However, typing the full path is tedious, so most users type merely sort, omitting the directory name. The shell locates the program file by using the component paths that make up the value of the PATH variable. It searches the paths one by one until it finds the specified program or fails to find it.

If you’re curious to learn the path associated with a program, you can issue the which command. For instance, issuing the command:


which sort



yields the output:


/bin/sort

telling you that the full path of the sort command is /bin/sort .

You may wonder where the value of the PATH environment variable originates. To find out, check the script file .bash_profile that generally resides in each user’s home directory. The BASH shell executes the contents of this file when the shell starts up (and remember — as we mentioned earlier, it’s really the shell, not Linux, that keeps track of and makes use of environment variables). Figure Two shows the contents of a typical .bash_ profile file.




Figure Two: Contents of a Typical bash_profile File


# .bash_profile

# Get the aliases and functions

if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin
BASH_ENV=$HOME/.bashrc
USERNAME=”
unset MAILCHECK

export USERNAME BASH_ENV PATH

Notice the line that assigns a value to PATH , which appears just below the middle of the file:


PATH=$PATH:$HOME/bin

This line takes the existing value of PATH , appends a colon, the value of the HOME environment variable, and the text /bin, and assigns the result to PATH . From Table One, you can see that the HOME environment variable holds the path of the user’s home directory, so the effect of the assignment is to add the bin subdirectory of the user’s home directory to the PATH . Because of this, the user can execute programs stored in the user’s bin subdirectory without having to type the full path, a valuable convenience.

Of course, this explanation concerns only the last component path of the PATH environment variable. Before executing the user’s .bash_profile script, the BASH shell executes the system’s BASH profile script, /etc/profile. Figure Three shows the typical contents of this file.




Figure Three: Contents of a Typical /etc/profile File


# /etc/profile

# System wide environment and startup programs
# Functions and aliases go in /etc/bashrc

PATH=”$PATH:/usr/X11R6/bin:/usr/local/bin”
PS1=”[\u@\h \W]\\$ ”

ulimit -c 1000000
if [ 'id -gn' = 'id -un' -a 'id -u' -gt 14 ]; then
umask 022
else
umask 022
fi

USER=’id -un’
LOGNAME=$USER
MAIL=”{mail.apu.edu}INBOX”
NNTPSERVER=news.apu.edu
HOSTNAME=’/bin/hostname’
HISTSIZE=1000
HISTFILESIZE=1000

INPUTRC=/etc/inputrc
export PATH PS1 HOSTNAME HISTSIZE HISTFILESIZE USER
LOGNAME MAIL INPUTRC NNTPSERVER

for i in /etc/profile.d/*.sh ; do
if [ -x $i ]; then
. $i
fi
done

unset i

Notice the sixth line of the file:


PATH=”$PATH:/usr/X11R6/bin:/usr/local/bin”

As you can see, this assignment adds two component paths to the value of PATH/usr/X11R6/bin and /usr/local/bin .

The remaining components of the PATH are inherited from the process that invokes the shell — that is, the shell’s parent process. Under Linux/Unix, processes are started or “spawned” by a “parent” process. The parent is responsible for passing all of its environment variables to the “child” process. This topic is beyond the scope of this article, but hopefully this basic explanation will help you understand what we’re talking about here.

The export command, which is used in both /etc/profile and .bash_profile, requests that the specified environment variable, or variables, be passed on to programs and processes initiated by the shell. If you write a shell script that modifies an environment variable, you will need to include an export command in your script. Otherwise, the intended recipient won’t receive the environment variable.

Environment Variable Tips and Techniques

Suppose you frequently run programs that reside in /opt/bin, a directory that does not appear in the value of your PATH environment variable. If you don’t want to type the full path of each program, you can issue the following command:


PATH=$PATH:/opt/bin

Thereafter, you can type merely the name of the program rather than the full path.

However, you must issue this command each time you log in, because the values of environment variables are discarded when the shell terminates. To avoid even this tedium, you can modify the contents of your .bash_ profile file, changing the line:


PATH=$PATH:$HOME/bin

to read:


PATH=$PATH:$HOME/bin:/opt/bin

The components of the PATH are searched in the order in which they appear. So, if two program files have the same name, the file stored in the directory mentioned toward the front of the PATH is executed in preference to the file mentioned toward the end. So, if you wanted files in /opt/bin to be executed in preference to identically named files residing in other directories, you could reorder the components of the PATH environment variable with the following:


PATH=/opt/bin:$PATH:$HOME/bin

On The Right Path

Now that you understand environment variables and PATH , you might want to review last month’s Newbies column on scripts. By combining knowledge of scripts with an understanding of environment variables, you can perform some pretty useful, even amazing, tasks. Next month, we’ll continue our tour of shell programming. Until then, stay on the PATH .




Quotes and More Quotes


If you place a reference to an environment variable inside double quotes, the shell will replace it with the value of the environment variable. For instance:


$y=”$x”


has the same effect as:


$y=$x


This lets you construct text strings that contain the values of variables. For example:


echo “The current PATH is $PATH.”


produces output resembling:


The current PATH is /usr/bin:/bin:/usr/bin:/usr/X11R6/bin:/
usr/local/bin:/home/bmccarty/bin.


However, single quotes do not share this property. The shell will not replace a reference within single quotes to an environment variable with its value. So, the command:


echo ‘The current PATH is $PATH.’


produces the output:


The current PATH is $PATH .



Bill McCarty is an associate professor at Azusa Pacific University. He can be reached at bmccarty@apu.edu.

Fatal error: Call to undefined function aa_author_bios() in /opt/apache/dms/b2b/linux-mag.com/site/www/htdocs/wp-content/themes/linuxmag/single.php on line 62