This chapter introduces you to the operating system shells. After completing this chapter, you will be able to:
Understand the purpose and general features of the C shell and the Bourne, Korn, and POSIX shells
Change your shell
Use command entry aids common to all shells
Understand your shell environment as well as the role of login scripts, environment variables, and shell variables
Set and clear environment and shell variables
Understand how the shell finds commands on your system
Write logout scripts
Write and run basic shell procedures
This chapter covers features common to all operating system shells,
with some descriptions of shell differences.
For detailed information on specific C shell
and Bourne, Korn, or POSIX shell features, see
Chapter 8.
7.1 Purpose of Shells
The user interfaces to the operating system are called shells. The shells are programs that interpret the commands you enter, run the programs you have asked for, and send the results to your screen.
The operating system provides the following shells:
The Bourne shell (system default)
The C shell
The Korn shell
The POSIX shell
You may access any shell, depending upon the security restrictions in effect on your system as well as upon the licensing restrictions of the Korn shell. In any case, all shells perform the same basic function: they let you perform work on your system by executing commands.
In addition to interpreting commands, the shell also can be used as a programming language. You can create shell procedures that contain commands. Shell procedures are executed in the same way that you execute a program -- on the command line after the shell prompt.
When you run a
shell procedure, your current shell creates or
spawns
a subshell.
A subshell is a new shell your current shell creates to run a
program.
Thus, any command the shell procedure executes (for example,
cd
) leaves the invoking shell unaffected.
Shell procedures provide a means of carrying out tedious commands, large or complicated sequences of commands, and routine or repetitive tasks.
See
Section 7.10
for more information on shell programming.
7.2 Summary of C, Bourne, Korn, and POSIX Shell Features
The operating system provides the following shells that have both command execution and programming capabilities:
The Bourne shell (sh
)
This is a simple shell that is easily used in programming. It usually is represented by a dollar sign ($) prompt. This shell does not provide either the interactive features or the complex programming constructs (arrays and integer arithmetic) of the C shell or the Korn and POSIX shells.
The Bourne shell also provides a restricted shell (Rsh
).
For more information, see
Section 7.2.2.
The C shell (csh
)
This shell is designed for interactive use. It usually is represented by a percent sign (%) system prompt. The C shell provides some features for entering commands interactively:
A command history buffer
Command aliases
File name completion
Command line editing
For more information on these features, see Section 7.2.1.
The Korn shell (ksh
)
This shell combines the ease of use of the C shell and the ease of programming of the Bourne shell. The system prompt is usually a dollar sign ($) prompt. The Korn shell provides these features:
The interactive features of the C shell
The simple programming syntax of the Bourne shelll
Command line editing
The fastest execution time
Upward compatibility with the Bourne shell (that is, most Bourne shell programs will run under the Korn shell)
For more information on these features, see Section 7.2.1.
The POSIX shell (sh
)
This shell conforms to the IEEE POSIX standard.
It is very similar to
the Korn shell.
In this book, the discussion of the Korn shell and the POSIX shell
are combined.
See the
sh
(1p)
and the
standards
(5)
reference pages for
information on this standard.
The POSIX shell is another designator for the Korn shell.
7.2.1 More Information on C and Korn or POSIX Shell Features
The C shell and the Korn or POSIX shells offer the following interactive features:
Command history
The command history buffer stores the commands you enter and lets you display them at any time. As a result, you can select a previous command, or parts of previous commands, and then reexecute them. This feature may save you time because it lets you reuse long commands instead of retyping them. In the C shell, this feature requires some setup in the .cshrc file; in the Korn and POSIX shells this feature is automatically provided.
Command aliases
The command
aliases feature lets you abbreviate long command lines or rename commands.
You do this by creating aliases for long command lines that you frequently
use.
For example, assume that you often need to move to the directory
/usr/chang/reports/status
.
You could create an alias
status
that could move you to that directory whenever you enter
status
on the command line.
In addition, aliases let you make up
more descriptive names for operating system commands.
For example, you could
define an alias named
rename
for the
mv
command.
File name completion
In the C shell, the file name completion feature saves typing by allowing you to enter a portion of the file name. When you press the Escape key, the shell will complete the file name for you. See Section 8.2.4 for more information about file name completion in the C shell.
In the Korn or POSIX shell, you can ask the shell to display a list of file names that match the partial name you entered. You then may choose among the displayed file names. See Section 8.4.5 for more information about file name completion in the Korn or POSIX shell.
The Korn and POSIX shells
provide an inline editing feature that allows you to retrieve a previously
entered command and edit it.
To use this feature, you must know how to use
a text editor such as
vi
or
emacs
.
For more information about these shell features, see
Chapter 8.
7.2.2 The Restricted Bourne Shell
The operating system enhances system security by providing specified
users a limited set of functions with a restricted version of the Bourne shell
(Rsh
).
When these specified users log in to the system,
they are given access to the Restricted Bourne shell only.
Your system administrator determines
who has access to the Restricted Bourne shell.
A restricted shell is useful for installations that require a
more controlled shell environment.
As a result, the system administrator can
create user environments that have a limited set of privileges and capabilities.
For example, all users that are guests to your system might be allowed access
under the user name
guest
.
When logging in to your system,
user
guest
would be assigned a restricted shell.
The actions of
Rsh
are identical to those of
sh
, except that the following actions are not allowed:
Changing directories.
The
cd
command is
deactivated.
Specifying pathnames or command names containing a slash ( / ).
Setting the value of the PATH or the SHELL variables. For more information on these variables, see Section 7.5.2.
Redirecting output with the right-angle brackets (> and >>).
For more detailed information on
Rsh
, see the
sh
(1b)
reference page.
For information on how system administrators create restricted
shells, see your system administrator.
7.3 Changing Your Shell
Whenever you log in, you automatically are placed in a shell specified by your system administrator. However, depending upon the security features in effect on your system, you can enter commands that will let you do the following:
Determine which shell you are running
Temporarily change your shell
Permanently change your shell
The following sections describe these operations.
7.3.1 Determining What Shell You Are Running
To determine what shell you currently are running, enter the following command:
echo $SHELL
The file name of the shell you are running will display.
In the following example, assume that you are running the Bourne shell
(sh
):
$
echo $SHELL
/usr/bin/sh $
Table 7-1 lists the file name that displays for each shell as well as the default system prompt for users other than root (your system prompt may vary).
Table 7-1: Shell Names and Default Prompts
Shell | Shell Name | Default Prompt |
Bourne | sh |
$ |
Restricted Bourne | Rsh |
$ |
C | csh |
% |
Korn | ksh |
$ |
POSIX | sh |
$ |
7.3.2 Temporarily Changing Your Shell
You may experiment with using other shells if the security features on your system allow it.
To temporarily change your shell, enter the following command:
shellname
The shellname is the file name of the shell you want to use. See Table 7-1 for valid shell file names to enter on the command line. Once the shell is invoked, the correct shell prompt is displayed.
Once you are done using the new shell, you can return to your default
shell by entering
exit
or by pressing Ctrl/D.
For example, assume that the Korn shell is your default shell. To change to the C shell and then back to the Korn shell, enter the following commands:
$
/usr/bin/csh
%
exit
$
Note
If you are using the Restricted Bourne shell, you cannot change to another shell.
7.3.3 Permanently Changing Your Shell
You may permanently change your default shell if the security features
on your system allow it.
If your current shell is the C shell, use the
chsh
command to change your default shell.
If you do not use the C shell,
change your default shell by contacting your system administrator.
In the C shell, enter the following command to change the default shell:
%
chsh
Changing login shell for user.
Old shell: /usr/bin/csh New shell:
Enter the name of the new shell. See Table 7-1 for valid shell names to enter on the command line.
After entering the
chsh
command, you must log out
and log in again for the change to take effect.
7.4 Command Entry Aids
The following features of all operating system shells help you do your work:
The ability to enter multiple commands and command lists
Pipes and filters
The ability to group commands
Quoting
7.4.1 Using Multiple Commands and Command Lists
The shell usually takes the first word on a command line as the name of a command and then takes any other words as arguments to that command. The shell usually considers each command line as a single command. However, you can use the operators in Table 7-2 to execute multiple commands on a single command line.
Table 7-2: Multiple Command Operators
Operator | Action | Example |
; | Causes commands to run in sequence. | cmd1 ; cmd2 |
&& | Runs the next command if the current command succeeds. | cmd1 && cmd2 |
|| | Runs the next command if the current command fails. | cmd1 || cmd2 |
| | Creates a pipeline. | cmd1 | cmd2 |
The following sections describe running commands in sequence (;), running
commands conditionally (|| and &&), and using pipelines ( | ).
7.4.1.1 Running Commands in Sequence with a Semicolon (;)
You can enter more than one command on a line if you separate commands with the semicolon (;).
In the following example, the shell runs
ls
and waits
for it to finish.
When
ls
is finished, the shell runs
who
, and so on through the last command:
$
ls ; who ; date ; pwd
change file3 newfile amy console/1 Jun 4 14:41 Tue Jun 4 14:42:51 CDT 1999 /u/amy $
If any one command fails, the others still execute.
To make the command line easier to read, separate commands from the
semicolon (;) with blanks or tabs.
The shell ignores blanks and tabs used
in this way.
7.4.1.2 Running Commands Conditionally
When you connect commands with two ampersands (&&
)
or vertical bars (||
), the shell runs the first command
and then runs the remaining commands only under the following conditions:
The shell runs the next command only if the current command completes (a command indicates successful completion when it returns a value of zero).
The shell runs the next command only if the current command does not complete.
The syntax for the two-ampersand (&&
) operator
follows:
cmd1
&&
cmd2
&&
cmd3
&&
cmd4
&&
cmd5
If cmd1 succeeds, the shell runs cmd2. If cmd2 succeeds, the shell runs cmd3, and on through the series until a command fails or the last command ends. (If any command fails, the shell stops executing the command line).
The syntax for the two-vertical-bar (||
) operator
follows:
cmd1
||
cmd2
If cmd1 fails, then the shell runs cmd2. If cmd1 succeeds, the shell stops executing the command line.
For example, suppose that the command
mysort
is a
sorting program that creates a temporary file (mysort.tmp
)
in the course of its sorting process.
When the sorting program finishes successfully,
it cleans up after itself, deleting the temporary file.
If, on the other hand,
the program fails, it may neglect to clean up.
To ensure deletion of
mysort.tmp
, enter the following command line:
$
mysort || rm mysort.tmp
$
The second command executes only if the first command fails.
7.4.2 Using Pipes and Filters
A pipe is a one-way connection between two related commands. One command writes its output to the pipe, and the other process reads its input from the pipe. When two or more commands are connected by the pipe ( | ) operator, they form a pipeline.
Figure 7-1
represents the flow of input and output through
a pipeline.
The output of the first command (cmd1)
is the input for the second command (cmd2); the
output of the second command is the input for the third command (cmd3).
Figure 7-1: Flow Through a Pipeline
A
filter
is a command that reads its standard input, transforms
that input, and then writes the transformed input to standard output.
Filters
are used typically as intermediate commands in pipelines - that is,
they are connected by a pipe ( | ) operator.
For example, to
cause the
ls
command to list recursively the contents of
all directories from the current directory to the bottom of the hierarchy,
and then to display the results, enter the following command:
$
ls -R | pg
In this
example, the
pg
command is the filter because it transforms
the output from the
ls -R
command and displays it
one screen at a time.
Certain commands that are not filters have a flag that causes them to
act like filters.
For example, the
diff
(compare files)
command ordinarily compares two files and writes their differences to standard
output.
The usual format for
diff
follows:
diff
file1 file2
However, if you use the dash (-) flag in place of one
of the file names,
diff
reads standard input and compares
it to the named file.
In the following pipeline,
ls
writes the contents
of the current directory to standard output.
The
diff
command
compares the output of
ls
with the contents of a file named
dirfile
, and writes the differences to standard output one page
at a time (with the
pg
command):
$
ls | diff - dirfile | pg
In the following example, another kind of filter program (grep
)
is used:
$
ls -l | grep r-x | wc -l
12 $
In this example, the following takes place:
The
ls -l
command lists in long format
the contents of the current directory.
The output of
ls -l
becomes the standard
input to
grep r-x
, a filter that searches for the files
in its standard input for patterns with permissions of
r-x
,
and writes all lines that contain the pattern to its standard output.
The standard output of
grep r-x
becomes
the standard input to
wc -l
, which displays
the number of files matching the
grep
criteria in the standard
input.
To get the same results without using a pipeline, you would have to do the following:
Direct the output of
ls -l /user
to a file.
For example:
$
ls -l > file1
Use
file1
as input for
grep r-x
and redirect the output of
grep
to another file.
For example:
$
grep r-x file1 > file2
Use the output file of
grep
as input for
wc -l
.
For example:
$
wc -l file2
As the preceding procedure demonstrates, using a pipeline is a much easier way to perform the same operations.
Each command in a pipeline runs as a separate process.
Pipelines operate in one direction only (left to right), and all processes
in a pipeline can run at the same time.
A process pauses when it has no input
to read or when the pipe to the next process is full.
7.4.3 Grouping Commands
The shell provides two ways to group commands, as shown in Table 7-3.
Table 7-3: Command Grouping Symbols
Symbols | Action |
(commands) | The shell creates a subshell to run the grouped
commands
as a separate process. |
{commands} | The shell runs the grouped
commands
as a unit.
Braces can only be used in the Bourne, Korn, and POSIX shells. |
The following sections describe the command grouping symbols of
Table 7-3
in greater detail.
7.4.3.1 Using Parentheses ( )
In the following command grouping, the shell runs the commands enclosed in parentheses as a separate process:
$
(cd reports;ls);ls
The shell creates a
subshell
(a separate shell program) that moves to the
reports
directory and lists the files in that directory.
After the subshell
process is complete, the shell lists the files in the current directory (ls
).
If this command were written without the parentheses, the original shell
would move to the
reports
directory, list the files in
that directory, and then list the files in that directory again.
There would
be no subshell and no separate process for the
cd reports;ls
command.
The shell recognizes the parentheses wherever they occur in the command
line.
To use parentheses literally (that is, without their command-grouping
action), quote them by placing a backslash ( \ ) immediately
before either the open parenthesis [(] or the close parenthesis [)], for example,
\(
.
For more information on quoting in the shell, see
Section 7.4.4.
7.4.3.2 Using Braces { }
Using braces is valid only in the Bourne, Korn, and POSIX shells.
When commands are
grouped in braces, the shell executes them without creating a subshell.
In
the following example, the shell runs the
date
command,
writing its output to the
today.grp
file, and then runs
the
who
command, writing its output to
today.grp:
$
{ date; who ;} > today.grp
$
If the commands were not grouped together with braces, the shell
would write the output of the
date
command to the display
and the output of the
who
command to the file.
The shell recognizes braces in pipelines and command lists, but only
if the left brace is the first character on a command line.
7.4.4 Quoting
Reserved characters are characters such as the left-angle bracket (<), the right-angle bracket (.), the pipe (|), the ampersand (&), the asterisk (*), and the question mark (?) that have a special meaning to the shell. See Chapter 8 for lists of reserved characters for each operating system shell.
To use a reserved character literally (that is, without its special meaning), quote it with one of the three shell quoting conventions, as shown in Table 7-4.
Table 7-4: Shell Quoting Conventions
Quoting Convention | Action |
\ | Backslash - Quotes a single character. |
' ' | Single quotes - Quotes a string of characters (except the single quotation marks themselves). |
" " | Double quotes - Quotes a string of
characters (except
$ ,
` , and
\ ). |
The following sections describe the quoting conventions of
Table 7-4
in greater detail.
7.4.4.1 Using the Backslash ( \ )
To quote a single character, place a backslash ( \ ) immediately before that character, as in the following:
$
echo \?
? $
This command displays a single question mark (?) character.
7.4.4.2 Using Single Quotes (' ')
When you enclose a string of characters in single quotes, the shell
takes every character in the string (except the
'
itself)
literally.
Single quotes are useful when you do not want the shell to interpret:
Reserved characters such as the dollar sign ($
),
the grave accent (
`
), and the backslash ( \
)
Variable names
The following example shows how single quotes are used when you want to display a variable name without having it being interpreted by the shell:
$
echo 'The value of $USER is' $USER
The value of $USER is amy $
The
echo
command displays the
variable name
$USER
when it appears within single
quotes, but interprets the value of
$USER
when
it appears outside the single quotes.
For information on variable assignments, see
Section 7.7.1.
7.4.4.3 Using Double Quotes (" ")
Double quotes (" "
) provide a special form of quoting.
Within double quotes, the reserved characters dollar sign ($
),
grave accent (
`
), and backslash ( \
) keep their special meanings.
The shell takes literally
all other characters within the double quotes.
Double quotes are most frequently
used in variable assignments.
The following example shows how double quotes are used when you want to display brackets (usually reserved characters) in a message containing the value of the shell variable:
echo "<<Current shell is $SHELL>>"
<<Current shell is /usr/bin/csh>> $
For information on variable assignments, see
Section 7.7.1.
7.5 The Shell Environment
Whenever you log in, your default shell defines and maintains a unique working environment for you. Your environment defines such characteristics as your user identity, where you are working on the system, and what commands you are running.
Your working environment is defined by both environment variables and shell variables. Your default login shell uses environment variables and passes them to all processes and subshells that you create. Shell variables are valid only for your current shell and are not passed to subshells.
The following sections discuss the shell environment, how it is configured,
and how you can tailor it.
7.5.1 The login Program
Whenever you log in, the
login
program is run.
This
program actually begins your login session using data stored in the
/etc/passwd
file, which contains one line of information about each
system user.
The
/etc/password
file contains your user
name, your password (in encrypted form), your home directory, and your default
shell.
For more information on the
/etc/passwd
file, see
Chapter 5.
The
login
program runs after you enter your user
name at the
login:
prompt.
It performs the following functions:
Displays the
Password:
prompt (if you have
a password).
Verifies the user name and password you entered against what
is contained in the
/etc/passwd
file.
Starts running the shell process.
Runs system login scripts and your personal login scripts. See Section 7.6 for more information.
Your shell environment defines and maintains a unique working environment for you. Most of the characteristics of your working environment are defined by environment variables.
Environment variables consist of a name and a value. For example, the environment variable for your login directory is named HOME, and its value is defined automatically when you log in.
Some environment variables are set by the
login
program,
and some can be defined in the login script that is appropriate for your shell.
For example, if you use the C shell, environment variables typically will
be set in the
.cshrc
login script.
For more information
on login scripts, see
Section 7.6.
Table 7-5 lists selected environment variables that can be used by all operating system shells. Most of the values of these variables are set during the login process, and are then passed to each process that you create during your session.
Table 7-5: Selected Shell Environment Variables
Environment Variable | Description |
HOME |
Specifies the name of your login directory,
the directory that becomes the current directory upon completion of a login.
The
cd
command uses the value of
HOME
as its default value.
The
login
program sets this variable,
and it cannot be changed by the individual user. |
LOGNAME |
Specifies your login name. |
MAIL |
Specifies the pathname of the file used by
the mail system to detect the arrival of new mail.
The
login
program sets this variable based upon your user name. |
PATH |
Specifies the directories and the directory order that your system uses to search for, find, and execute commands. This variable is set by your login scripts. |
SHELL |
Specifies your default shell.
This variable
is set by
login
using the shell specified in your entry
in the
/etc/passwd
file. |
TERM |
Specifies the type of terminal you are using. This variable usually is set by your login script. |
TZ |
Specifies the current time zone and difference from Greenwich mean time. This variable is set by the system login script. |
LANG |
Specifies the locale of your system, which
is comprised of three parts: language, territory, and character code set.
The default value is the C locale, which implies English for language, U.S.
for territory, and ASCII for code set.
LANG
can be set
in a login script. |
LC_COLLATE |
Specifies the collating sequence to use when
sorting names and when character ranges occur in patterns.
The default value
is the ASCII collating sequence.
The
LC_COLLATE
variable
can be set in a login script. |
LC_CTYPE |
Specifies the character classification rules
used in the
ctype
functions for the current locale.
The
default value is the classification for ASCII characters.
The
LC_TYPE
variable can be set in a login script. |
LC_MESSAGES |
Specifies the language used for yes/no prompts. The default value is American English, but your system may specify another language. |
LC_MONETARY |
Specifies the monetary format for your system.
The default value is the American format for monetary figures.
The
LC_MONETARY
variable can be set in a login script. |
LC_NUMERIC |
Specifies the numeric format for your system.
The default value is the American format for numeric quantities.
The
LC_NUMERIC
variable can be set in a login script. |
LC_TIME |
Specifies the date and time format for your
system.
The default value is the American format for dates and times.
The
LC_TIME
variable can be set in a login script. |
Many of these environment variables can be set during the login process by the appropriate login script (see Section 7.6). However, you may reset them as well as set those for which no default values have been provided. See Section 7.7.1 for more information.
For more information on the
LANG
,
LC_COLLATE
,
LC_CTYPE
,
LC_MESSAGES
,
LC_MONETARY
,
LC_NUMERIC
, and
LC_TIME
variables, refer to
Appendix C
which explains the
variables in the context of other system features that support the languages
and customs of different countries.
You may also create your own environment variables.
For example, some
systems have more than one mail program available to users.
Assume that
mail
and
mh
are available on your system and
that each has its own pathname.
As a result, you could define a variable for
the pathname of each mail program.
For more information about environment variables specific to each operating
system shell, see
Chapter 8.
For a complete list of operating
system shell environment variables, see the
sh
(1b),
sh
(1p),
csh
(1),
and
ksh
(1)
reference pages.
7.5.3 Shell Variables
Shell variables are valid only for your current shell and are not passed to subshells. Consequently, they can be used only in the shell in which they are defined. In other words, they may be thought of as local variables.
Shell variables can be accessed outside of the current shell by becoming environment variables. For more information about environment variables, see Section 7.7.1.
You may also create your own shell variables.
For example, some mail
programs use the
PAGER
variable to define the program that
displays mail.
Suppose that your mail program is
mailx
.
You could define the
PAGER
variable to use the
more
program to display your mail.
For information on how to set shell variables, see
Section 7.7.1.
7.6 Login Scripts and Your Environment
A login script is a file that contains commands that set up your user environment. There are two kinds of login scripts:
System login scripts for all users of a particular shell
These scripts create a default environment for all users and are maintained
by your system administrator.
The Bourne, Korn, and POSIX shells use a system login script
called
/etc/profile
.
The C shell uses a script called
/etc/csh.login
.
See
Table 7-6
for the pathnames
of system login scripts.
When you log in, the commands in this file are executed first.
Local login scripts in your default login directory
These
scripts let you tailor your environment, and you maintain the appropriate
file.
For example, you could change the default search path or shell prompt.
If your default shell (see
Section 7.3) is the Bourne, Korn, or POSIX shell,
the login script file is called
.profile
.
The C shell
uses the file called
.login
.
A local login script is executed
after the system login script.
If
the C shell is your default, your environment can be further tailored with
the
.cshrc
file.
It executes when you log in (before
.login
) and whenever you spawn a subshell.
The
.cshrc
file is the C shell mechanism that automatically makes variables available
to subshells.
On startup, the Korn and POSIX shells will also execute any file pointed to
by the
ENV
environment variable.
This variable is typically
set in the
.profile
file and is set to another file, usually
in the
$HOME
directory.
Some users prefer to call this
file
.kshrc
or
.envfile
.
To use such
a file, place a line like this in your
.profile
file:
ENV= ~ /.kshrc
Such a file typically contains
shell variables, alias definitions, and function definitions.
This file will
be referred to as
.kshrc
for the remainder of this document.
Creating your own login script is not mandatory as the system login script for your shell provides a basic environment. Your system administrator may have created a local login script that you can modify with a text editor.
When you are new to the system, you may want to use the default environment established for you. However, as you become more familiar with the system, you may want to create or modify your own login script.
Table 7-6
lists the system login and local login scripts
for each operating system shell.
All scripts for a given shell run whenever
you log in to your system.
In addition, when you enter
csh
at any shell prompt or execute a C shell script, the
.cshrc
file executes and creates an environment for the C subshell.
Table 7-6: System and Local Login Scripts
Shell | Pathname | System Login Script | Local Login Script |
Bourne | /usr/bin/sh |
/etc/profile |
.profile |
Korn | /usr/bin/ksh |
/etc/profile |
.profile ENV |
POSIX | /usr/bin/posix/sh |
/etc/profile |
.profile ENV |
C shell | /usr/bin/csh |
/etc/csh.login |
.login .cshrc |
To determine if you have any local login scripts in your home directory,
use the
ls -a
command.
This command displays all
files that begin with a dot (.) as well as all other entries.
The following customization features are commonly set in the local login scripts:
Terminal characteristics
Search path and other environment variables
Shell variables
Maximum permissions for new files with
umask
(see
Chapter 5)
Allowing or stopping messages to your workstation
The
trap
command (Bourne, Korn, and POSIX shells only)
Command aliases, history variables (C shell and Korn or POSIX shells only)
Displaying system status information and other messages
Checking for mail
Checking for news
It is a good idea to check the contents of your system login script so that you can avoid duplication in your local login script. For example, if your system login script checks for news, there is no need to do the same in your local login script.
See
Chapter 8
for specific examples of login scripts.
7.7 Using Variables
All operating system shells use environment and shell variables to define user environment characteristics. As part of the set-up process, your system administrator has provided default environment and shell variable values in the appropriate login scripts.
For most users, the default environment and shell variable values are sufficient. As you become more familiar with the system, however, you may want to modify some values. For example, you may want to reset the variable that defines your shell prompt so that it is more personalized. You also may want to set a shell variable that specifies a very long directory pathname so that you can save time keying commands that use the directory (see the examples in Section 7.7.1). You also may find setting variables useful when writing shell procedures. You will find that you may use variables creatively to enhance your work environment.
Some environment variables may be reset and some are read-only and cannot
be reset.
That is, these variables can be used, but not modified.
For more
information on this topic, see the appropriate shell reference page;
sh
(1b),
sh
(1p),
csh
(1),
or
ksh
(1).
To reset environment variables as well as define your own shell variables, do one of the following:
Edit the appropriate local login script if you want these values set for you whenever you log in. For more information, see Section 7.6.
Set the environment variables on the command line if you want these values set only for the current login session.
At any time, you may reference the value of any variable as well as
display its value.
You also may clear the value of any variable.
7.7.1 Setting Variables
The following sections describe how to set, reference, display, and
clear variable values.
7.7.1.1 Bourne, Korn, and Posix Shell Variables
In the Bourne, Korn, and POSIX shells, you set variables with an assignment statement. The general format for setting variables is the following:
name
=
value
The name entry specifies the variable name. The value entry specifies the value assigned to the variable. Be sure you do not enter spaces on the command line.
If you want to make the shell variable available to subshells, enter the export command:
export
name
When you export a shell variable, it becomes an environment variable.
With the Bourne shell, two statements are required. The Korn and POSIX shells allow the two statements to be combined into one command, as follows:
export
name
=
value
For example, you can create a variable called
place
by assigning it a value of
U.
S.
A.
with the following
statement:
$
place='U. S. A.'
$
From then on, you can use the variable place just as you would use its value.
For a more useful example, assume that you are using the Bourne shell and
that you temporarily want to personalize your shell prompt.
The default Bourne shell
prompt is a dollar sign ($) set by the
PS1
environment
variable.
To set it to
What Shall I Do Next? >
, enter the
following command:
$
PS1='What Shall I Do Next? >'
What Shall I Do Next? >
If you want to make the shell prompt available to subshells, enter the following command:
$
export PS1
This
What Shall I Do Next? >
prompt will be in effect throughout your
session.
If you want to make the new prompt more permanent, enter the same
assignment statement and the
export
command in your
.profile
file.
As another example, to save keying time you want to define a variable
for a long pathname that you use often.
To define the variable
reports
for the directory
/usr/sales/shoes/women/retail/reports
, enter the following:
$
reports=/usr/sales/shoes/women/retail/reports
To reference the variable after setting it, enter a dollar sign ($) before the variable name. For more information on referencing variables, see Section 7.7.2.
You now can use the variable
reports
in any
commands you enter during this session.
If you want to make this variable
permanent, enter the same assignment statement in your
.profile
file.
7.7.1.2 C Shell Variables
In the C shell, you set environment variables with the
setenv
command.
The general format of the
setenv
command
is the following:
setenv
name value
The name entry specifies the variable name. The value entry specifies the value assigned to the variable.
For an example of setting the PATH environment variable, see Section 7.8.
You set shell variables with the
set
command.
The
format of the
set
command is:
set
name
=
value
The
name
entry specifies the variable
name.
The
value
entry specifies the value assigned
to the variable.
If the
value
entry contains more than
one part (has spaces), enclose the whole expression in single quotes (').
For example, assume that you want to change your prompt.
The default C shell
prompt is a percent sign (%).
To set it to
Ready? >
, enter
the following on the command line:
%
set prompt='Ready? >'
Ready? >
The
Ready? >
prompt will be in effect throughout
your session.
If you execute another shell from the
Ready? >
prompt, you will get the new shell's prompt.
To make the new prompt permanent,
enter the same command in your
.cshrc
file.
7.7.1.3 Setting Variables in All Shells
To set or reset environment or shell variables in any operating system shell, do one of the following:
Edit the appropriate local login script if you want these values set for you whenever you log in. For more information about login scripts, see Section 7.6.
Set them on the command line if you want these values set only for the current login session.
7.7.2 Referencing Variables (Parameter Substitution)
To reference the value of a variable in a command line, enter a dollar sign ($) before the variable name. The dollar sign ($) causes the shell you are using to substitute the value of the variable for the variable name. This is known as parameter substitution.
For example, assume that you have previously defined the variable
sales
for the long pathname
/user/reports/Q1/march/sales
, and that you want to use this variable with the
cd
command.
To do so, enter the
cd
command with the
sales
variable:
$
cd $sales
$
Then, enter the
pwd
command to verify that the
directory is changed:
$
pwd
/user/reports/Q1/march/sales $
In this example, the shell substitutes the actual pathname of the
directory
/user/reports/Q1/march/sales
for the variable
name
sales.
7.7.3 Displaying the Values of Variables
You can display the value of any variable currently set in your shell. Variable values can be displayed either singly or as a group.
To display the value of a single variable, use the
echo
command in the following general format:
echo
$variable
The variable entry identifies the variable you want to display.
For example, assume that you use the Korn shell and want to display the value of the SHELL environment variable. To do so, enter the following command:
$
echo $SHELL
/usr/bin/ksh $
For the Bourne, Korn, and POSIX shells, to display the value of all currently
set variables, use the
set
command without any options.
For example, the following example lists the currently set values in the Bourne shell
(your output will vary):
$
set
EDITOR=emacs HOME=/users/chang LOGNAME=chang MAIL=/usr/mail/chang PATH=:/usr/bin:/usr/bin/X11 PS1=$ SHELL=/usr/bin/sh TERM=xterm $
For the C shell,
to display the value of all currently set shell variables, use the
set
command without any options.
To display the value of all currently
set environment variables, use the
setenv
command or the
printenv
command without any options.
7.7.4 Clearing the Values of Variables
You may remove the value of most any current variable. Please note, however, that the following variables cannot be cleared:
PATH
PS1 (Bourne, Korn, and POSIX shells)
PS2 (Bourne, Korn, and POSIX shells)
MAILCHECK (Bourne, Korn, and POSIX shells)
IFS (Bourne, Korn, and POSIX shells)
For more information on these variables, see the appropriate shell reference
pages;
sh
(1b),
sh
(1p),
csh
(1), or
ksh
(1).
In the Bourne, Korn, and POSIX shells, you can clear
both environment and shell variables with the
unset
command.
The format of the
unset
command is:
unset
name
The name entry specifies the variable name.
In the C shell, you clear environment variables with the
unsetenv
command.
The format of the
unsetenv
command is:
unsetenv
name
The name entry specifies the variable name.
You clear shell variables with the
unset
command.
The format of the
unset
command is:
unset
name
The name entry specifies the variable name.
For an example, assume that you use the Korn shell and have created a
variable called
place
and have assigned it a value
of
U.
S.
A.
.
To clear the variable, enter the following:
$
unset place
$
For more detailed information about setting and referencing variables,
see the appropriate shell reference page.
7.8 How the Shell Finds Commands
Every time you enter a command, your shell searches through a list of directories to find the command. This list of directories is specified by the PATH environment variable.
At many installations, system administrators specify default PATH directories for new users. However, more experienced users may need to change these PATH directories.
The PATH variable contains a list of directories to search, separated by colons (:). The order in which the directories are listed is the search order that the shell uses to search for the commands that you enter.
To determine the value of
PATH, use the
echo
command.
For example, assume that you are using the C shell
and have entered the following:
%
echo $PATH
/usr/bin:/usr/bin/X11 %
This output from the
echo
command (your output
may vary) tells you that the search order of the preceding example is the
following:
The
/usr/bin
directory is searched first.
The
/usr/bin/X11
directory is searched
second.
Typically,
PATH
is set as an environment
variable in the appropriate login script.
In the Bourne, Korn, and POSIX shells, the
PATH
variable usually is set in the
.profile
script.
In the C shell, it usually is set in the
.login
script.
If you want to change the search path, you can assign a new value to
the
PATH
variable.
For example, assume that you
use the Bourne shell and that you have decided to use your own versions of some
operating system commands.
As a result, you want to add
$HOME/usr/bin/
to the search path.
To do so, enter the following on the command
line if you want the new
PATH
variable value to
be in effect for the current login session:
$
export PATH=$HOME/usr/bin:/usr/bin:/usr/bin/X11
$
If you want this new
PATH
variable value
to be in effect for all future sessions, modify the
PATH
variable in your
.profile
script.
When you next log in,
the changes you have made in your
.profile
script will
take effect.
7.9 Using Logout Scripts
You can create a logout script that automatically runs every time you
end your session.
Just like login scripts, the
.logout
file must reside in your home directory.
You can use logout scripts for the following purposes:
To clear your screen
To display a logout message
To run long background processes after you log out
To run a file cleanup routine
To create a logout script, do the following:
Create a file called
.logout
in your home
directory with a text editor.
Place the commands you want in the file. See Section 1.2 for ideas.
Save the text and exit the editor.
Enter the following command to ensure that the
.logout
file has the appropriate executable permissions:
$
chmod u+x .logout
$
Using a
.logout
file is not mandatory; it is a convenience
that may enhance your work environment.
7.9.1 Logout Scripts and the Shell
If you are using the C shell, the
.logout
script
executes automatically when you log out.
If you are using the Korn or POSIX shell and want to use a logout script,
you must ensure that a special trap is set in your
.profile
script.
A
trap
is a command sequence that looks for
a specified signal from a terminal, and then runs a specified command or set
of commands.
If the following line is not set in your
.profile
script, you must add it with a text editor:
trap $HOME/.logout 0
This statement tells your system to run the
.logout
script whenever it receives a zero (0) signal, which occurs automatically
when you log out.
7.9.2 A Sample .logout File
The following example
.logout
file does the following:
Clears the screen
Displays a logout message that provides the name of your system, your user name, and the logout time
Displays a parting message
Runs a file cleanup routine in the background after you log out
Lines beginning with the number sign (#) are comment lines that describe the commands below them.
# Clear the screen clear # Display the name of your system, your user name, # and the time and date that you logged out echo `hostname` : `whoami` logged out on `date` # Run the find command in the background. This command # searches your login directory hierarchy for all # temporary files that have not been accessed in # 7 days, and then deletes them. find ~ -name '*.tmp' -atime +7 -exec rm {} \; & # A parting message echo "Good Day. Come Back Soon"
7.10 Using Shell Procedures (Scripts)
In addition to running commands from the command line, the shell can read and run commands contained in a file. Such a file is called a shell procedure or shell script.
Shell procedures are easy to develop, and using them can help you work more efficiently. For example, you may find shell procedures useful because you can place frequently used commands in one file, and then execute them by entering only the name of the procedure. As a result, they are useful for doing repetitious tasks that would usually require entering many commands on the command line.
Because shell procedures are text files that do not have to be compiled, they are easy to create and to maintain.
Each shell has its own native programming language. The following are some programming language features that apply to all shells:
Storing values in variables
Testing for predefined conditions
Executing commands repeatedly
Passing arguments to a program
For more information on specific programming features of your shell,
see
Chapter 8.
7.10.1 Writing and Running Shell Procedures
To write and run a shell procedure, do the following:
Create a file of the commands you need to accomplish a task.
Create this file as you would any text file: with
vi
or
another editing program.
The file can contain any system command or shell
command (described in the
sh
(1b),
sh
(1p),
csh
(1), or
ksh
(1)
reference pages).
Use the
chmod +x
command to give the file
x
(execute) status.
For example, the command
chmod g+x
reserve
gives execute status to the file named
reserve
for any user in your group (g
).
See
Chapter 5
for information on using the
chmod
command.
Run the procedure by entering its name. Enter the pathname if the procedure file is not in your current directory.
The following example shows a simple shell procedure
named
lss
that sorts
ls -l
command
output by file size:
#! /usr/bin/csh # lss: sort and list ls -l | sort -n +4
Table 7-7
describes
each line in
lss
.
Table 7-7: Description of Example Shell Script
Shell Command | Description |
#! /usr/bin/csh |
Specifies the shell where the shell procedure should run. [Footnote 1] |
#lss: list and sort |
Comment line that describes the purpose of the shell procedure. |
ls -l | sort -n +4 |
These are the commands in the shell procedure.
This procedure lists the files in a directory (ls -l ).
Output from the
ls -l
command is then piped to the
sort
command (
| sort -n +4 ).
This command
skips over the first four columns of the
ls -l
output,
sorts the fifth column (the file size column) numerically, and writes the
lines to the standard output. |
To run the
lss
procedure, enter
lss
.
Sample system output looks similar to the following:
$
lss
-rw-rw-rw- 1 larry system 65 Mar 13 14:46 file3 -rw-rw-rw- 1 larry system 75 Mar 13 14:45 file2 -rw-rw-rw- 1 larry system 101 Mar 13 14:44 file1 $
At times, you may want to specify the shell where a shell procedure should run. This is because of possible syntactic differences between the shells, but is especially true of differences between the C shell and the other shells.
By default, the operating system assumes that any shell procedure you run should be executed in the same shell as your login shell. For example, if your login shell is the Korn shell, by default your shell procedures will run in that same shell.
The ability to override the default is very useful for shell procedures that many users run because it ensures that the procedure executes in the correct shell, regardless of the user's login shell. To change this default run shell, include the following command as the first line of the shell procedure:
#!shell_path
The shell_path entry specifies the full pathname of shell where you want the procedure to run.
For example, if you want a shell procedure to run under the C shell, the first line of the procedure should be the following:
#!/usr/bin/csh