NAME
sh - The Bourne shell, an interactive command interpreter
and command programming language
SYNOPSIS
sh [-ir] [+ | -aefhkntuvx] [file] [argument ...] [-
ccommand_string | -s]
Rsh [-ir] [+ | -aefhkntuvx] [file] [argument ...] [-
ccommand_string | -s]
The shell carries out commands either interactively from a
keyboard or from a file.
FLAGS
The following flags are interpreted by the shell only when
you call it. Note that unless you specify either the -c or
-s flag, the shell assumes that the next argument is a com-
mand file (shell procedure). It passes anything else on the
command line to that command file (see Positional Parame-
ters).
-c command_string
Runs commands read from command_string. The shell does
not read additional commands from standard input when
you specify this flag.
-i Makes the shell interactive, even if input and output
are not from a tty. In this case, the shell ignores the
SIGTERM signal (so that kill 0 does not stop an interac-
tive shell) and traps a SIGINT (so that you can inter-
rupt wait). In all cases, the shell ignores the SIGQUIT
signal. (See the sigaction() system call and kill for
more information about signals.)
-r Creates a restricted shell (the same as running Rsh).
-s Reads commands from standard input. Any remaining argu-
ments specified are passed as positional parameters to
the new shell. Shell output is written to standard
error, except for the output of built-in commands (see
Built-In Commands).
The remaining flags and arguments are discussed in the
description of the built-in set command (see Built-In Com-
mands).
DESCRIPTION
The Bourne shell is a command programming language that
executes commands read from a terminal or a file. Rsh is a
restricted version of the standard command interpreter sh;
Rsh is used to set up login names and execution environments
whose capabilities are more controlled than those of the
standard shell. This allows you to create user environments
that have a limited set of privileges and capabilities.
(See Restricted Shell for more information.)
A file from which the shell carries out commands is usually
called a shell script, a shell procedure, or a command file.
For more information about writing shell scripts, see the
OSF/1 User's Guide.
A simple command is a sequence of words separated by spaces
or tabs. A word is a sequence of characters that contains
no unquoted spaces or tabs. The first word in the sequence
(numbered as 0), usually specifies the name of a command.
Any remaining words, with a few exceptions, are passed to
that command. A space refers to both spaces and tabs.
The value of a simple command is its exit value if it ends
normally, or (octal) 200 added to the signal number if it
terminates due to a signal. For a list of status values,
see the signal() system call.
A pipeline is a sequence of one or more commands separated
by a | (vertical bar) or, for historical compatibility, by a
^ (circumflex). In a pipeline, the standard output of each
command becomes the standard input of the next command.
Each command runs as a separate process, and the shell waits
for the last command to end. A filter is a command that
reads its standard input, transforms it in some way, then
writes it to its standard output. A pipeline normally con-
sists of a series of filters. Although the processes in a
pipeline (except the first process) can execute in parallel,
they are synchronized to the extent that each program needs
to read the output of its predecessor.
The exit value of a pipeline is the exit value of the last
command.
A list is a sequence of one or more pipelines separated by ;
(semicolon), & (ampersand), && (two ampersands), or || (two
vertical bars) and optionally ended by a ; (semicolon), an &
(ampersand), a |& (coprocess), or a newline. These separa-
tors and terminators have the following effects:
; Causes sequential execution of the preceding pipeline;
the shell waits for the pipeline to finish.
& Causes asynchronous execution of the preceding pipeline;
the shell does not wait for the pipeline to finish.
&& Causes the list following it to be executed only if the
preceding pipeline returns a 0 (zero) exit value.
|| Causes the list following it to be executed only if the
preceding pipeline returns a nonzero exit value.
The cd command is an exception; if it returns a nonzero
exit value, no subsequent commands in a list are exe-
cuted, regardless of the separator characters.
The ; and & separators have equal precedence, as do && and
||. The single-character separators have lower precedence
than the double-character separators. An unquoted newline
character following a pipeline functions the same as a ;
(semicolon).
The shell treats as a comment any word that begins with a #
character and ignores that word and all characters following
up to the next newline character.
Shell Flow Control Statements
Unless otherwise stated, the value returned by a statement
is that of the last simple command executed in the state-
ment.
for identifier [in word ...] do list done
For each word, sets identifier to word and executes the
commands in list. If you omit in word ..., then the for
command executes list for each positional parameter that
is set. Execution ends when there are no more words in
the list.
case word in pattern [|pattern] ...)list;;] ... esac
Executes the commands in the list associated with the
first pattern that matches word. Uses the same
character-matching notation in patterns that you use for
filename substitution (see Filename Substitution),
except that you do not need to match explicitly a /
(slash), a leading . (dot), or a . (dot) immediately
following a / (slash).
if list then list [elif list then list] ... [else list] fi
Executes the list following the if keyword. If it
returns a 0 (zero) exit value, executes the list follow-
ing the first then. Otherwise, executes the list fol-
lowing elif (if there is an elif), and if its exit value
is 0 (zero), executes the next then. Failing that, exe-
cutes the list following the else. If no else list or
then list is executed, the if command returns a 0 (zero)
exit value.
while list do list done
Executes the list following the while. If the exit
value of the last command in the list is 0 (zero), exe-
cutes the list following do. Continues looping through
the lists until the exit value of the last command in
the while list is nonzero. If no commands in the do
list are executed, the while command returns a 0 (zero)
exit value.
until list do list done
Executes the list following the until. If the exit
value of the last command in the list is nonzero, exe-
cutes the list following do. Continues looping through
the lists until the exit value of the last command in
the until list is 0 (zero). If no commands in the do
list are executed, the until command returns a 0 (zero)
exit value.
(list)
Executes the commands in list in a subshell.
{ list; }
Executes the commands in list in the current shell pro-
cess; does not spawn a subshell.
name () { list; }
Defines a function that is referenced by name. The body
of the function is the list of commands between the
braces.
The following reserved words are recognized only when they
appear without quotes as the first word of a command.
if esac
then case
else for
elif while
fi until
do done
{ }
Command Execution
Each time the shell executes a command, it carries out the
substitutions discussed in the following text. If the com-
mand name matches one of the built-in commands discussed in
Built-In Commands, it executes it in the shell process. If
the command name does not match a built-in command but
matches the name of a defined function, it executes the
function in the shell process. The shell sets the posi-
tional parameters to the parameters of the function.
If the command name matches neither a built-in command nor
the name of a defined function and the command names an exe-
cutable file that is a compiled (binary) program, the shell
(as parent) spawns a new (child) process that immediately
runs the program. If the file is marked executable but is
not a compiled program, the shell assumes that it is a shell
script. In this case, the shell spawns another instance of
itself (a subshell), to read the file and execute the com-
mands included in it (note how this differs from the execu-
tion of functions). The shell also executes a command
enclosed in parentheses in a subshell. From the perspective
of an end user, a compiled program is run in exactly the
same way as a shell script.
The shell normally searches for commands in two places in
the file system. The shell first looks for the command in
the current directory; if it does not find the command
there, it looks in the /usr/bin directory. This search
order is in effect if the PATH environment variable is not
set (or is set to :/usr/bin, as is the case by default on
many systems).
You can also give a specific pathname when you invoke a com-
mand, for example /usr/bin/sort, in which case the shell
does not search any directories other than the one you
specify in the pathname. If the command name contains a /
(slash), the shell does not use the search path (note that
the restricted shell will not execute such commands). You
can give a full pathname that begins with the root directory
(as in /usr/bin/sort), or a pathname relative to the current
directory, for example bin/myfile. In this last case, the
shell looks in the current directory for a directory named
bin and in that directory for myfile.
You can change the particular sequence of directories
searched by resetting the PATH variable (see Variables Used
by the Shell).
The shell remembers the location in the search path of each
executed command (to avoid unnecessary exec commands later).
If the command was found in a relative directory (one whose
name does not begin with /), the shell must redetermine its
location whenever the current directory changes. The shell
forgets all remembered locations whenever you change the
PATH variable or execute the hash -r command (see Built-In
Commands).
Signals
The shell ignores SIGINT and SIGQUIT signals for an invoked
command if the command is terminated with a & (that is, if
it is running in the background). Otherwise, signals have
the values inherited by the shell from its parent, with the
exception of signal 11 (see also the built-in trap command
in Built-In Commands).
Initialization Files
When you log in, the shell is called to read your commands.
Before it does that, however, it checks to see if a file
named /etc/profile exists on the system, and if it does, it
reads commands from it (this file sets variables needed by
all users). After this, the shell looks for a file named
.profile in your login directory. If it finds one, it exe-
cutes commands from it. Finally, the shell is ready to read
commands from your standard input.
Filename Substitution
Command arguments are very often filenames. You can
automatically produce a list of filenames as arguments on a
command line by specifying a pattern that the shell matches
against the filenames in a directory.
Most characters in such a pattern match themselves, but you
can also use some special pattern-matching characters in
your pattern. These special characters are as follows:
. Matches any single character, except a newline charac-
ter.
* Matches any string, including the null string.
? Matches any one character.
[ ...]
Matches any one of the characters enclosed in brackets.
[! ...]
Matches any character other than those that follow the
exclamation point within brackets.
Inside brackets, a pair of characters separated by a -
(dash) specifies a set of all characters lexically within
the inclusive range of that pair according to the current
collating sequence. The LANG and LC_COLLATE environment
variables control the collating sequence. See "Using Inter-
nationalization Features" in the OSF/1 User's Guide for more
information on collating sequences.
The current collating sequence groups characters into
equivalence classes for the purpose of defining the end-
points of a range of characters. For example, if the col-
lating sequence defines the lexical order to be AaBbCc ...
and groups uppercase and lowercase characters into
equivalence classes, then all the following have the same
effect: [a-c], [A-C], [a-C], and [A-c].
Pattern matching has some restrictions. If the first char-
acter of a filename is a . (dot), it can be matched only by
a pattern that begins with a dot. For example, * (asterisk)
matches the filenames myfile and yourfile, but not the
filenames .myfile and .yourfile. To match these files, use
a pattern such as the following:
.*file
If a pattern does not match any filenames, then the pattern
itself is returned as the result of the attempted match.
File and directory names should not contain the characters
*, ?, [, or ], because this requires quoting those names in
order to refer to the files and directories.
Shell Variables and Command-Line Substitutions
The shell has several mechanisms for creating variables
(assigning a string value to a name). Certain variables,
positional parameters and keyword parameters, are normally
set only on a command line. Other variables are simply
names to which you or the shell can assign string values.
Positional Parameters
When you run a shell script, the shell implicitly creates
positional parameters that reference each word on the com-
mand line by its position on the command line. The word in
position 0 (the procedure name), is called $0, the next word
(the first parameter) is called $1, and so on up to $9. To
refer to command-line parameters numbered higher than 9, use
the built-in shift command (see Built-In Commands).
You can also assign values to these positional parameters
explicitly by using the built-in set command (see Built-In
Commands).
When an argument for a position is not specified, its posi-
tional parameter is set to null.
Positional parameters are global and can be passed to nested
shell scripts.
User-Defined Variables
The shell also recognizes alphanumeric variables to which
string values can be assigned. You assign a string value to
a name, as follows:
name=string
A name is a sequence of letters, digits, and underscores
that begins with an underscore or a letter. To use the
value that you have assigned to a variable, add a $ (dollar
sign) to the beginning of its name. Thus, $name yields the
value string. Note that no spaces surround the = (equal
sign) in an assignment statement. (Positional parameters
cannot appear in an assignment statement; they can only be
set as described earlier.) You can put more than one
assignment on a command line, but remember: the shell per-
forms the assignments from right to left.
If you surround string with quotes, either " " (double) or '
' (single), the shell does not treat spaces, tabs, semi-
colons, and newline characters within it as word delimiters
but embeds them literally in the string.
If you surround string with double quotes, the shell still
recognizes variable names in the string and performs vari-
able substitution; that is, it replaces references to posi-
tional parameters and other variable names that are prefaced
by $ with their corresponding values, if any. The shell
also performs command substitution (see Command Substitu-
tion) within strings that are surrounded by double quotes.
If you surround string with single quotes, the shell does no
variable or command substitution within the string. The
following sequence illustrates this difference:
You enter:
stars=*****
asterisks1="Add $stars"
asterisks2='Add $stars'
echo $asterisks1
The system displays:
Add *****
You enter:
echo $asterisks2
The system displays:
Add $stars
The shell does not reinterpret spaces in assignments after
variable substitution (see Interpretation of Spaces). Thus,
the following assignments result in $first and $second hav-
ing the same value:
first='a string with embedded spaces'
second=$first
When you reference a variable, you can enclose the variable
name (or the digit designating a positional parameter) in {
} (braces) to delimit the variable name from any following
string. In particular, if the character immediately follow-
ing the name is a letter, digit, or underscore and the vari-
able is not a positional parameter, then the braces are
required:
You enter:
a='This is a'
echo "${a}n example"
The system displays:
This is an example
You enter:
echo "$a test"
The system displays:
This is a test
See Conditional Substitution for a different use of braces
in variable substitutions.
A Command's Environment
All the variables (with their associated values) that are
known to a command at the beginning of its execution consti-
tute its environment. This environment includes variables
that a command inherits from its parent process and
variables specified as keyword parameters on the command
line that calls the command.
The shell passes to its child processes the variables that
were named as arguments to the built-in export command.
export places the named variables in the environments of
both the shell and all its future child processes.
Keyword parameters are variable-value pairs that appear in
the form of assignments, normally before the procedure name
on a command line (but see also the -k flag, discussed under
the set command in Built-In Commands). Such variables are
placed in the environment of the procedure being called.
For example, given the following simple procedure that
echoes the values of two variables (saved in a command file
named key_command):
# cat key_command
echo $a $b
#
the following command lines produce the output shown:
You enter:
a=key1 b=key2 key_command
The system displays:
key1 key2
You enter:
a=tom b=john key_command
The system displays:
tom john
A procedure's keyword parameters are not included in the
parameter count stored in $#.
A procedure can access the values of any variables in its
environment; however, if it changes any of these values,
these changes are not reflected in the shell environment.
They are local to the procedure in question. To place these
changes in the environment that the procedure passes to its
child processes, you must export these values within that
procedure.
To obtain a list of variables that were made exportable from
the current shell, enter:
export
(You will also get a list of variables that were made read
only.) To get a list of name-value pairs in the current
environment, enter:
env
Conditional Substitution
Normally, the shell replaces $variable with the string value
assigned to variable, if there is one. However, there is a
special notation that allows conditional substitution,
depending on whether the variable is set and is not null.
By definition, a variable is set if it was assigned a value.
The value of a variable can be the null string, which you
can assign to a variable in any one of the following ways:
A=
bcd=""
Efg=''
set '' ""
The first three of these examples assign the null string to
each of the corresponding variable names. The last example
sets the first and second positional parameters to the null
string and unsets all other positional parameters.
The following is a list of the available expressions you can
use to perform conditional substitution:
${ variable-string }
If the variable is set, substitute the value of variable
in place of this expression. Otherwise, replace this
expression with the value of string.
${ variable:-string }
If the variable is set and is not null, substitute the
value of variable in place of this expression. Other-
wise, replace this expression with the value of string.
${ variable=string }
If the variable is set, substitute the value of variable
in place of this expression. Otherwise, set variable to
string and then substitute the value of the variable in
place of this expression. You cannot assign values to
positional parameters in this fashion.
${ variable:=string }
If the variable is set and is not null, substitute the
value of variable in place of this expression. Other-
wise, set variable to string and then substitute the
value of the variable in place of this expression. You
cannot assign values to positional parameters in this
fashion.
${ variable?string }
If the variable is set, substitute the value of variable
in place of this expression. Otherwise, display a mes-
sage of the form:
variable: string
and exit from the current shell, unless the shell is the
login shell. If you do not specify string, the shell
displays the following message:
variable: parameter null or not set
${ variable:?string }
If the variable is set and not null, substitute the
value of variable in place of this expression. Other-
wise, display a message of the form:
variable: string
and exit from the current shell, unless the shell is the
login shell. If you do not specify string, the shell
displays the following message:
variable: parameter null or not set
${ variable+string }
If the variable is set, substitute the value of string
in place of this expression. Otherwise, substitute the
null string.
${ variable:+string }
If the variable is set and not null, substitute the
value of string in place of this expression. Otherwise,
substitute the null string.
In conditional substitution, the shell does not evaluate
string until it uses it as a substituted string, so that, in
the following example, the shell executes the pwd command
only if d is not set or is null:
echo ${ d:-`pwd` }
Variables Used by the Shell
The shell uses the following variables. The shell sets some
of them, and you can set or reset all of them.
CDPATH
The search path for the cd (change directory) command.
HOME
The name of your login directory, the directory that
becomes the current directory upon completion of a
login. The login program initializes this variable.
The cd command uses the value of $HOME as its default
value. If you use this variable in your shell scripts
rather than using the full pathname, your procedures run
even if your login directory is changed or if another
user runs them.
LANG
Specifies the locale of your system, which is comprised
of three parts: language, territory, and codeset. The
default locale is the C locale, which specifies the
value English for language, U.S. for territory, and
ASCII for codeset.
LC_COLLATE
Specifies the collating sequence to use when sorting
names and when character ranges occur in patterns. The
default value is the collating sequence for American
English. If absent, the collating sequence may be taken
from the LANG variable. If both LC_COLLATE and LANG are
absent, the ANSI C collating sequence is used.
LC_CTYPE
Specifies the character classification information to
use on your system. The default value is American
English.
LC_MESSAGES
Specifies the language in which system messages appear,
and the language that the system expects for user input
of yes and no strings. The default is American English.
LC_MONETARY
Specifies the monetary format for your system. The
default value is the monetary format for American
English.
LC_NUMERIC
Specifies the numeric format for your system. The
default value is the numeric format for American
English.
LC_TIME
Specifies the date and time format for your system. The
default value is the date and time format for American
English.
LOGNAME
Your login name, marked readonly in the /etc/profile
file.
MAIL
The pathname of the file used by the mail system to
detect the arrival of new mail. If MAIL is set, the
shell periodically checks the modification time of this
file and displays the value of $MAILMSG, if this time
changes and the length of the file is greater than 0
(zero).
Set MAIL in your .profile file. The value normally
assigned to it by users of the mail or mailx commands is
/var/spool/mail/$LOGNAME.
MAILCHECK
The number of seconds that the shell lets elapse before
checking again for the arrival of mail in the files
specified by the MAILPATH or MAIL variables. The
default value is 600 seconds (10 minutes). If you set
MAILCHECK to 0 (zero), the shell checks before each
prompt.
MAILPATH
A list of filenames separated from one another by a :
(colon). If you set this variable, the shell informs
you of the arrival of mail in any of the files specified
in the list. You can follow each filename by a % (per-
cent sign) and a message to be displayed when mail
arrives. Otherwise, the shell uses the value of MAILMSG
or, by default, the message you have mail.
When MAILPATH is set, these files are checked instead of
the file set by MAIL. To check the files set by MAIL-
PATH and the file set by MAIL, specify the MAIL file in
your list of MAILPATH files.
MAILMSG
The mail notification message. If you explicitly set
MAILMSG to a null string (MAILMSG=""), no message is
displayed.
NLSPATH
Specifies a list of directories to search to find mes-
sage catalogs.
PATH
An ordered list of directory pathnames separated by
colons. The shell searches these directories in the
specified order when it looks for commands. A null
string anywhere in the list represents the current
directory.
PATH is normally initialized in the /etc/profile file,
usually to :/usr/bin (by definition, a null string is
assumed in front of the leading colon). You can reset
this variable to suit your own needs. Thus, if you wish
to search your current directory last rather than first,
you would enter:
PATH=/usr/bin:
If you have a personal directory of commands (say,
$HOME/bin) that you want searched before the standard
system directories, set your PATH as follows:
PATH=$HOME/bin:/usr/bin:
The best place to set your PATH to something other than
the default value is in your .profile file (see The
.profile File). You cannot reset PATH if you are exe-
cuting commands under the restricted shell (Rsh).
PS1 The string to be used as the primary system prompt. An
interactive shell displays this prompt string when it
expects input. The default value of PS1 is $ followed
by a space.
PS2 The value of the secondary prompt string. If the shell
expects more input when it encounters a newline charac-
ter in its input, it prompts with the value of PS2. The
default value of PS2 is > followed by a space.
IFS The characters that are internal field separators (the
characters that the shell uses during interpretation of
spaces, see Interpretation of Spaces). The shell ini-
tially sets IFS to include the space, tab, and newline
characters.
SHACCT
The name of a file that you own. If this variable is
set, the shell writes an accounting record in the file
for each shell script executed. You can use accounting
programs such as acctcom and acctcms to analyze the data
collected.
SHELL
A pathname whose simple part (the part after the last /)
contains an r if you want the shell to become restricted
when invoked. This should be set and exported by the
$HOME/.profile file of each restricted login.
TIMEOUT
A number of minutes. After the shell displays its
prompt, you have TIMEOUT minutes to enter a command. If
you fail to do so, the shell exits; in the login shell,
such an exit is a logout. Setting TIMEOUT to 0 (zero)
inhibits automatic logout.
Predefined Special Variables
Several variables have special meanings; the following are
set only by the shell:
$# The number of positional parameters passed to the shell,
not counting the name of the shell script itself. The
$# variable thus yields the number of the highest-
numbered positional parameter that is set. One of the
primary uses of this variable is to check for the pres-
ence of the required number of arguments.
$? The exit value of the last command executed. Its value
is a decimal string. Most commands return 0 (zero) to
indicate successful completion. The shell itself
returns the current value of $? as its exit value.
$$ The process number of the current process. Because pro-
cess numbers are unique among all existing processes,
this string of up to five digits is often used to gen-
erate unique names for temporary files. The following
example illustrates the recommended practice of creating
temporary files in a directory used only for that pur-
pose:
temp=$HOME/temp/$$
ls >$temp
.
.
.
rm $temp
$! The process number of the last process run in the back-
ground (using the & terminator). Again, this is a
string of up to five digits.
$- A string consisting of the names of the execution flags
(see Built-In Commands) currently set in the shell.
Command Substitution
To capture the output of any command as an argument to
another command, place that command line within ` ` (grave
accents). This concept is known as command substitution.
The shell first executes the command or commands enclosed
within the grave accents, and then replaces the whole
expression, grave accents and all, with their output. This
feature is often used in assignment statements:
today=`date`
This statement assigns the string representing the current
date to the today variable. The following assignment saves,
in the files variable, the number of files in the current
directory:
files=`ls | wc -l`
You perform command substitution on any command that writes
to standard output by enclosing that command in grave
accents. You can nest command substitutions by preceding
each of the inside sets of grave accents with a \
(backslash):
logmsg=`echo Your login directory is \`pwd\``
You can also give values to shell variables indirectly by
using the built-in read command. The read command takes a
line from standard input (usually your keyboard), and
assigns consecutive words on that line to any variables
named:
read first middle last
Thus, read will accept the following input line
Jane C. Chen
and it will have the same effect as if you had entered
first=Jane init=C. last=Chen
The read command assigns any excess words to the last vari-
able.
Quoting Mechanisms
The following characters have a special meaning to the shell
and cause termination of a word unless quoted:
; & ( ) | ^ < > <newline> <space> <tab>
Using ' ' (single) and " " (double) quotes to surround a
string or a \ (backslash) before a single character enables
the character to stand for itself, instead of conveying spe-
cial meaning to the shell.
Within single quotes, all characters (except the single
quote character itself), are taken literally, with any spe-
cial meaning removed. Thus, entering:
stuff='echo $? $*; ls * | wc'
results only in the literal string echo $? $*; ls * | wc
being assigned to the stuff variable; the echo, ls, and wc
commands are not executed, nor are the variables $? and $*
and the special character * expanded by the shell.
To verify this you could export the variable stuff with the
command export stuff, and then use the command printenv
stuff to view it. Note that this is different from the sim-
ple command echo $stuff.
Within double quotes, the special meaning of certain charac-
ters ($, `, and ") does persist, while all other characters
are taken literally. Thus, within double quotes, command
and variable substitution takes place. In addition, the
quotes do not affect the commands within a command substitu-
tion that is part of the quoted string, so characters there
retain their special meanings.
Consider the following sequence:
You enter:
ls *
System displays:
file1
file2
file3
You enter:
message="This directory contains `ls * ` "
echo $message
System displays:
This directory contains file1 file2 file3
This shows that the * special character inside the command
substitution was expanded.
To hide the special meaning of $, `, and " within double
quotes, precede these characters with a \ (backslash). Out-
side of double quotes, preceding a character with \
(backslash) is equivalent to placing it within single
quotes. Hence, a \ (backslash) immediately preceding the
newline character (that is, a \ (backslash) at the end of
the line) hides the newline character and allows you to con-
tinue the command line on the next physical line.
Redirection of Input and Output
In general, most commands do not know or care whether their
input or output is associated with the keyboard, the display
screen, or a file. Thus, a command can be used conveniently
either at the keyboard or in a pipeline.
Standard Input and Standard Output
When a command begins running, it usually expects that three
files are already open: standard input, standard output, and
standard error (sometimes called error output or standard
error output). A number called a file descriptor is associ-
ated with each of these files as follows:
File descriptor 0
Standard input
File descriptor 1
Standard output
File descriptor 2
Standard error
A child process normally inherits these files from its
parent; all three files are initially assigned to the tty.
Conventionally, commands read from standard input (0), write
to standard output (1), and write error messages to standard
error (2). The shell permits them to be redirected else-
where before control is passed to a command. Any argument
to the shell in the form <file or >file opens the specified
file as the standard input or output, respectively.
In the case of output, this process destroys the previous
contents of file, if it already exists and write permission
is available. An argument in the form >>file directs the
standard output to the end of file, thus allowing you to add
data to it without destroying its existing contents. If
file does not exist, the shell creates it.
Such redirection arguments are subject only to variable and
command substitution; neither interpretation of spaces nor
pattern matching of filenames occurs after these substitu-
tions. Thus, entering:
echo 'this is a test' > *.ggg
produces a 1-line file named *.ggg, and entering:
cat < ?
produces an error message, unless you have a file named ? (a
bad choice for a filename).
Diagnostic and Other Output
Diagnostic output from commands is normally directed to the
file associated with file descriptor 2. You can redirect
this error output to a file by immediately preceding either
output redirection symbol (> or >>) with a 2 (the number of
the file descriptor). Note that there must be no spaces
between the file descriptor and the redirection symbol; oth-
erwise, the shell interprets the number as a separate argu-
ment to the command.
You can also use this method to redirect the output associ-
ated with any of the first 10 file descriptors (numbered 0
to 9) so that, for instance, if a command writes to file
descriptor 9 (although this is not a recommended programming
habit), you can capture that output in a file named savedata
as follows:
command 9> savedata
If a command writes to more than one output, you can
independently redirect each one. Suppose that a command
directs its standard output to file descriptor 1, directs
its error output to file descriptor 2, and builds a data
file on file descriptor 9. The following command line
redirects each of these outputs to a different file:
command > standard 2> error 9> data
Inline Input (Here) Documents
When the shell sees a command line of the following form,
where eof_string is any string that contains no pattern-
matching characters, the shell takes the subsequent lines as
the standard input of command until it reads a line consist-
ing of only eof_string (possibly preceded by one or more tab
characters):
command << eof_string
The lines between the first eof_string and the second are
frequently referred to as a here document. If a - (dash)
immediately follows the <<, the shell strips leading tab
characters from each line of the input document before it
passes the line to the command.
The shell creates a temporary file containing the input
document and performs variable and command substitution on
its contents before passing it to the command. It performs
pattern matching on filenames that are a part of command
lines in command substitutions. If you want to prohibit all
substitutions, quote any character of eof_string:
command << \eof_string
The here document is especially useful for a small amount of
input data that is more conveniently placed in the shell
script rather than kept in a separate file (such as editor
scripts). For instance, you could enter:
cat <<- xyz
This message will be shown on the
display with leading tabs removed.
xyz
This feature is most useful in shell scripts. Note that
inline input documents cannot appear within grave accents
(command substitution).
I/O Redirection with File Descriptors
As discussed previously, a command occasionally directs out-
put to some file associated with a file descriptor other
than 1 or 2. The shell also provides a mechanism for creat-
ing an output file associated with a particular file
descriptor. For example, if you enter the following, where
digit1 and digit2 are valid file descriptors, you can direct
the output that would normally be associated with file
descriptor digit1 to the file associated with digit2:
digit1>&digit2
The default value for digit1 and digit2 is 1 (standard out-
put). If, at execution time, no file is associated with
digit2, then the redirection is void. The most common use
of this mechanism is to direct standard error output to the
same file as standard output, as follows:
command 2>&1
If you want to redirect both standard output and standard
error output to the same file, enter:
command > file 2>&1
The order here is significant. First, the shell associates
file descriptor 1 with file; then it associates file
descriptor 2 with the file that is currently associated with
file descriptor 1. If you reverse the order of the redirec-
tions, standard error output goes to the display and stan-
dard output goes to file because at the time of the error
output redirection, file descriptor 1 was still associated
with the display.
You can also use this mechanism to redirect standard input.
You could enter:
digit1<&digit2
where digit1 refers to standard input and digit2 refers to
standard output, to cause both file descriptors to be asso-
ciated with the same input file. For commands that run
sequentially, the default value of digit1 and digit2 is 0
(standard input). For commands that run asynchronously
(commands terminated by &), the default value of digit1 and
digit2 is /dev/null. Such input redirection is useful for
commands that use two or more input sources.
Summary of Redirection Options
The following can appear anywhere in a simple command or can
precede or follow a command, but they are not passed to the
command:
<file
Use file as standard input.
>file
Use file as standard output. Create the file if it does
not exist; otherwise, truncate it to 0 (zero) length.
>>file
Use file as standard output. Create the file if it does
not exist; otherwise, append the output to the end of
the file.
<<[-]eof_string
Read as standard input all lines from eof_string up to a
line containing only eof_string or up to an End-of-File
character. If any character in eof_string is quoted,
the shell does not expand or interpret any characters in
the input lines; otherwise, it performs variable and
command substitution and ignores a quoted newline char-
acter (\newline). Use a \ (backslash) to quote charac-
ters within eof_string or within the input lines.
If you add a - (dash) to <<, then all leading tabs are
stripped from eof_string and from the input lines.
< &digit
Associate standard input with file descriptor digit.
> &digit
Associate standard output with file descriptor digit.
< &-
Close standard input.
> &-
Close standard output.
The restricted shell does not allow the redirection of out-
put.
Interpretation of Spaces
After the shell performs variable and command substitution,
it scans the results for internal field separators (those
defined in the IFS shell variable, see Variables Used by the
Shell). It splits the line into distinct words at each
place it finds one of these characters. It retains explicit
null arguments ("" '') and discards implicit null arguments
(those resulting from parameters that have no values).
Built-In Commands
: Does nothing. This null command returns a 0 (zero) exit
value.
. file
Reads and executes commands from file and returns. Does
not spawn a subshell. The search path specified by PATH
is used to find the directory containing file.
break [n]
Exits from the enclosing for, while, or until loop, if
any. If n is specified, then breaks n levels.
continue [n]
Resumes the next iteration of the enclosing for, while,
or until loop. If n is specified, resumes at the nth
enclosing loop.
cd [directory]
Changes the current directory to directory. If no
directory is specified, the value of the HOME shell
variable is used. The CDPATH shell variable defines the
search path for directory. Alternative directory names
appear in a list, separated from one another by a :
(colon). A null pathname specifies the current direc-
tory, which is the default path. This null pathname can
appear immediately after the = (equal sign) in the
assignment or between the colon delimiters anywhere else
in the path list. If directory begins with a / (slash),
the shell does not use the search path. Otherwise, the
shell searches each directory in the path. The cd com-
mand cannot be executed by the restricted shell.
echo [argument ...]
Writes arguments to standard output.
eval [argument ...]
Reads arguments as input to the shell and executes the
resulting commands. eval is most often used in command
substitution. For example, the following command sets
up the shell's TERM and TERMCAP variables according to
the type of terminal the user is logged in on:
eval `tset -s vt100`
exec [argument ...]
Executes the command specified by argument in place of
this shell without creating a new process. Input and
output arguments can appear and, if no other arguments
appear, cause the shell input or output to be modified
(not a good idea with your login shell). If this com-
mand is given from your login shell, you will be logged
out after the specified command has been executed.
exit [n]
Causes a shell to exit with the exit value specified by
n. If you omit n, the exit value is that of the last
command executed. (Pressing the End-of-File key
sequence also causes a shell to exit.) The value of n
can be from 0 to 255, inclusive.
export [name ...]
Marks the specified names for automatic export to the
environments of subsequently executed commands. If you
do not specify a name, the export command displays a
list of all the names that are exported in this shell.
You cannot export function names.
hash [-r] [name ...]
For each name, finds and remembers the location in the
search path of the command specified by name. The -r
flag causes the shell to forget all locations. If you
do not specify the flag or any names, the shell displays
information about the remembered commands. In this
information, hits is the number of times a command has
been run by the shell process. cost is a measure of the
work required to locate a command in the search path.
There are certain situations that require that the
stored location of a command be recalculated (for exam-
ple, the location of a relative pathname when the
current directory changes). Commands for which that
might be done are indicated by an * (asterisk) next to
the hits information. cost is incremented when the
recalculation is done.
inlib library_name
Installs the specified shared library into the shell's
private table of installed libraries. This makes the
library available for resolution of unresolved symbols
in commands subsequently executed from this shell.
newgrp [-] [group]
Changes the primary group identification of the current
shell process to group. If you specify -, newgrp
changes the login environment to the login environment
of the new group. If you do not specify a group, newgrp
changes the group identification to that specified for
the current user in the /etc/passwd file. newgrp recog-
nizes group names only; it does not recognize group ID
numbers.
Only a user with superuser authority can change the pri-
mary group of the shell to one to which that user does
not belong.
Any active user-generated shell is terminated when the
newgrp command is used.
pwd Displays the current directory. See pwd for a discus-
sion of command options.
read [name...]
Reads one line from standard input. Assigns the first
word in the line to the first name, the second word to
the second name, and so on, with leftover words assigned
to the last name. This command returns a 0 (zero)
unless it encounters an end of file.
readonly [name...]
Marks the specified names as read only. The values of
these names cannot be reset. If you do not specify any
names, the readonly command displays a list of all
readonly names.
return [n]
Causes a function to exit with a return value of n. If
you do not specify n, the function returns the status of
the last command executed in that function. This com-
mand is valid only when executed within a shell func-
tion.
rmlib library_name
Removes the specified shared library from the shell's
private table of installed libraries. This library is
no longer available for resolution of unresolved symbols
in commands executed from this shell.
set [+ | -flag ...] [argument ...]
Sets one or more of the following flags:
-a Marks for export all variables that are modified or
changed.
-e Exits immediately if a command exits with a nonzero
exit value.
-f Disables filename substitution.
-h Locates and remembers the commands called within
functions as the functions are defined. (Normally
these commands are located when the function is exe-
cuted; see the built-in hash command.)
-k Places all keyword parameters in the environment for
a command, not just those that precede the command
name.
-n Reads commands, but does not execute them.
-t Exits after reading and executing one command.
-u Treats an unset variable as an error when performing
variable substitution.
-v Displays shell input lines as they are read.
-x Displays commands and their arguments as they are
executed.
-- Does not change any of the flags. This is useful in
setting the $1 positional parameter to a string
beginning with a - (dash).
Using a + (plus sign) rather than a - (dash) unsets
flags. You can also specify these flags on the shell
command line. The $- special variable contains the
current set of flags.
Any arguments to set are positional parameters and are
assigned, in order, to $1, $2, and so on. If you do not
specify flags or arguments, set displays all names.
shift [n]
Shifts command-line arguments to the left; that is,
reassigns the value of the positional parameters by dis-
carding the current of value of $1 and assigning the
value of $2 to $1, of $3 to $2, and so on. If there are
more than nine command line arguments, the tenth is
assigned to $9 and any that remain are still unassigned
(until after another shift). If there are nine or fewer
arguments, a shift unsets the highest-numbered posi-
tional parameter.
$0 is never shifted. The command shift n is a shorthand
notation for n consecutive shifts. The default value of
n is 1.
test expression | [ expression ]
Evaluates conditional expressions. See test for a dis-
cussion of command options.
times
Displays the accumulated user and system times for
processes run from the shell.
trap [command] [n] ...
Runs the command specified by command when the shell
receives n signal(s). (Note that the shell scans com-
mand once when the trap is set and once when the trap is
taken). The trap commands are executed in order of sig-
nal number. Any attempt to set a trap on a signal that
was ignored on entry to the current shell is ineffec-
tive.
If you do not specify a command, then all traps n are
reset to their current values. If command is a null
string, this signal is ignored by the shell and by the
commands it invokes. If n is 0 (zero), the command is
executed on exit from the shell. If neither a command
or a signal (n) is specified, trap displays a list of
commands associated with each signal number.
type [name ...]
For each name specified, indicates how the shell inter-
prets it as a command name.
ulimit [-b [m]] [-f] [n] [-s [m]]
Sets or queries size limits. The -b flag sets the break
value to m. This limits the size of data segment to m
pages. If you specify -b with no m, ulimit displays the
current break value. The -f flag imposes a size limit
of n blocks on files written by the child processes
(files of any size can be read). Without n, ulimit
displays the current limit; this is the default action
of ulimit.
Any user can decrease this limit, but only a user
operating with superuser authority can increase the
limit. The -s flag imposes a size limit of m pages on
the stack. If you specify -s with no m, ulimit displays
the current stack size limit.
umask [nnn]
Sets your file-creation mask to the octal value nnn (see
the umask() system call). If you omit nnn, umask
displays the current value of the mask.
unset [name ...]
For each name, removes the corresponding variable,
built-in command, or function. The PATH, PS1, PS2,
MAILCHECK, and IFS variables cannot be unset.
wait [n]
Waits for the child process whose process number is n to
end and reports its termination status. If you do not
specify n, then the shell waits for all currently active
child processes and the return value is 0 (zero).
Character Classes
You can use the following notation to match filenames within
a range indication:
[:charclass:]
This format instructs the system to match any single charac-
ter belonging to charclass; the defined classes correspond
to ctype() subroutines as follows:
alnum
alpha
cntrl
digit
graph
lower
print
punct
space
upper
xdigit
Your locale might define additional character properties,
such as the following:
[:vowel:]
The preceding character class could be TRUE for a, e, i, o,
u, or y. You could then use [:vowel] inside a set construc-
tion to match any vowel. Refer to The LC_CTYPE Category
section of the locale file format reference page for more
information.
Running the Shell
The sh command can be run either as a login shell or as a
subshell under the login shell. Only the login command can
call sh as a login shell. It does this by using a special
form of the sh command name: -sh. When called with an ini-
tial - (dash), the shell first reads and runs commands found
in the system .profile file and your $HOME/.profile, if one
exists. It then accepts commands as described in the fol-
lowing discussion of flags.
Once logged in and working under a login shell, you can call
sh with the command name sh. This command runs a subshell,
a second shell running as a child of the login shell.
Restricted Shell
The restricted shell, Rsh, is used to set up login names and
execution environments whose capabilities are more con-
trolled than those of the standard shell. The actions of
Rsh are identical to those of sh, except that the following
are not allowed:
o Changing directory (with the cd command).
o Setting the value of PATH or SHELL.
o Specifying pathnames or command names containing /.
o Redirecting output (with > and >>).
A restricted shell can be invoked in one of the following
ways: (1) Rsh is the filename part of the last entry in the
/etc/passwd file; (2) the environment variable SHELL exists
and Rsh is the filename part of its value; (3) the shell is
invoked and Rsh is the filename part of argument 0 (zero);
(4) the shell is invoked with the -r flag.
When a command to be run is determined to be a shell script,
Rsh invokes sh to run the command. Thus, it is possible to
provide the end user with shell scripts that have access to
the full power of the standard shell, while imposing a lim-
ited menu of commands; this scheme assumes that the end user
does not have write and execute permissions in the same
directory.
The preceding restrictions are enforced after the .profile
file is interpreted. Therefore, the writer of the .profile
has complete control over user actions by performing set-up
actions and leaving the user in an appropriate directory
(probably not the login directory). An administrator can
set up a directory of commands in /usr/rbin that the Rsh
command can invoke.
When called with the name -rsh or -Rsh, Rsh reads the user's
.profile from $HOME/.profile. It acts as the standard sh
while doing this, except that an Interrupt causes an immedi-
ate exit instead of a return to command level.
The system administrator should be aware that use of Rsh
does not imply that the system is secure. A secure system
implements a system-wide framework to protect the system
against unauthorized activity. Rsh is not designed to
implement this type of system security.
FILES
$HOME/.profile
User profile.
/etc/passwd
Contains user information.
EXIT VALUES
For information about exit values, see the following sec-
tions: The Shell Commands, Predefined Special Variables,
Built-In Commands, and FLAGS.
NOTES
1. If a command is executed, and a command with the same
name is installed in a directory in the search path
before the directory where the original command was
found, the shell will execute the original command.
Use the hash command to correct this situation.
2. When the shell encounters the >> characters, it does
not open the file in append mode; instead, the shell
opens the file for writing and seeks to the end.
3. Failure (nonzero exit status) of a special command
preceding a || symbol prevents the list following ||
from executing.
RELATED INFORMATION
Commands: acctcms(8), acctcom(8), cd(1), csh(1), echo(1),
env(1)/printenv(1), ksh(1), login(1), mail(1)/binmail(1),
mailx(1)/Mail(1), pwd(1), test(1).
Functions: fcntl(2), exec(2), fork(2), ldr_install(2),
ldr_remove(2), pipe(2), sigaction(2), stat(2), ulimit(3),
umask(2).
Files: osf_rose(4), null(7).
"Using Internationalization Features" in the OSF/1 User's
Guide.
Acknowledgement and Disclaimer