sh
PURPOSE
Interprets commands read from a file or entered at the
keyboard.
SYNOPSIS
sh [ [ -i ] [ -r ] ] [ setflags ] [ file [ parameters ] ]
[ [ -s ] [ -c cmdstring ] ]
rsh [ [ -i ] [ -r ] ] [ setflags ] [ file [ parameters ] ]
[ [ -s ] [ -c cmdstring ] ]
DESCRIPTION
The sh command is a system command interpreter and pro-
gramming language. It is not a part of the operating
system kernel, but an ordinary user program that reads
commands entered at the keyboard and arranges for their
execution. In addition, it can read commands that you
have saved in a file. Such a file is usually called a
shell procedure or a command file. For a complete
description of how to write shell procedures to take
advantage of this useful tool, see Using the AIX Oper-
ating System.
A restricted version of shell (the rsh command) is avail-
able that allows you to create user environments with a
limited set of privileges and capabilities. See
"Restricted Shell" for additional information on the
restricted shell.
Commands
A command is either a simple command or a control command
(see "Control Commands").
A simple command is a sequence of words separated by
blanks or tabs. A word is a sequence of characters
and/or numerals that contains no unquoted blanks. The
first word in the sequence (numbered as 0), usually spec-
ifies the name of a command. Any remaining words, with a
few exceptions, are passed to that command.
The value of a simple command is its exit value if it
ends normally or (octal) 200 status if it ends abnor-
mally. For a list of status values, see the signal
system call in AIX Operating System Technical Reference.
A pipeline is a sequence of one or more commands sepa-
rated by a | (vertical bar) or, for historical compat-
ibility, 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 sepa-
rate 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 consists 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) or an "&" (ampersand). These separators and
terminators have the following effects:
; Causes sequential execution of the preceding pipe-
line (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 zero exit value.
|| Causes the list following it to be executed only if
the preceding pipeline returns a nonzero exit
value.
Note: The cd command is an exception. If it
returns a nonzero exit value, no subsequent com-
mands in a list are executed, 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 new-line character following a pipeline func-
tions 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 fol-
lowing up to the next new-line character.
Command Execution
Each time the shell executes a command, it carries out
the substitutions discussed in the following text. If
the command 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 func-
tion, it executes the function in the shell process. The
shell sets the positional 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 executable 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 exe-
cutable but is not a compiled program, the shell assumes
that it is a shell procedure. In this case, the shell
spawns another instance of itself (a subshell), to read
the file and execute the commands included in it (note
how this differs from the execution of functions). The
shell also executes a parenthesized command in a subshell
(see page ). From your point of view as a user, a com-
piled program is run in exactly the same way as a shell
procedure.
The shell normally searches for commands in four places
in the file system. The shell first looks for the
command in the /bin directory. If it does not find the
command there, it looks in the /usr/bin directory. If
this also fails, it looks in the /etc directory and then,
finally, in the current directory. You can also give a
specific path name when you invoke a command, for example
"/bin/sort", in which case the shell does not search any
directories other than the one you specify in the path
name. 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 path name that begins with the root
directory (as in "/bin/sort"), or a path name 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 (page ).
The shell remembers the location in the search path of
each executed command (to avoid unnecessary execs later).
If the command was found in a relative directory (one
whose name does not being with /), the shell must rede-
termine 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 (page ).
Signals
The shell ignores INTERRUPT and QUIT 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 on page ).
The .profile File
When you log in, the shell is called to read your com-
mands. 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 should set
variables needed by all users). After this, the shell
looks for a file named .profile in your login directory.
If it finds one, it executes commands from it. Finally,
the shell is ready to read commands from your standard
input.
File-name Substitution
Command parameters are very often file names. You can
automatically produce a list of file names as parameters
on a command line by specifying a pattern that the shell
matches against the file names 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:
* Matches any string, including the null
_
string.
? Matches any one character.
_
[ . . . ] Matches any one of the characters enclosed in
square brackets.
[! . . . ] Matches any character other than one of the
_
characters that follow the exclamation mark
within square brackets.
Inside square brackets, a pair of characters separated by
a - (minus) specifies a set of all characters lexically
within the inclusive range of that pair, according to the
current collating sequence (see "ctab"). The NLCTAB
environment variable controls the collating sequence.
The current collating sequence may group characters into
equivalence classes for the purpose of defining the end
points of a range of characters. For example, if the
collating sequence defines the lexical order to be
"AaBbCc . . . " and groups upper- and lowercase charac-
ters 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
character of a file name is a . (dot), it can be matched
only by a pattern that literally begins with a dot. For
example, "*" matches the file names "myfile" and
"yourfile" but not the file names ".myfile" and
".yourfile". To match these files, use a pattern such as
the following:
.*file
If a pattern does not match any file names, then the
pattern itself is returned as the result of the attempted
match.
File and directory names should not contain the charac-
ters "*", "?", [, or ] because this can cause infinite
recursion (that is, infinite loops) during pattern-
matching attempts.
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 procedure,
the shell implicitly creates positional parameters that
reference each word on the command line by its position
on the command line. The word in position "0" (the pro-
cedure 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 (page ).
You can also assign values to these positional parameters
explicitly by using the built-in set command (page ).
Notes:
1. When an argument for a position is not specified, its
positional parameter is set to null.
2. Positional parameters are global and can be passed to
nested shell procedures.
USER-DEFINED VARIABLES: The shell also recognizes alpha-
numeric 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 blanks surround
the = (equal sign) in an assignment statement. (Posi-
tional parameters cannot appear in a assignment state-
ment; they can only be set as described earlier.) You
can put more than one assignment on a command line, but
remember: the shell performs the assignments from right
to left.
If you surround string with quotation marks, either
double or single (" " ' '), the shell does not treat
blanks, tabs, semicolons, and new-line characters within
it as word delimiters but imbeds them literally in the
string.
If you surround string with double quotation marks (" "),
the shell still recognizes variable names in the string
and performs variable substitution; that is, it replaces
references to positional parameters and other variable
names that are prefaced by "$" with their corresponding
values, if any. The shell also performs command substi-
tution (see "Command Substitution") within strings that
are surrounded by double quotation marks.
If you surround string with single quotation marks (' '),
the shell does no variable or command substitution within
the string. The following sequence illustrates this dif-
ference:
You:
stars=*****
asterisks1="Add $stars"
asterisks2='Add $stars'
echo $asterisks1
System:
Add *****
You:
echo $asterisks2
System:
Add $stars
The shell does not reinterpret blanks in assignments
after variable substitution (see "Blank Interpretation").
Thus the following assignments result in "$first" and
"$second" having the same value:
first='a string with embedded blanks'
second=$first
When you reference a variable, you can enclose the vari-
able name (or the digit designating a positional param-
eter) in "{ }" (braces) to delimit the variable name from
any following string. In particular, if the character
immediately following the name is a letter, digit, or
underscore and the variable is not a positional param-
eter, then the braces are required:
You:
a='This is a'
echo "${ a } n example"
Display:
This is an example
You:
echo "$a test"
Display:
This is a test
Note: The { } operator requires a space following the
opening brace and a space preceding the closing brace.
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 constitute 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 have been named as arguments to the built-in export
command. export places the named variables in the envi-
ronments of both the shell and all its future child proc-
esses.
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 on page
). 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"):
# key_command
echo $a $b
the following command lines produce the output shown:
You:
a=key1 b=key2 key_command
Display:
key1 key2
You:
a=tom b=john key_command
Display:
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 have been made
exportable from the current shell, enter:
export
(You will also get a list of variables that have been
made readonly.) 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/or not null. By defi-
nition, a variable is set if it has ever been 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 fol-
lowing 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 param-
eters.
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. Otherwise, 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. Otherwise, set vari-
able 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 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 and not null, sub-
stitute the value of variable in place of
this expression. Otherwise, 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, sub-
stitute 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 fol-
lowing 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 (see the PATH variable in the fol-
lowing list for an explanation of search
paths).
HOME The name of your login directory, the direc-
tory that becomes the current directory upon
completion of a login. The login program ini-
tializes this variable. The cd command uses
the value of $HOME as its default value. If
you use this variable in your shell procedures
rather than using explicit full path name,
your procedures run even if your login direc-
tory is changed or if another user runs them.
LIBPATH The search path for shared libraries.
LOGNAME Your login name, marked readonly in the
/etc/profile file.
MAIL The path name 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 zero.
You should set MAIL in your .profile file.
The value normally assigned to it by users of
the mail command is /usr/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 parameters. The default value is 600
seconds (10 minutes). If you set MAILCHECK to
0, the shell checks before each prompt.
MAILPATH A colon-separated list of file names (see
PATH). If you set this parameter, the shell
informs you of the arrival of mail in any of
the files specified in the list. You can
follow each file name by a "%" (percent sign)
and a message to be displayed when mail
arrives. Otherwise, the shell uses the value
of MAILMSG or by default ""you have mail"".
Note: When MAILPATH is set, these files are
checked instead of the file set by MAIL. To
check the files set by MAILPATH and the file
set by MAIL, specify the MAIL file in your
list of MAILPATH files.
MAILMSG The mail notification message. If you explic-
itly set MAILMSG to a null string ("MAIL="""),
no message is displayed.
NLCTAB Defines the collating sequence to use when
sorting names and when character ranges occur
in patterns. If absent, it may be taken form
the parameter NLFILE. If both are absent, the
American English collating sequence is used.
See "Overview of International Character
Support" in IBM RT PC Managing the AIX Oper-
ating System for further information.
PATH An ordered list of directory path names sepa-
rated 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
/bin:/usr/bin:/etc::. You can reset this var-
iable to suit your own needs. Thus if you
wish to search your current directory first,
rather than last, you would enter:
PATH=:/bin:/usr/bin:/etc
where, by definition, a null string is assumed
in front of the leading colon. 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:/bin:/usr/bin:/etc::
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 executing com-
mands under the restricted shell.
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 ""$"" (a "$" followed
by a blank).
PS2 The value of the secondary prompt string. If
the shell expects more input when it
encounters a new-line character in its input,
it prompts with the value of PS2. The default
value of PS2 is "> " (a > followed by a
blank).
IFS The characters that are internal field separa-
tors (the characters that the shell uses
during blank interpretation, see "Blank Inter-
pretation"). The shell initially sets IFS to
include the blank, tab, and new-line charac-
ters.
SHACCT The name of a file that you own. If this
parameter is set, the shell writes an
accounting record in the file for each shell
script executed. You can use accounting pro-
grams such as acctcom and acctcms to analyze
the data collected.
SHELL A path name 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 inhibits auto-
matic 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 procedure
itself. "$#" 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 presence of the required number of
arguments.
$? The exit value of the last command executed. Its
__
value is a decimal string. Most UNIX commands
return 0 to indicate successful completion. The
shell itself returns the current value of "$?" as
its exit value.
$$ The process number of the current process. Because
__
process numbers are unique among all existing proc-
esses, this string of up to five digits is often
used to generate unique names for temporary files.
The following example illustrates the recommended
practice of creating temporary files in a directory
used only for that purpose:
temp=$HOME/temp/$$
ls >$temp
.
rm $temp
$! The process number of the last process run in the
__
background (using the "&" terminator). Again, this
is a string of up to five digits.
$- A string consisting of the names of the execution
__
flags (page ) 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 variable "today". The following
assignment saves, in the variable "files", the number of
files in the current directory:
files=`ls | ws -l`
You can enclose any command that writes to standard
output in grave accents. You can nest command substi-
tutions as long as you quote the inside sets of grave
accents with a preceding \ (backslash):
logmsg=`echo Your login directory is \`pwd\``
You can also give values to shell variables indirectly by
using the built-in read command. read takes a line from
standard input (usually your keyboard), and assigns con-
secutive words on that line to any variables named:
read first init last
will take an input line of the form:
J. Q. Public
and have the same effect as if you had typed:
first=J. init=Q. last=Public
read assigns any excess words to the last variable.
Quoting Mechanisms
Many characters have a special meaning to the shell;
sometimes you want to conceal that meaning. Single (' ')
and double (" ") quotation marks surrounding a string or
a backslash (\) before a single character provide this
function in somewhat different ways.
Within single quotation marks, all characters (except the
single quotation character itself), are taken literally,
with any special meaning removed. Thus:
stuff='echo $? $*; ls * | wc'
results only in the literal string "echo $? $*; ls * |
wc" being assigned to the variable "stuff"; the "echo",
"ls", and "wc" commands are not executed, nor are the
variables "$?" and "$*" and the special character "*"
expanded by the shell.
Within double quotation marks, the special meaning of
certain characters (the "$", "`", and ") does persist,
while all other characters are taken literally. Thus,
within double quotation marks, command and variable sub-
stitution takes place. In addition, the quotation marks
do not affect the commands within a command substitution
that is part of the quoted string, so characters there
retain their special meanings.
Consider the following sequence:
You:
ls *
Display:
file1
file2
file3
You:
message="This directory contains `ls * ` "
echo $message
Display:
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 quotation marks, precede these characters with a \
(backslash). Outside of double quotation marks, pre-
ceding a character with \ is equivalent to placing it
within single quotation marks. Hence, a \ immediately
preceding the new-line character (that is, a \ at the end
of the line) hides the new-line character and allows you
to continue 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 pipe-
line.
STANDARD INPUT AND STANDARD OUTPUT: When a command
begins running, it usually expects that three files are
already open: standard input, standard output, and diag-
nostic output (sometimes called error output or standard
error output). A number called a file descriptor is
associated with each of these files as follows:
File descriptor 0 Standard input
File descriptor 1 Standard output
File descriptor 2 Diagnostic (error) output
A child process normally inherits these files from its
parent; all three files are initially assigned to the
work station (0 to the keyboard, 1 and 2 to the display).
The shell permits them to be redirected elsewhere 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 con-
tents of file, if it already exists. 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 blank interpretation
nor pattern matching of file names occurs after these
substitutions. Thus:
echo 'this is a test' > *.ggg
produces a one-line file named "*.ggg" (a disastrous name
for a file), and:
cat < ?
produces an error message, unless you have a file named
"?" (also a bad choice for a file name).
DIAGNOSTIC AND OTHER OUTPUT: Diagnostic output from UNIX
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
arrow (> >>) with a "2" (the number of the file
descriptor). For example, the following line adds error
messages from the cc command to the file "ERRORS":
cc testfile.c 2>> ERRORS
Note that there must be no blanks between the file
descriptor and the redirection symbol; otherwise, the
shell interprets the number as a separate argument to the
command.
You can also use this method to redirect the output asso-
ciated with any of the first 10 file descriptors (num-
bered 0 through 9) so that, for instance, if a command
("cmd") writes to file descriptor 9 (although this is not
a recommended programming habit), you can capture that
output in a file "savedata" as follows:
cmd 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:
cmd > standard 2> error 9> data
INLINE INPUT DOCUMENTS: Upon seeing a command line of
the form:
"cmd <<" eofstring
where eofstring is any string that does not contain any
pattern-matching characters, the shell takes the subse-
quent lines as the standard input of "cmd" until it reads
a line consisting of only eofstring (possibly preceded by
one or more tab characters). The lines between the first
eofstring and the second are frequently referred to as a
here document. If a - (minus) 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 file names that are a part
of command lines in command substitutions. If you want
to prohibit all substitutions, quote any character of
eofstring:
"cmd << "\eofstring
The here document is especially useful for a small amount
of input data that is more conveniently placed in the
shell procedure 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 procedures. Note
that inline input documents can not appear within grave
accents (command substitution).
INPUT AND OUTPUT REDIRECTION USING FILE DESCRIPTORS: As
discussed previously, a command occasionally directs
output to some file associated with a file descriptor
other than "1" or "2". The shell also provides a mech-
anism for creating an output file associated with a par-
ticular file descriptor. By entering:
fd1">&"fd2
where fd1 and fd2 are valid file descriptors, you can
direct the output that would normally be associated with
file descriptor fd1 to the file associated with fd2. The
default value for fd1 and fd2 is "1" (standard output).
If, at execution time, no file is associated with fd2,
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:
cmd 2>&1
If you want to redirect both standard output and standard
error output to the same file, enter:
cmd > file 2>&1
The order here is significant. First, the shell associ-
ates file descriptor "1" with "file"; then it associates
file descriptor "2" with the file that is currently asso-
ciated with file descriptor "1". If you reverse the
order of the redirections, standard error output will go
to the display and standard output would go 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:
fda"<&"fdb
to cause both file descriptors to be associated with the
same input file. For commands that run sequentially, the
default value of fda and fdb is "0" (standard input).
For commands that run asynchronously (commands terminated
by "&"), the default value of fda and fdb 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 trun-
cate it to zero length.
>>file Use file as standard output. Create the
file if it does not exist; otherwise add
the output to the end of the file.
<<[-]eofstr Read as standard input all lines from
eofstr up to a line containing only eofstr
or up to an end-of-file character. If any
character in eofstr 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 new-line character
(\new-line). Use a \ to quote characters
within eofstr or within the input lines.
If you add a - (minus) to << then all
leading tabs are stripped from eofstr 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
output.
Blank Interpretation
After the shell performs variable and command substi-
tution, it scans the results for internal field separa-
tors (those defined in the shell variable IFS, see page
). 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).
Control Commands
The shell provides several flow control commands that are
useful in creating shell procedures:
for name [ in word . . . ]
do list
done For each word, sets name to word and
executes the commands in list. If you
omit in word . . ., then the for
command executes list for each posi-
tional parameter that is set. Exe-
cution ends when there are no more
words in the word list.
case word in
pattern [|pattern] . . . ) list;;
[ .
.
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 pat-
terns that you use for file-name sub-
stitution (see "File-name
Substitution"), except that you do not
need to match explicitly a slash, a
leading dot, or a dot immediately fol-
lowing a slash.
if list
then list
[elif list ] . . .
[else list]
fi Executes the list following the if
keyword. If it returns a zero exit
value, execute the list following the
first then. Otherwise, execute the
list following elif (if there is an
elif), and if its exit value is zero,
execute the next then. Failing that,
execute the list following the else.
If no else list or then list is exe-
cuted, the if command returns a 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 zero, executes the list
following do. Continue 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 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, executes the
list following do. Continues looping
through the lists until the exit value
of the last command in the until list
is zero. If no commands in the do
list are executed, the until command
returns a zero exit value.
(list) Executes the commands in list in a
subshell.
{ list; } Executes the commands in list in the
current shell process (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 words are recognized only as the first word
of a command and when not quoted:
if then else elif fi case esac for while until do
done { }
Built-in Commands
: Does nothing. This null command returns a
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 speci-
fied, resumes at the nth enclosing loop.
cd [dir] Changes the current directory to dir. The
value of the shell variable HOME is the
default dir. The shell variable CDPATH
defines the search path for the directory
containing dir. Alternative directory names
appear in a colon-separated list. A null
path name specifies the current directory
(which is the default path). This null path
name can appear immediately after the equal
sign in the assignment or between the colon
delimiters anywhere else in the path list.
If dir begins with a slash, the shell does
not use the search path. Otherwise, the
shell searches each directory in the path.
cd cannot be executed by the restricted
shell.
echo [arg . . . ]
Writes arguments to standard output. See
"echo" for a discussion of its usage and
parameters.
eval [arg . . . ]
Reads arguments as input to the shell and
executes the resulting command(s).
exec [arg . . . ]
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 modi-
fied (not a good idea with your login
shell).
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
(an end of file will also cause a shell to
exit).
export [name . . . ]
Marks the specified names for automatic
export to the environments of subsequently
executed commands. If you do not specify a
names, export displays a list of all 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 example, the
location of a relative path name 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.
newgrp [arg . . . ]
Executes the newgrp command in the current
shell process. See "newgrp" for a dis-
cussion of command options.
pwd Displays the current directory. See "pwd"
for a discussion 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
unless it encounters an end of file.
readonly [name . . . ]
Marks the specified names readonly. The
values of these names cannot be reset. If
you do not specify any names, readonly dis-
plays a list of all readonly names.
return [n] Cause 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 exe-
cuted in that function. This command is
valid only when executed within a shell
function.
set [flag . . . [arg] . . . ]
-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 file-name substitution.
-h Locates and remembers the commands
called within functions as the functions
are defined (normally these commands are
located when the function is
executed--see the hash command on page
).
-k Places all keyword parameters in the
environment for a command, not just
those that precede the command name.
-n Reads commands but do 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 "$1" to a string
beginning with a - (minus).
Using a + (plus) rather than a - (minus)
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 parame-
ters and are assigned, in order, to "$1",
"$2", and so on. If you do not specify
flags or parameters, set displays all names.
shift [n] Shifts command line arguments to the left;
that is, reassign the value of the posi-
tional parameters by discarding 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 9 command line argu-
ments, the tenth is assigned to "$9" and any
that remain are still unassigned (until
after another shift). If there are 9 or
fewer arguments, a shift unsets the highest-
numbered positional 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 expr | [ expr ]
Evaluates conditional expressions. See
"test" for a discussion of command options.
times Displays the accumulated user and system
times for processes run from the shell.
trap [arg] [n] . . .
Runs the command specified by arg when the
shell receives signal(s) n. (Note that the
shell scans parm once when the trap is set
and once when the trap is taken). trap com-
mands are executed in order of signal
number. Any attempt to set a trap on a
signal that was ignored on entry to the
current shell is ineffective.
If you do not specify an arg, then all
trap(s) n are reset to their current values.
If arg is the null string, then this signal
is ignored by the shell and by the commands
it invokes. If n is 0, then arg is executed
on exit from the shell. If you specify no
arg and no n, trap displays a list of com-
mands associated with each signal number.
type [name . . . ]
For each name, indicates how the shell would
interpret 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).
Notes:
1. Since the shell rounds n down to the
nearest cluster size, it is best to make
it a multiple of 4 (for example, speci-
fying values of 1, 2, or 3 for n all
result in a size limit of 0).
2. Any user can decreased 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 the user file-creation mask to 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 or function. The variables PATH,
PS1, PS2, MAILCHECK and IFS cannot be unset.
wait [n] Waits for the child process whose process
number is n to end and reports its termi-
nation status. If you do not specify n,
then the shell waits for all currently
active child processes and the return value
is 0.
Running the Shell
The sh command can be run either as a login shell or as a
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 initial - (minus), 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 following 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 environments whose capabilities are more controlled
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 (see "cd")
o Setting the value of "$"PATH
o Specifying path or command names containing "/"
o Redirecting output (> and >>).
The restrictions above are enforced after .profile is
interpreted, meaning that the restrictions can override
settings originally set in .profile.
When a command to be run is found to be a shell proce-
dure, rsh starts sh to run it. Thus, it is possible to
provide to the end-user shell procedures that have access
to the full power of the standard shell, while imposing a
limited menu of commands; this scheme assumes that the
end-user does not have write and run permissions in the
same directory.
The net effect of these rules is that the writer of the
.profile has complete control over user actions, by per-
forming setup actions and leaving the user in an appro-
priate directory (probably not the login directory).
When called with the name -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
immediate exit instead of a return to command level.
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 param-
eter is a command file (shell procedure). It passes any-
thing else on the command line to that command file (see
"Positional Parameters").
-c cmdstring
Runs commands read from cmdstring. 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 work station. In
this case the shell ignores the TERMINATE
signal (so that kill 0 does not stop an
interactive shell) and traps an INTERRUPT (so
that you can interrupt wait). In all cases,
the shell ignores the QUIT signal. (See the
signal system call in AIX Operating System
Technical Reference 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 parameters 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 parameters are described in the
built-in set command on page .
FILES
/etc/environment
/etc/profile
$HOME/.profile
/tmp/sh*
/dev/null
RELATED INFORMATION
The following commands: "cd," "echo," "env," "login,"
"newgrp," "pwd," "test" and "umask."
The dup, exec, fork, fullstat, pipe, signal, ulimit, and
umask system calls and the a.out, .profile, and environ
files in AIX Operating System Technical Reference.
"Using the Shell with Processes" and "Advanced Shell Fea-
tures" in Using the AIX Operating System.
"Overview of International Character Support" in Managing
the AIX Operating System.