NAME
ksh - Korn shell
SYNOPSIS
ksh [-ir] [-c command_string | -s] [+ | -aefhkmnopstuvx] [+
| -o][option ...]
| [+ | -A name] [argument ...] | [file] [argument ...]
The Korn shell is an interactive command interpreter and a
command programming language.
FLAGS
-c command_string
Causes ksh to read commands from command_string.
-i Causes ksh to run as an interactive shell. The SIGTERM
signal is thus ignored, and the SIGINT signal is caught,
causing the current command to be terminated and a new
prompt to be output.
-r Causes ksh to run as a restricted shell.
-s Causes ksh to read commands from standard input. If you
do not specify the -c flag or do not specify any argu-
ments to ksh other than flags, ksh automatically invokes
the -s flag. The -c flag overrides the -s flag, how-
ever.
The rest of the flags that can be used with ksh are
described under the set subcommand, in the subsection Spe-
cial ksh Commands.
DESCRIPTION
The Korn shell carries out commands either interactively
from a terminal keyboard or from a file. The Korn shell is
backward compatible with the Bourne shell (invoked with the
sh command) and contains virtually all of the Bourne shell
features, as well as several of the best features of the C
shell.
Some important features of the Korn shell are as follows:
o Command aliasing
o Filename substitution
o Tilde substitution
o Command substitution
o Parameter substitution
o Job control
o Inline editing
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).
Comments
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 command is
that of the last simple command executed in the command.
for identifier [in word...] ;do list ;done
Each time a for command is executed, identifier is set
to the next word taken from the in word list. If in
word ... is omitted, the for command executes the do
list once for each positional parameter that is set.
(See Parameter Substitution.) Execution ends when there
are no more words in the list.
select identifier [in word...] ;do list ;done
Prints on standard error (file descriptor 2), the set of
words, each preceded by a number. If in word... is
omitted, then the positional parameters are used
instead. (See Parameter Substitution.) The PS3 prompt
is printed and a line is read from the standard input.
If this line consists of the number of one of the listed
words, then the value of the parameter identifier is set
to the word corresponding to this number. If this line
is empty, the selection list is printed again. Other-
wise, the value of the parameter identifier is set to
null. The contents of the line read from standard input
is saved in the REPLY parameter. The list is executed
for each selection until a break or End-of-File is
encountered.
case word in [[(] pattern [| pattern] ...) list ;;] ... esac
Executes the list associated with the first pattern that
matches word. The form of the patterns is the same as
that used for filename generation. (See Filename Gen-
eration.)
if list ;then list [elif list ;then list] ... [;else list] ;fi
Executes the list following if and, if it returns a 0
(zero) exit status, executes the list following the
first then. Otherwise, the list following elif is exe-
cuted and, if its value is 0 (zero), the list following
the next then is executed. Failing that, the else list
is executed. If no else list or then list is executed,
then the if command returns a 0 (zero) exit status.
while list ;do list ;done
until list ;do list ;done
Executes the while list repeatedly, and if the exit
status of the last command in the list is 0 (zero), exe-
cutes the do list; otherwise the loop terminates. If no
commands in the do list are executed, then the while
command returns a 0 (zero) exit status; until can be
used in place of while to negate the loop termination
test.
(list)
Executes list in a separate environment. Note that if
two adjacent open parentheses are needed for nesting, a
space must be inserted to avoid arithmetic evaluation as
described later.
{list;}
Executes list. Note that unlike the metacharacters (
and ), { and } are reserved words and must be at the
beginning of a line or after a ; (semicolon) in order to
be recognized.
[[expression]]
Evaluates expression and returns a 0 (zero) exit status
when expression is TRUE. See Conditional Expressions
for a description of expression.
function identifier {list;}
identifier () {list;}
Defines a function that is referenced by identifier.
The body of the function is the list of commands between
{ and }. (See Functions.)
time pipeline
Executes pipeline and prints the elapsed time as well
as the user and system time on standard error.
The following reserved words are recognized only when they
appear, without single or double quotes, as the first word
of a command:
if for case
then while esac
else until function
elif do select
fi done time
{ } [[ ]]
Command Aliasing
The first word of each command is replaced by the text of an
alias (if an alias for this word was defined). The first
character of an alias name can be any nonspecial printable
character, but the rest of the characters must be the same
as for a valid identifier. The replacement string can con-
tain any valid shell script, including the metacharacters
previously listed. The first word of each command in the
replaced text, other than any that are in the process of
being replaced, will be tested for aliases. If the last
character of the alias value is a space, the word following
the alias will also be checked for alias substitution.
Aliases can be used to redefine special built-in commands
but cannot be used to redefine the reserved words previously
listed. Aliases can be created, listed, and exported with
the alias command and can be removed with the unalias com-
mand. Exported aliases remain in effect for scripts invoked
by name, but must be reinitialized for separate invocations
of the shell. (See Invocation.)
Aliasing is performed when scripts are read, not while they
are executed. Therefore, for an alias to take effect, the
alias definition command has to be executed before the com-
mand that references the alias is read.
Aliases are frequently used as shorthand for full pathnames.
An option to the aliasing facility allows the value of the
alias to be automatically set to the full pathname of the
corresponding command. These aliases are called tracked
aliases.
The value of a tracked alias is defined the first time the
corresponding command is looked up and becomes undefined
each time the PATH environment variable is reset. These
aliases remain tracked so that the next subsequent reference
will redefine the value. Several tracked aliases are com-
piled into the shell. The -h flag of the set command makes
each referenced command name into a tracked alias.
The following exported aliases are compiled into the shell,
but can be unset or redefined:
autoload='typeset -fu'
false='let 0'
functions='typeset -f'
hash='alias -t'
history='fc -l'
integer='typeset -i'
nohup='nohup '
r='fc -e -'
true=':'
type='whence -v'
Tilde Substitution
After alias substitution is performed, each word is checked
to see if it begins with an unquoted ~ (tilde). If it does,
then the word up to a / (slash) is checked to see if it
matches a username in the /etc/passwd file. If a match is
found, the tilde and the matched login name are replaced by
the login directory of the matched user. This is called a
tilde substitution. If no match is found, the original text
is left unchanged. A tilde by itself, or in front of a /,
is replaced by the value of the HOME parameter. A tilde
followed by a + (plus sign) or - (dash) is replaced by $PWD
and $OLDPWD, respectively.
In addition, tilde substitution is attempted when the value
of a variable assignment parameter begins with a tilde.
Command Substitution
The standard output from a command enclosed in parentheses
preceded by a dollar sign $( ) or a pair of `` (grave
accents) can be used as part or all of a word; trailing new-
lines are removed. In the second (archaic) form, the string
between the grave accents is processed for special quoting
characters before the command is executed. (See Quoting.)
The command substitution $(cat file) can be replaced by the
equivalent but faster $(<file). Command substitution of
most special commands that do not perform input/output
redirection are carried out without creating a separate pro-
cess. An arithmetic expression enclosed in double
parentheses preceded by a dollar sign ( $(( )) ) is replaced
by the value of the arithmetic expression within the double
parentheses.
Parameter Substitution
A parameter is an identifier, one or more digits, or any of
the characters *, @, #, ?, -, $, and !. A named parameter
(a parameter denoted by an identifier) has a value and 0
(zero) or more attributes. Named parameters can be assigned
values and attributes by using the typeset special command.
The attributes supported by the shell are described later
with the typeset special command. Exported parameters pass
values and attributes to the environment.
The shell supports a 1-dimensional array facility. An ele-
ment of an array parameter is referenced by a subscript. A
subscript is denoted by an arithmetic expression enclosed
with [ ] (brackets). To assign values to an array, use set
-A name value ... The value of all subscripts must be in
the range of 0 to 1023. Arrays need not be declared. Any
reference to a named parameter with a valid subscript is
legal and an array will be created if necessary. Referenc-
ing an array without a subscript is equivalent to referenc-
ing the element 0 (zero).
The value of a named parameter can be assigned by the fol-
lowing:
name=value [ name=value ]
If the integer attribute, -i, is set for name, the value is
subject to arithmetic evaluation, as described later. Posi-
tional parameters, which are denoted by a number, can be
assigned values with the set special command. Parameter $0
is set from argument 0 (zero) when the shell is invoked.
The $ (dollar sign) character is used to introduce substi-
tutable parameters.
${parameter}
Reads all the characters from the ${ (dollar sign left
brace) to the matching } (right brace) as part of the
same word even if it contains braces or metacharacters.
The value, if any, of the parameter is substituted. The
braces are required when parameter is followed by a
letter, digit, or underscore that is not to be inter-
preted as part of its name or when a named parameter is
subscripted. If parameter is one or more digits, it is
a positional parameter. A positional parameter of more
than one digit must be enclosed in braces. If parameter
is * (asterisk) or @ (at sign), all the positional
parameters, starting with $1, are substituted (separated
by a field separator character). If an array identifier
with subscript * or @ is used, the value for each of the
elements is substituted (separated by a field separator
character).
${#parameter}
Substitutes the number of positional parameters if
parameter is * or @; otherwise, the length of the value
of the parameter is substituted.
${#identifier[*]}
Substitutes the number of elements in the array identif-
ier.
${parameter:-word}
Substitutes the value of parameter if it is set and
non-null; otherwise, substitute word.
${parameter:=word}
Sets parameter to word if it is not set or is null; the
value of the parameter is then substituted. Positional
parameters cannot be assigned values in this way.
${parameter:?word}
Substitutes the value of parameter if it is set and is
non-null; otherwise, print word and exit from the shell.
If word is omitted, a standard message is printed.
${parameter:+word}
Substitute word if parameter is set and is non-null;
otherwise, substitute nothing.
${parameter#pattern} | ${parameter##pattern}
Causes the value of this substitution to be the value of
parameter with the matched portion deleted if the shell
pattern matches the beginning of the value of parameter;
otherwise the value of parameter is substituted. In the
first form, the smallest matching pattern is deleted and
in the second form, the largest matching pattern is
deleted.
${parameter%pattern} | ${parameter%%pattern}
Causes the value of this substitution to be the value of
parameter with the matched part deleted if the shell
pattern matches the end of the value of parameter; oth-
erwise, substitute the value of parameter. In the first
form, the smallest matching pattern is deleted and in
the second form, the largest matching pattern is
deleted.
If the : (colon) is omitted from the previous expressions,
then the shell checks only whether parameter is set or not.
In the previous expressions, word is not evaluated unless it
is to be used as the substituted string, so that, in the
following example, pwd is executed only if d is not set or
is null:
echo ${d:-$(pwd)}
The following parameters are automatically set by the shell:
# (hash mark)
The number of positional parameters in decimal.
- (dash)
Flags supplied to the shell on invocation or by the set
command.
? (question mark)
The decimal value returned by the last executed command.
$ (dollar sign)
The process number of this shell.
_ (underscore)
Initially, the value of _ (underscore) is an absolute
pathname of the shell or script being executed as passed
in the environment. Subsequently, it is assigned the
last argument of the previous command. This parameter is
not set for commands that are asynchronous. This parame-
ter is also used to hold the name of the matching MAIL
file when checking for mail.
! (exclamation point)
The process number of the last background command
invoked.
ERRNO
The value of errno as set by the most recently failed
system call. This value is system dependent and is
intended for debugging purposes.
LINENO
The line number of the current line within the script or
function being executed.
OLDPWD
The previous working directory set by the cd command.
OPTARG
The value of the last option argument processed by the
getopts special command.
OPTIND
The index of the last option argument processed by the
getopts special command.
PPID
The process number of the parent of the shell.
PWD The present working directory set by the cd command.
RANDOM
Each time this parameter is referenced, a random
integer, uniformly distributed between 0 and 32767, is
generated. The sequence of random numbers can be ini-
tialized by assigning a numeric value to RANDOM.
REPLY
This parameter is set by the select statement and by the
read special command when no arguments are supplied.
SECONDS
Each time this parameter is referenced, the number of
seconds since shell invocation is returned. If this
parameter is assigned a value, then the value returned
upon reference will be the value that was assigned plus
the number of seconds since the assignment.
The following parameters are used by the shell:
CDPATH
The search path for the cd command.
COLUMNS
If this variable is set, the value is used to define the
width of the edit window for the shell edit modes and
for printing select lists.
EDITOR
If the value of this variable ends in emacs, gmacs, or
vi and the VISUAL variable is not set, then the
corresponding option (see set under Special ksh Com-
mands) will be turned on.
ENV If this parameter is set, then parameter substitution is
performed on the value to generate the pathname of the
script that will be executed when the shell is invoked.
(See Invocation.) This file is typically used for alias
and function definitions.
FCEDIT
The default editor name for the fc command.
FPATH
The search path for function definitions. This path is
searched when a function with the -u attribute is refer-
enced and when a command is not found. If an executable
file is found, then it is read and executed in the
current environment.
IFS Internal field separators, normally spaces, tabs, and
newlines that are used to separate command words which
result from command or parameter substitution and for
separating words with the read special command. The
first character of the IFS parameter is used to separate
arguments for the $* substitution. (See Quoting.)
HISTFILE
If this parameter is set when the shell is invoked, then
the value is the pathname of the file that will be used
to store the command history. (See Command Reentry.)
HISTSIZE
If this parameter is set when the shell is invoked, the
number of previously entered commands that are accessi-
ble by this shell will be greater than or equal to this
number. The default is 128.
HOME
The default argument (home directory) for the cd com-
mand.
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 can be taken
from the LANG parameter. 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.
LINES
If this variable is set, the value is used to determine
the column length for printing select lists. Select
lists will print vertically until about two-thirds of
LINES lines are filled.
MAIL
If this parameter is set to the name of a mail file and
the MAILPATH parameter is not set, the shell informs you
of the arrival of mail in the specified file.
MAILCHECK
This variable specifies how often (in seconds) the shell
checks for changes in the modification time of any of
the files specified by the MAILPATH or MAIL parameters.
The default value is 600 seconds. When the time has
elapsed, the shell checks before issuing the next
prompt.
MAILPATH
A list of filenames separated by : (colons). If this
parameter is set, the shell informs you of any modifica-
tions to the specified files that have occurred within
the last MAILCHECK seconds. Each filename can be fol-
lowed by a ? (question mark) and a message that will be
printed. The message will undergo parameter substitu-
tion with the parameter, $_ defined as the name of the
file that has changed. The default message is you have
mail in $_.
NLSPATH
Specifies a list of directories to search to find mes-
sage catalogs.
PATH
The search path for commands. (See Execution.) You
cannot change PATH if executing under rsh, except in
.profile.
PS1 The value of this parameter is expanded for parameter
substitution to define the primary prompt string which
by default is the $ (dollar sign). The ! (exclamation
point) in the primary prompt string is replaced by the
command number. (See Command Reentry.)
PS2 Secondary prompt string, by default > (right angle
bracket).
PS3 Selection prompt string used within a select loop, by
default #? (number sign, question mark).
PS4 The value of this parameter is expanded for parameter
substitution and precedes each line of an execution
trace. If omitted, the execution trace prompt is +
(plus sign).
SHELL
The pathname of the shell is kept in the environment.
TMOUT
If set to a value greater than 0 (zero), the shell ter-
minates if a command is not entered within the
prescribed number of seconds after issuing the PS1
prompt. (Note that the shell can be compiled with a
maximum bound for this value that cannot be exceeded.)
VISUAL
If the value of this variable ends in emacs, gmacs, or
vi, the corresponding option (see the set command in
Special ksh Commands) will be turned on.
The shell gives default values to PATH, PS1, PS2, MAILCHECK,
TMOUT, and IFS, while HOME, SHELL, ENV, and MAIL are not set
by the shell (although HOME is set by the login command).
On some systems, MAIL and SHELL are also set by the login
command.
Interpretation of Spaces
After parameter and command substitution, the results of
substitutions are scanned for the field separator characters
(those found in IFS), and split into distinct arguments
where such characters are found. Explicit null arguments
(`` or '') are retained. Implicit null arguments (those
resulting from parameters that have no values) are removed.
Filename Generation
Following substitution, each command word is scanned for the
characters * (asterisk), ? (question mark), and [ ]
(brackets), unless the -f option was set. If one of these
characters appears, the word is regarded as a pattern. The
word is replaced with lexicographically sorted filenames
that match the pattern. If no filename is found that
matches the pattern, the word is left unchanged. When a
pattern is used for filename generation, the . (dot) charac-
ter at the start of a filename or immediately following a /
(slash), as well as the / character itself, must be matched
explicitly. In other instances of pattern matching, the /
and . are not treated specially.
* Matches any string, including the null string.
? Matches any single character.
[...]
Matches any one of the enclosed characters. In an
expression such as [a-z], the - (dash) means "through"
according to the current collating sequence. The col-
lating sequence is determined by the value of the
LC_COLLATE environment variable. (See "Using Interna-
tionalization Features" in the OSF/1 User's Guide for
more information on collating sequences.) If the first
character following the [ (left bracket) is a ! (excla-
mation point), then any character not enclosed is
matched. A - can be included in the character set by
putting it as the first or last character.
A pattern_list is a list of one or more patterns separated
from each other with a | (vertical bar). Composite patterns
can be formed with one or more of the following:
?(pattern_list)
Optionally matches any one of the given patterns.
*(pattern_list)
Matches zero or more occurrences of the given patterns.
+(pattern_list)
Matches one or more occurrences of the given patterns.
@(pattern_list)
Matches exactly one of the given patterns.
!(pattern_list)
Matches anything, except one of the given patterns.
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.
Quoting
The following characters have a special meaning to the shell
and cause termination of a word unless quoted:
; & ( ) | ^ < > <newline> <space> <tab>
Each of the metacharacters previously listed has a special
meaning to the shell and causes termination of a word unless
quoted. A character can be quoted (that is, made to stand
for itself) by preceding it with a \ (backslash). The pair
\newline is ignored. All characters enclosed between a pair
of '' (single quotes) are quoted. A single quote cannot
appear within single quotes.
Inside "" (double quotes) parameter and command substitution
occurs and \ quotes the characters \, `, ', and $. The
meaning of $* and $@ is identical when not quoted or when
used as a parameter assignment value or as a filename. How-
ever, when used as a command argument, '$*' is equivalent to
'$1d$2d. . .', where d is the first character of the IFS
parameter, whereas '$@' is equivalent to '$1' '$2' . . .
Inside `` (grave accents) \ (backslash) quotes the charac-
ters \, `, and $. If the grave accents occur within double
quotes, then \ also quotes the ' (single quote) character.
The special meaning of reserved words or aliases can be
removed by quoting any character of the reserved word. The
recognition of function names or special command names
listed later cannot be altered by quoting them.
Arithmetic Evaluation
An ability to perform integer arithmetic is provided with
the let special command. Evaluations are performed using
long arithmetic. Constants are of the form [base#]n, where
base is a decimal number between 2 and 36 representing the
arithmetic base and n is a number in that base. If base is
omitted, then base 10 is used.
An arithmetic expression uses the same syntax, precedence,
and associativity of expression of the C language. All the
integral operators, other than ++, --, ?:, and , are sup-
ported. Named parameters can be referenced by name within
an arithmetic expression without using the parameter substi-
tution syntax. When a named parameter is referenced, its
value is evaluated as an arithmetic expression.
An internal integer representation of a named parameter can
be specified with the -i option of the typeset special com-
mand. Arithmetic evaluation is performed on the value of
each assignment to a named parameter with the -i attribute.
If you do not specify an arithmetic base, the first assign-
ment to the parameter determines the arithmetic base. This
base is used when parameter substitution occurs.
Because many of the arithmetic operators require quoting, an
alternative form of the let command is provided. For any
command that begins with a ((, all the characters until a
matching )) are treated as a quoted expression. More pre-
cisely, ((...)) is equivalent to let "...".
Note that ((...)) is a command with a return value, whereas
$((...)) is the way to put the string representation of the
value of an arithmetic expression into the command line
(that is, it is like a $ variable).
Prompting
When used interactively, the shell prompts with the value of
PS1 before reading a command. If at any time a newline is
typed and further input is needed to complete a command,
then the secondary prompt (that is, the value of PS2) is
issued.
Conditional Expressions
A conditional expression is used with the [[ compound com-
mand to test attributes of files and to compare strings.
Word splitting and filename generation are not performed on
the words between [[ and ]]. Each expression can be con-
structed from one or more of the following unary or binary
expressions:
-a file
TRUE, if file exists.
-b file
TRUE, if file exists and is a block-special file.
-c file
TRUE, if file exists and is a character-special file.
-d file
TRUE, if file exists and is a directory.
-f file
TRUE, if file exists and is an ordinary file.
-g file
TRUE, if file exists and has its setgid bit set.
-G file
TRUE, if file exists and its group matches the effective
group ID of this process.
-k file
TRUE, if file exists and has its sticky bit set.
-L file
TRUE, if file exists and is a symbolic link.
-n string
TRUE, if length of string is nonzero.
-o option
TRUE, if option named option is on.
-O file
TRUE, if file exists and is owned by the effective user
ID of this process.
-p file
TRUE, if file exists and is a FIFO special file or a
pipe.
-r file
TRUE, if file exists and is readable by current process.
-s file
TRUE, if file exists and has size greater than 0 (zero).
-S file
TRUE, if file exists and is a socket.
-t file_des
TRUE, if file descriptor number file_des is open and
associated with a terminal device.
-u file
TRUE, if file exists and has its setuid bit set.
-w file
TRUE, if file exists and is writable by current process.
-x file
TRUE, if file exists and is executable by current pro-
cess. If file exists and is a directory, then the
current process has permission to search in the direc-
tory.
-z string
TRUE, if length of string is 0 (zero).
file1 -nt file2
TRUE, if file1 exists and is newer than file2.
file1 -ot file2
TRUE, if file1 exists and is older than file2.
file1 -ef file2
TRUE, if file1 and file2 exist and refer to the same
file.
string = pattern
TRUE, if string matches pattern.
string != pattern
TRUE, if string does not match pattern.
string1 < string2
TRUE, if string1 collates before string2.
string1 > string2
TRUE, if string1 collates after string2.
expression1 -eq expression2
TRUE, if expression1 is equal to expression2.
expression1 -ne expression2
TRUE, if expression1 is not equal to expression2.
expression1 -lt expression2
TRUE, if expression1 is less than expression2.
expression1 -gt expression2
TRUE, if expression1 is greater than expression2.
expression1 -le expression2
TRUE, if expression1 is less than or equal to expres-
sion2.
expression1 -ge expression2
TRUE, if expression1 is greater than or equal to expres-
sion2.
A compound expression can be constructed from these primi-
tives by using any of the following, listed in decreasing
order of precedence.
(expression)
TRUE, if expression is TRUE. Used to group expressions.
! expression
TRUE if expression is FALSE.
expression1 && expression2
TRUE, if expression1 and expression2 are both TRUE.
expression1 || expression2
TRUE, if either expression1 or expression2 is TRUE.
Input/Output
Before a command is executed, you can redirect its input and
output by using a special notation interpreted by the shell.
The following can appear anywhere in a simple command or can
precede or follow a command and are not passed on to the
invoked command. Command and parameter substitution occurs
before word or digit is used, except as noted in the follow-
ing text. Filename generation occurs only if the pattern
matches a single file and interpretation of spaces is not
performed.
<word
Use file word as standard input (file descriptor 0).
>word
Use file word as standard output (file descriptor 1).
If the file does not exist, it is created. If the file
exists, and the noclobber option is on, this causes an
error; otherwise, it is truncated to 0 (zero) length.
>|word
Sames as >, except that it overrides the noclobber
option.
>>word
Use file word as standard output. If the file exists,
output is appended to it (by first seeking to the End-
of-File); otherwise, the file is created.
<>word
Open file word for reading and writing as standard
input.
<<[-]word
The shell input is read up to a line that is the same as
word, or to an End-of-File. No parameter substitution,
command substitution, or filename generation is per-
formed on word. The resulting document, called a here
document, becomes the standard input. If any character
of word is quoted, then no interpretation is placed upon
the characters of the document; otherwise, parameter and
command substitution occurs, \newline is ignored, and \
must be used to quote the characters \, $, `, and the
first character of word. If - is appended to <<, then
all leading tabs are stripped from word and from the
document.
<&digit
The standard input is duplicated from file descriptor
digit (see dup()). The standard output is duplicated
using >& digit.
<&- The standard input is closed. The standard output is
closed using >&-.
<&p The input from the coprocess (or background process) is
moved to standard input.
>&p The output to the coprocess is moved to standard output.
If one of the preceding redirections is preceded by a digit,
then the file descriptor number referred to is that speci-
fied by the digit (instead of the default 0 or 1). For
example:
... 2>&1
means file descriptor 2 is to be opened for writing as a
duplicate of file descriptor 1.
The order in which redirections are specified is signifi-
cant. The shell evaluates each redirection in terms of the
(file descriptor, file) association at the time of evalua-
tion. For example:
... 1>fname >&1
first associates file descriptor 1 with file fname. It then
associates file descriptor 2 with the file associated with
file descriptor 1 (that is, fname). If the order of
redirections were reversed, file descriptor 2 is associated
with the terminal (assuming file descriptor 1 is) and then
file descriptor 1 is associated with file fname.
If a command is followed by & and job control is not active,
the default standard input for the command is the empty
/dev/null file. Otherwise, the environment for the execu-
tion of a command contains the file descriptors of the
invoking shell as modified by input/output specifications.
Environment
The environment is a list of name-value pairs that is passed
to an executed program in the same way as a normal argument
list. The names must be identifiers and the values are
character strings. The shell interacts with the environment
in several ways. On invocation, the shell scans the
environment and creates a parameter for each name found,
giving it the corresponding value and marking it export.
Executed commands inherit the environment. If you modify
the values of these parameters or create new ones, using the
export or typeset -x commands, they become part of the
environment. The environment seen by any executed command
is thus composed of any name-value pairs originally inher-
ited by the shell, whose values can be modified by the
current shell, plus any additions that must be noted in the
export or typeset -x commands.
You can augment the environment for any simple command or
function by prefixing it with one or more parameter assign-
ments. A parameter assignment argument is a word of the
form identifier=value.
Thus, the following two expressions are equivalent (as far
as the execution of command is concerned):
TERM=450 command argument ...
(export TERM; TERM=450; command argument ...)
If the -k flag is set, all parameter assignment arguments
are placed in the environment, even if they occur after the
command name. The following first prints a=b c and then c:
echo a=b c
set -k
echo a=b c
This feature is intended for use with scripts written for
early versions of the shell; its use in new scripts is
strongly discouraged. It is likely to disappear someday.
Functions
The function reserved word is used to define shell func-
tions. Shell functions are read in and stored internally.
Alias names are resolved when the function is read. Func-
tions are executed like commands with the arguments passed
as positional parameters. (See Execution.)
Functions execute in the same process as the caller and
share all files and the present working directory with the
caller. Traps caught by the caller are reset to their
default action inside the function. A trap condition that
is not caught or ignored by the function causes the function
to terminate and the condition to be passed on to the
caller. A trap on EXIT set inside a function is executed
after the function completes in the environment of the
caller. Ordinarily, variables are shared between the cal-
ling program and the function. However, the special command
typeset used within a function defines local variables whose
scope includes the current function and all functions it
calls.
The special command return is used to return from function
calls. Errors within functions return control to the
caller.
Function identifiers can be listed with the -f or +f option
of the typeset special command. The text of functions is
also listed with -f. Function can be undefined with the -f
option of the unset special command.
Ordinarily, functions are unset when the shell executes a
shell script. The -xf option of the typeset command allows
a function to be exported to scripts that are executed
without a separate invocation of the shell. Functions that
need to be defined across separate invocations of the shell
should be specified in the ENV file with the -xf option of
typeset.
Jobs
If the monitor option of the set command is turned on, an
interactive shell associates a job with each pipeline. It
keeps a table of current jobs, printed by the jobs command,
and assigns them small integer numbers. When a job is
started asynchronously with &, the shell prints a line that
looks like:
[1] 1234
This line indicates that the job, which was started asyn-
chronously, was job number 1 and had one (top-level) pro-
cess, whose process ID was 1234.
If you are running a job and want to do something else, you
can enter the Suspend key sequence (normally <Ctrl-z>, which
sends a SIGINT signal to the current job. The shell then
normally indicates that the job has been stopped, and it
prints another prompt. You can then manipulate the state of
this job, putting it in the background with the bg command,
or run some other commands and then eventually bring the job
back into the foreground with the foreground command fg.
The job suspension takes effect immediately, and corresponds
to the Interrupt key sequence in that pending output and
unread input are discarded. A special key sequence, <Ctrl-
y>, does not generate a SIGINT signal until a program
attempts to read it. (See the read() system call for more
information.) This key sequence can usefully be typed ahead
when you have prepared some commands for a job that you wish
to stop after it has read them.
A job being run in the background will stop if it tries to
read from the terminal. Background jobs are normally
allowed to produce output, but this can be disabled by issu-
ing the stty tostop command. If you set this tty option,
then background jobs will stop when they try to produce out-
put like they do when they try to read input.
There are several ways to refer to jobs in the shell. A job
can be referred to by the process ID of any process of the
job, or by one of the following:
%job_number
The job with the given number.
%string
Any job whose command line begins with string.
%?string
Any job whose command line contains string.
%% Current job.
%+ Equivalent to %%.
%- Previous job.
This shell learns immediately whenever a process changes
state. It normally informs you whenever a job becomes
blocked so that no further progress is possible, but only
just before it prints a prompt. This is done so that it
does not otherwise disturb your work.
When the monitor mode is on, each background job that is
completed triggers any trap set for CHLD.
When you try to leave the shell while jobs are stopped or
running, you are warned that You have stopped(running) jobs.
You can use the jobs command to see what they are. If you
do this or immediately try to exit again, the shell does not
warn you a second time, and the stopped jobs are terminated.
Signals
The SIGINT and SIGQUIT signals for an invoked command are
ignored if the command is followed by & and job monitor
option is not active. Otherwise, signals have the values
inherited by the shell from its parent (but see also the
trap command).
Execution
Each time a command is executed, the previous substitutions
are carried out. If the command name matches one of the
special commands listed later, it is executed within the
current shell process. Next, the command name is checked to
see if it matches one of the user-defined functions. If it
does, the positional parameters are saved and then reset to
the arguments of the function call. When the function is
completed or issues a return, the positional parameter list
is restored and any trap set on EXIT within the function is
executed. The value of a function is the value of the last
command executed. A function is also executed in the
current shell process. If a command name is not a special
command or a user-defined function, a process is created and
an attempt is made to execute the command via exec.
The PATH shell parameter defines the search path for the
directory containing the command. Alternative directory
names are separated by a : (colon). The default path is
:/usr/bin: (specifying /usr/bin, and the current directory
in that order). The current directory can be specified by
two or more adjacent colons, or by a colon at the beginning
or end of the path list. If the command name contains a /
(slash), then the search path is not used. Otherwise, each
directory in the path is searched for an executable file.
If the file has execute permission but is not a directory or
an a.out file, it is assumed to be a file containing shell
commands. A subshell is spawned to read it. All nonex-
ported aliases, functions, and named parameters are removed
in this case. If the shell command file does not have read
permission, or if the setuid and/or setgid bits are set on
the file, the shell executes an agent whose job it is to set
up the permissions and execute the shell with the shell com-
mand file passed down as an open file. A command in
parentheses is executed in a subshell without removing
nonexported quantities.
Command Reentry
The text of the last HISTSIZE (default 128) commands entered
from a terminal device is saved in a history file. The
$HOME/.sh_history file is used if the HISTFILE variable is
not set or is not writable. A shell can access the commands
of all interactive shells that use the same named HISTFILE.
The fc special command is used to list or edit a portion of
this file. The portion of the file to be edited or listed
can be selected by number or by giving the first character
or characters of the command. A single command or range of
commands can be specified. If you do not specify an editor
program as an argument to fc, then the value of the FCEDIT
parameter is used. If FCEDIT is not defined, then
/usr/bin/ed is used. The edited commands are printed and
reexecuted upon leaving the editor. The editor name -
(dash) is used to skip the editing phase and to reexecute
the command. In this case, a substitution parameter of the
form old=new can be used to modify the command before execu-
tion. For example, if r is aliased to 'fc -e -', then typ-
ing `r bad=good c' reexecutes the most recent command, which
starts with the letter c, replacing the first occurrence of
the string bad with the string good.
Inline Editing Options
Normally, each command line entered from a terminal device
is simply typed followed by a newline (<Return> or
linefeed). If the emacs, gmacs, or vi option is active, you
can edit the command line. To be in any of these edit
modes, set the corresponding option. An editing option is
automatically selected each time the VISUAL or EDITOR vari-
able is assigned a value ending in either of these option
names.
The editing features require that the terminal accept
<Return> as carriage-return without linefeed and that a
space must overwrite the current character on the screen.
ADM terminal users should set the space-advance switch to
Space. Hewlett-Packard series 2621 terminal users should
set the straps to bcGHxZ etX.
The editing modes create the impression that the user is
looking through a window at the current line. The window
width is the value of COLUMNS if it is defined, otherwise it
is 80 bytes. If the line is longer than the window width
minus 2, a mark is displayed at the end of the window to
notify the user. As the cursor moves and reaches the window
boundaries, the window will be centered about the cursor.
The mark is a > (right angle bracket) if the line extends on
the right side of the window, a < (left angle bracket) if
the line extends on the left side of the window, and an *
(asterisk) if the line extends on both sides of the window.
The search commands in each edit mode provide access to the
history file. Only strings are matched, not patterns,
although if the leading character in the string is a ^ (cir-
cumflex), the match is restricted to begin at the first
character in the line.
The emacs Editing Mode
This mode is entered by enabling either the emacs or gmacs
option. The only difference between these two modes is the
way they handle <Ctrl-t>. To edit, the user moves the cur-
sor to the point needing correction and then inserts or
deletes characters or words as needed. All the editing com-
mands are control characters or escape sequences. The nota-
tion for control characters is ^ (circumflex) followed by
the character. For example, ^F is the notation for <Ctrl-
f>. This is entered by pressing f while holding down
<Ctrl>. <Shift> is not depressed. (The notation ^? indi-
cates <Delete>.)
The notation for escape sequences is M- followed by a char-
acter. For example, M-f (pronounced Meta f) is entered by
pressing <Esc> (ASCII 033) followed by f. (M-F would be the
notation for <Esc> followed by <Shift> (capital) F.)
All edit commands operate from any place on the line (not
just at the beginning). Do not press <Return> or linefeed
after edit commands except when noted.
<Ctrl-f>
Moves the cursor forward (right) one character.
<Esc-f>
Moves the cursor forward one word. (The emacs editor's
definition of a word is a string of characters, consist-
ing of only letters, digits, and underscores, and delim-
ited with spaces or tabs.)
<Ctrl-b>
Moves the cursor backward (left) one character.
<Esc-b>
Moves the cursor backward one word.
<Ctrl-a>
Moves the cursor to the start of the line.
<Ctrl-e>
Moves the cursor to the end of the line.
<Ctrl-]> character
Moves the cursor forward on the current line to the
character indicated by the character argument.
<Esc-Ctrl-]> character
Moves the cursor backward on the current line to the
character indicated by the character argument.
<Ctrl-x Ctrl-x>
Interchanges the cursor and mark.
Erase
Deletes the previous character. (User-defined Erase
character as defined by the stty command, often <Ctrl-h>
or #.)
<Ctrl-d>
Deletes the current character.
<Esc-d>
Deletes the current word.
<Esc-Backspace>
Deletes the previous word.
<Esc-h>
Deletes the previous word.
<Esc-Delete>
Deletes the previous word (if your Interrupt character
is <Delete>, this command does not work).
<Ctrl-t>
Transposes the current character with next character in
emacs mode. Transposes two previous characters in gmacs
mode.
<Ctrl-c>
Capitalizes the current character.
<Esc-c>
Capitalizes the current word.
<Esc-l>
Changes the current word to lowercase.
<Ctrl-k>
Deletes from the cursor to the end of the line. If pre-
ceded by a numerical parameter whose value is less than
the current cursor position, deletes from given position
up to the cursor. If preceded by a numerical parameter
whose value is greater than the current cursor position,
deletes from the cursor up to given cursor position.
<Ctrl-w>
Deletes from the cursor to the mark.
<Esc-p>
Pushes the region from the cursor to the mark on the
stack.
Kill
Kills the entire current line. If two Kill characters
are entered in succession, all Kill characters from then
on cause a linefeed (useful when using paper terminals).
(User-defined Kill character as defined by the stty com-
mand, often <Ctrl-g> or @.)
<Ctrl-y>
Restores the last item removed from the line. (Yanks
the item back to the line.)
<Ctrl-l>
Performs a linefeed and prints the current line.
<Ctrl-@>
(Null character.) Sets the mark.
<Esc space>
Sets the mark.
<Ctrl-j>
Executes the current line (newline).
<Ctrl-m>
Executes the current line (enter).
EOF The End-of-File character is processed as an End-of-File
only if the current line is null.
<Ctrl-p>
Fetches the previous command. Each time <Ctrl-p> is
entered, the previous command back in time is accessed.
Moves back one line when not on the first line of a mul-
tiline command.
<Esc-<>
Fetches the least recent (oldest) history line.
<Esc->>
Fetches the most recent (youngest) history line.
<Ctrl-n>
Fetches the next command line. Each time <Ctrl-n> is
entered, the next command line forward in time is
accessed.
<Ctrl-r> string
Reverses the search history for a previous command line
containing string. If an argument of 0 (zero) is given,
the search is forward. string is terminated by an
<Return> or newline character. If string is preceded by
a ^ (circumflex), the matched line must begin with
string. If string is omitted, then the next command
line containing the most recent string is accessed. In
this case, an argument of 0 (zero) reverses the direc-
tion of the search.
<Ctrl-o>
Executes the current line and fetches the next line
relative to current line from the history file.
(Operate)
<Esc> digits
Defines the numeric parameter (escape). The digits are
taken as an argument to the next command. The commands
that accept a parameter are <Ctrl-f>, <Ctrl-b>, <Erase>,
<Ctrl-c>, <Ctrl-d>, <Ctrl-k>, <Ctrl-r>, <Ctrl-p>,
<Ctrl-n>, <Ctrl-]>, <Esc-.>, <Esc-Ctrl-]>, <Esc-_>,
<Esc-b>, <Esc-c>, <Esc-d>, <Esc-f>, <Esc-h>, <Esc-l> and
<Esc-Ctrl-h>.
<Esc> letter
Your alias list is searched for an alias by the name
_letter and if an alias of this name is defined, its
value is inserted on the input queue. letter must not
be one of the preceding metafunctions. (Soft-key)
<Esc-]> letter
Your alias list is searched for an alias by the name
_letter and if an alias of this name is defined, its
value is inserted on the input queue (Soft-key). This
can be used to program functions keys on many systems.
<Esc-.>
The last word of the previous command is inserted on the
line. If preceded by a numeric parameter, the value of
this parameter determines which word to insert, rather
than the last word.
<Esc-_>
Same as the <Esc-.> combination.
<Esc-*>
Attempts filename generation on the current word. An *
(asterisk) is appended if the word does not match any
file or contain any special pattern characters.
<Esc-Esc>
Filename completion. Replaces the current word with the
longest common prefix of all filenames matching the
current word with an asterisk appended. If the match is
unique, a / (slash) is appended if the file is a direc-
tory, and a space is appended if the file is not a
directory.
<Esc-=>
Lists the files matching current word pattern if an *
(asterisk) were appended.
<Ctrl-u>
Multiplies the argument of the next command by 4.
\ Escapes the next character. Editing characters, the
user's Erase, Kill, and Interrupt (normally by using
<Delete>) characters can be entered in a command line or
in a search string if preceded by a \ (backslash). The
backslash removes the next character's editing features
(if any).
<Ctrl-v>
Displays the version of the shell.
<Esc-#>
Inserts a # (number sign) at the beginning of the line
and executes it. This causes a comment to be inserted
in the history file.
The vi Editing Mode
There are two typing modes. Initially, when you enter a
command you are in the input mode. To edit, the user enters
control mode by typing <Esc> (ASCII 033) and moves the cur-
sor to the place needing correction and then inserts or
deletes characters or words as needed. Most control com-
mands accept an optional repeat count prior to the command.
When in vi mode on most systems, canonical processing is
initially enabled and the command are echoed again if the
speed is 1200 baud or greater, if it contains any control
characters, or if less than 1 second has elapsed since the
prompt was printed. The Escape character terminates canoni-
cal processing for the remainder of the command and the user
can then modify the command line.
This scheme has the advantages of canonical processing with
the type-ahead echoing of raw mode. If the option viraw is
also set, the terminal always has canonical processing dis-
abled. This mode is implicit for systems that do not sup-
port two alternate End-of-Line delimiters, and can be help-
ful for certain terminals.
Input Edit Commands
By default the editor is in input mode.
Erase
(User-defined Erase character as defined by the stty
command, often <Ctrl-h> or #.) Deletes the previous
character.
<Ctrl-w>
Deletes the previous space-separated word.
<Ctrl-d>
Terminates the shell.
<Ctrl-v>
Escapes the next character. Editing characters and the
user's Erase or Kill characters can be entered in a com-
mand line or in a search string if preceded by a <Ctrl-
v>. <Ctrl-v> removes the next character's editing
features (if any).
\ Escapes the next Erase or Kill character.
Motion Edit Commands
These commands move the cursor:
[count]l
Cursor forward (right) one character.
[count]w
Cursor forward one word. A word is a string of charac-
ters delimited by spaces or tabs.
[count]W
Cursor to the beginning of the next word that follows a
space.
[count]e
Cursor to the end of the word.
[count]E
Cursor to end of the current space-delimited word.
[count]h
Cursor backward (left) one character.
[count]b
Cursor backward one word.
[count]B
Cursor to the preceding space-delimited word.
[count]|
Cursor to the column count.
[count]fc
Finds the next character c in the current line.
[count]Fc
Finds the previous character c in the current line.
[count]tc
Equivalent to f followed by h.
[count]Tc
Equivalent to F followed by l.
[count];
Repeats count times, the last single character find com-
mand: f, F, t, or T.
[count],
Reverses the last single character find command count
times.
0 Cursor to the start of the line.
^ Cursor to the first nonspace character in the line.
$ Cursor to the end of the line.
Search Edit Commands
These commands access your command history.
[count]k
Fetches the previous command. Each time k is entered,
the previous command back in time is accessed.
[count]-
Equivalent to k.
[count]j
Fetches the next command. Each time j is entered, the
next command forward in time is accessed.
[count]+
Equivalent to j.
[count]G
Fetches the command number count. The default is the
least recent history command.
/string
Searches backward through history for a previous command
containing the specified string. string is terminated
by <Return> or a newline character. If the specified
string is preceded by a ^ (circumflex), the matched line
must begin with string. If string is null, the previous
string is used.
?string
Same as / (slash) except that the search is in the for-
ward direction.
n Searches for next match of the last pattern to the / or
? commands.
N Searches for next match of the last pattern to the / or
? commands, but in reverse direction. Searches the com-
mand history for the string entered by the previous /
command.
Text Modification Edit Commands
These commands modify the line.
a Enters input mode and enters text after the current
character.
A Appends text to the end of the line. Equivalent to $a.
[count]cmotion
c[count]motion
Deletes the current character through the character to
which motion would move the cursor, and enters input
mode. If motion is c, the entire line is deleted and
input mode is entered.
C Deletes the current character through the end of line,
and enters input mode. Equivalent to c$.
S Equivalent to cc.
D Deletes the current character through the end of line.
Equivalent to d$.
[count]dmotion
d[count]motion
Deletes the current character through the character to
which motion would move. If motion is d, the entire
line is deleted.
i Enters input mode and inserts text before the current
character.
I Inserts text before the beginning of the line.
Equivalent to 0i.
[count]P
Places the previous text modification before the cursor.
[count]p
Places the previous text modification after the cursor.
R Enters input mode and replaces characters on the screen
with the characters you type, overlay fashion.
[count]rc
Replaces the count characters, starting at the current
cursor position with c and advancing the cursor.
[count]x
Deletes the current character.
[count]X
Deletes the preceding character.
[count].
Repeats the previous text modification command.
[count]~
Inverts the case of the count characters, starting at
the current cursor position and advancing the cursor.
[count]_
Causes the count word of the previous command to be
appended and input mode entered. The last word is used
if count is omitted.
* Causes an * (asterisk) to be appended to the current
word and filename generation to be attempted. If no
match is found, it rings the bell. Otherwise, the word
is replaced by the matching pattern and input mode is
entered.
\ Filename completion. Replaces the current word with the
longest common prefix of all filenames matching the
current word with an * (asterisk) appended. If the
match is unique, a / (slash) is appended if the file is
a directory; a space is appended if the file is not a
directory.
Miscellaneous vi Commands
[count]ymotion
y[count]motion
Yanks the current character through the character to
which motion would move the cursor and puts the charac-
ters into the delete buffer. The text and cursor are
unchanged.
Y Yanks from current position to the end of line.
Equivalent to y$.
u Undoes the last text-modifying command.
U Undoes all the text-modifying commands performed on the
line.
[count]v
Returns the command fc -e ${VISUAL:-${EDITOR:-vi}} count
in the input buffer. If count is omitted, the current
line is used.
<Ctrl-l>
Performs a linefeed and prints the current line. Effec-
tive only in control mode.
<Ctrl-j>
Executes the current line, regardless of mode (newline).
<Ctrl-m>
Executes the current line, regardless of mode (enter).
# Sends the line after inserting a # (number sign) in
front of the line. Useful for causing the current line
to be inserted in the history without being executed.
= Lists the filenames that match the current word if an *
(asterisk) is appended to it.
@letter
Searches the alias list for an alias by the name _letter
. If an alias of this name is defined, its value is
inserted in the input queue for processing.
Special ksh Commands
The following simple commands are executed in the shell pro-
cess. Input/output redirection is permitted. Unless other-
wise indicated, the output is written on file descriptor 1
and the exit status, when there is no syntax error, is 0
(zero).
Commands that are indicated as command1 or command2 are
treated specially in the following ways:
o Parameter assignment lists that precede the command
remain in effect when the command completes.
o I/O redirections are processed after parameter assign-
ments.
o Errors cause a script that contains the commands so
marked to abort.
o Words, following a command specified as command2 that
are in the format of a parameter assignment, are
expanded with the same rules as a parameter assignment.
This means that ~ (tilde) substitution is performed
after the = (equal sign). Word splitting and filename
generation are not performed.
:[argument ...]1
The command only expands arguments.
.file [argument ...]1
Reads the complete file and executes the commands. The
commands are executed in the current shell environment.
The search path specified by PATH is used to find the
directory containing file. If any arguments are speci-
fied, they become the positional parameters. Otherwise,
the positional parameters are unchanged. The exit
status is the exit status of the last command executed.
alias [-tx] [name[=value ...]]2
The alias command with no arguments prints the list of
aliases in the form name=value on standard output. An
alias is defined for each name whose value is given. A
trailing space in value causes the next word to be
checked for alias substitution. The -t flag is used to
set and list tracked aliases. The value of a tracked
alias is the full pathname corresponding to the given
name. The value becomes undefined when the value of
PATH is reset but the aliases remained tracked. Without
the -t flag, for each name in the argument list for
which no value is given, the name and value of the alias
is printed. The -x flag is used to set or print
exported aliases. An exported alias is defined for
scripts invoked by name. The exit status is nonzero if
a name is given without a value, and no alias was
defined.
bg [job ...]
Puts each specified job into the background. The
current job is put into the background if job is not
specified. (See Jobs for a description of the format of
job.)
break [n]1
Exits from the enclosing for, while, until, or select
loop, if any. If n is specified, breaks n levels.
continue [n]1
Resumes the next iteration of the enclosing for, while,
until, or select loop. If n is specified, resumes at
the nth enclosing loop.
cd [argument]
cd old new
This command can be in either of two forms. In the
first form, it changes the current directory to argu-
ment. If argument is a - (dash), the directory is
changed to the previous directory. The HOME shell
parameter is the default argument. The PWD parameter is
set to the current directory. The CDPATH shell parame-
ter defines the search path for the directory containing
argument. Alternative directory names are separated by
a : (colon). The default path is a null string, speci-
fying the current directory. Note that the current
directory is specified by a null pathname, which can
appear immediately after the = (equal sign) or between
the colon delimiters anywhere else in the path list.
If argument begins with a / (slash), the search path is
not used. Otherwise, each directory in the path is
searched for argument. The second form of cd substi-
tutes the string new for the string old in the current
directory name PWD and tries to change to this new
directory. The cd command cannot be executed by rsh.
echo [argument ...]
Writes arguments to standard output. See echo for a
discussion of its usage and arguments.
eval [argument ...]1
The arguments are read as input to the shell and the
resulting commands are executed.
exec [argument ...]1
If argument is given, the command specified by the argu-
ments is executed in place of this shell without creat-
ing a new process. Input/output arguments can appear
and affect the current process. If no arguments are
given, the effect of this command is to modify file
descriptors as prescribed by the input/output redirec-
tion list. In this case, any file descriptor numbers
greater than 2 that are opened with this mechanism are
closed when invoking another program.
exit [n]1
Causes the shell to exit with the exit status specified
by n. If n is omitted, the exit status is that of the
last command executed. An End-of-File also causes the
shell to exit, except for a shell which has the
ignoreeof option (see set) turned on.
export [name[=value ...]]2
The given names are marked for automatic export to the
environment of subsequently executed commands.
fc [-e editor] [-nlr] [first [last]]
fc -e - [old=new] [command]
In the first form, a range of commands from first to
last is selected from the last HISTSIZE commands that
were entered at the terminal. The arguments first and
last can be specified as a number or as a string. A
string is used to locate the most recent command, start-
ing with the given string. A negative number is used as
an offset to the current command number. If the -l flag
is selected, the commands are listed on standard output.
Otherwise, the editor program editor is invoked on a
file containing these keyboard commands.
If editor is not supplied, the value of the parameter
FCEDIT (default /usr/bin/ed) is used as the editor.
When editing is complete, the edited commands are exe-
cuted. If last is not specified, then it will be set to
first. If first is not specified, the default is the
previous command for editing and -16 for listing. The
-r flag reverses the order of the commands and the -n
flag suppresses command numbers when listing. In the
second form, the command is reexecuted after the substi-
tution old=new is performed.
fg [job ...]
Each job specified is brought to the foreground. Other-
wise, the current job is brought into the foreground.
(See Jobs for a description of the format of job.)
getopts optstring name [argument ...]
Checks argument for legal options. If argument is omit-
ted, the positional parameters are used. An option
argument begins with a + (plus sign) or a - (dash). An
option not beginning with + or - or the argument -- ends
the options. optstring contains the letters that
getopts recognizes. If a letter is followed by a :
(colon), that option is expected to have an argument.
The options can be separated from the argument by
spaces. getopts places the next option letter it finds
inside variable name each time it is invoked with a +
prepended when argument begins with a +. The index of
the next argument is stored in OPTIND.
The option argument, if any, gets stored in OPTARG. A
leading : in optstring causes getopts to store the
letter of an invalid option in OPTARG, and to set name
to a ? (question mark) for an unknown option and to :
when a required option is missing. Otherwise, getopts
prints an error message. The exit status is nonzero
when there are no more options.
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.
jobs [-lnp] [job ...]
Lists information about each given job; or all active
jobs if job is omitted. The -l flag lists process IDs
in addition to the normal information. The -n flag only
displays jobs that have stopped or exited since last
notified. The -p flag causes only the process group to
be listed. (See Jobs for a description of the format of
job.)
kill [-signal] job ...
kill -l
Sends either the TERM signal or the specified signal to
the specified jobs or processes. Signals are either
given by number or by names (as given in
/usr/include/signal.h, stripped of the prefix SIG). If
the signal being sent is TERM (terminate) or HUP
(hangup), the job or process is sent a CONT (continue)
signal if it is stopped. The argument job can be the
process ID of a process that is not a member of one of
the active jobs. (See Jobs for a description of the
format of job.) In the second form, kill -l, the signal
numbers and names are listed.
let argument ...
Each argument is a separate arithmetic expression to be
evaluated. (See Arithmetic Evaluation for a description
of arithmetic expression evaluation.) The exit status
is 0 (zero) if the value of the last expression is
nonzero, and 1 otherwise.
newgrp [-] [group]
Changes the primary group identification of the current
shell process to group. If you specify a - (dash),
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 recognizes group names only; it does not recog-
nize 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.
print [-Rnprsu[n]] [argument ...]
The shell output mechanism. With no flags or with flag
- or --, the arguments are printed on standard output as
described by echo. In raw mode, -R or -r, the escape
conventions of echo are ignored. The -R option prints
all subsequent arguments and options other than -n.
The -p option causes the arguments to be written onto
the pipe of the process spawned with |& instead of
standard output. The -s option causes the arguments to
be written onto the history file instead of standard
output. The -u flag can be used to specify a 1-digit
file descriptor unit number n on which the output will
be placed. The default is 1. If the -n flag is used,
no newline is added to the output.
pwd Equivalent to print -r - $PWD.
read [-prsu[n]] [name?prompt] [name ...]
The shell input mechanism. One line is read and is bro-
ken up into fields using the characters in IFS as
separators. In raw mode, a \ (backslash) at the end of
a line does not signify line continuation. The first
field is assigned to the first name, the second field to
the second name, and so on, with leftover fields
assigned to the last name. The -p flag causes the input
line to be taken from the input pipe of a process
spawned by the shell using |&. If the -s flag is
present, the input will be saved as a command in the
history file. The -u flag can be used to specify a 1-
digit file descriptor unit to read from. The file
descriptor can be opened with the exec special command.
The default value of n is 0 (zero). If name is omitted,
REPLY is used as the default name. The exit status is 0
(zero) unless an End-of-File is encountered. An End-
of-File with the -p flag causes cleanup for this process
so that another can be spawned. If the first argument
contains a ? (question mark), the remainder of this word
is used as a prompt on standard error when the shell is
interactive. The exit status is 0 (zero) unless an
End-of-File is encountered.
readonly [name[=value ...]]2
The given names are marked read-only. These names can-
not be changed by subsequent assignment.
return [n]1
Causes a shell function to return to the invoking script
with the return status specified by n. If n is omitted,
the return status is that of the last command executed.
If return is invoked while not in a function or a .
(dot) script, it is the same as an exit.
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.
[argument ...]
set [+ | -aefhkmnopstuvx] [+ | -o option ...] [+ | -A name]
Preceding a flag with + sets the parameter, and preced-
ing the flag with - unsets the parameters. The flags
for the set command have the following meanings:
A name
Array assignment. Unset the variable name and
assign values sequentially from the list argument.
If +A is used, the variable name is not unset first.
a All subsequent parameters that are defined are
automatically exported.
e If a command has a nonzero exit status, executes the
ERR trap, if set, and exits. This mode is disabled
while reading profiles.
f Disables filename generation.
h Each command becomes a tracked alias when first
encountered.
k All parameter assignment arguments are placed in the
environment for a command, not just those that pre-
cede the command name.
m Background jobs will run in a separate process group
and a line will print upon completion. The exit
status of background jobs is reported in a comple-
tion message. On systems with job control, this
flag is turned on automatically for interactive
shells.
n Reads commands and checks them for syntax errors,
but does not execute them. Ignored for interactive
shells.
o The argument can be one of the following option
names:
allexport
Same as a.
errexit
Same as e.
bgnice
Runs all background jobs at a lower priority.
This is the default mode.
emacs
Invokes an emacs style inline editor for command
entry.
gmacs
Invokes a gmacs-style inline editor for command
entry.
ignoreeof
The shell does not exit on End-of-File. The
exit command must be used.
keyword
Same as k.
markdirs
All directory names resulting from filename gen-
eration have a trailing / (slash) appended.
monitor
Same as m.
noclobber
Prevents redirection > from truncating existing
files. Requires >| to truncate a file when
turned on.
noexec
Same as n.
noglob
Same as f.
nolog
Does not save function definitions in history
file.
nounset
Same as u.
privileged
Same as p.
verbose
Same as v.
trackall
Same as h.
vi Invokes, in insert mode, a vi-style inline edi-
tor until you press Escape (ASCII 033). This
changes to move mode. A return sends the line.
viraw
Each character is processed as it is entered in
vi mode.
xtrace
Same as x.
If no option name is supplied, then the current
option settings are printed.
p Disables processing of the $HOME/.profile file and
uses the /etc/suid_profile file instead of the ENV
file. This mode is on whenever the effective user
ID or group ID is not equal to the real user ID or
group ID. Turning this off causes the effective
user ID and group ID to be set to the real user ID
and group ID.
s Sorts the positional parameters.
t Exits after reading and executing one command.
u Treats unset parameters as an error when substitut-
ing.
v Prints shell input lines as they are read.
x Prints commands and their arguments as they are exe-
cuted.
- Unsets x and v flags and stops examining arguments
for flags.
-- Does not change any of the flags; useful in setting
$1 to a value beginning with -. If no arguments
follow this flag, the positional parameters are
unset.
These flags can also be used upon invocation of the
shell. The current set of flags can be found in $-.
Unless -A is specified, the remaining arguments are
positional parameters and are assigned, in order, to
$1 $2 .... If no arguments are given, the names and
values of all named parameters are printed on the
standard output. If the only argument is +, the
names of all named parameters are printed.
shift [n]1
The positional parameters from $n+1 ... are renamed $1
... , default n is 1. The argument n can be any
arithmetic expression that evaluates to a nonnegative
number less than or equal to $#.
times1
Prints the accumulated user and system times for the
shell and for processes run from the shell.
trap [argument] [signal ...]1
The argument variable specifies a command to be read and
executed when the shell receives the specified signals.
(Note that argument is scanned once when the trap is set
and once when the trap is taken.) Each signal can be
given as a number or as the name of the signal. Trap
commands 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 argument is omitted or is -, all traps signal are
reset to their original values. If argument is the null
string, this signal is ignored by the shell and by the
commands it invokes. If signal is ERR, argument is exe-
cuted whenever a command has a nonzero exit status. If
signal is DEBUG, argument is executed after each com-
mand. If signal is 0 or EXIT and the trap statement is
executed inside the body of a function, the command
argument is executed after the function completes. If
signal is 0 (zero) or EXIT for a trap set outside any
function, the command argument is executed on exit from
the shell. The trap command with no arguments prints a
list of commands associated with each signal number.
typeset [+ | -HLRZfilrtux[n]] [name[=value ...]]2
Sets attributes and values for shell parameters. When
invoked inside a function, a new instance of the parame-
ter name is created. The parameter value and type are
restored when the function completes. The following
list of attributes can be specified:
-f The names refer to function names rather than param-
eter names. No assignments can be made and the only
other valid flags are -t, -u, and -x. The -t flag
turns on execution tracing for this function. The
-u flag causes this function to be marked undefined.
The FPATH variable is searched to find the function
definition when the function is referenced. The -x
flags allows the function definition to remain in
effect across shell procedures invoked by name.
-H Provides OSF/1 system-to-hostname file mapping on
machines that restrict the set of characters in
filenames.
-i Parameter is an integer. This makes arithmetic fas-
ter. If n is nonzero, it defines the output arith-
metic base; otherwise, the first assignment deter-
mines the output base.
-l All uppercase characters are converted to lowercase.
The uppercase -u flag is turned off.
-L Left justifies and removes leading spaces from
value. If n is nonzero, it defines the width of the
field; otherwise, it is determined by the width of
the value of first assignment. When the parameter
is assigned, it is filled on the right with spaces
or truncated, if necessary, to fit into the field.
Leading zeros are removed if the -Z flag is also
set. The -R flag is turned off.
-r The given names are marked read-only and these names
cannot be changed by subsequent assignment.
-R Right justifies and fills with leading spaces. If n
is nonzero, it defines the width of the field; oth-
erwise, it is determined by the width of the value
of first assignment. The field is left-filled with
spaces or truncated from the end if the parameter is
reassigned. The L flag is turned off.
-t Tags the named parameters. Tags are user definable
and have no special meaning to the shell.
-u All lowercase characters are converted to uppercase
characters. The lowercase -l flag is turned off.
-x The given names are marked for export.
-Z Right justifies and fills with leading zeros if the
first nonspace character is a digit and the -L flag
was not set. If n is nonzero, it defines the width
of the field; otherwise, it is determined by the
width of the value of first assignment.
Using + (plus sign) rather than - (dash) causes these
flags to be turned off. If no name arguments are given
but flags are specified, a list of names (and optionally
the values) of the parameters that have these flags set
is printed. (Using + rather than - keeps the values
from being printed.) If no names and flags are given,
the names and attributes of all parameters are printed.
ulimit [-HSacdfmnpstvw] [limit]
Sets or displays a resource limit. Available resources
limits follow. Many systems do not contain one or more
of these limits. The limit for a specified resource is
set when limit is specified. The value of limit can be
a number in the unit specified with each resource, or
the value unlimited.
The H and S flags specify whether the hard limit or the
soft limit for the given resource is set. A hard limit
cannot be increased once it is set. A soft limit can be
increased up to the value of the hard limit. If neither
H nor S is specified, the limit applies to both. The
current resource limit is printed when limit is omitted.
In this case, the soft limit is printed unless H is
specified. When more than one resource is specifed, the
limit name and unit are printed before the value.
-a Lists all of the current resource limits.
-c The number of 512-byte blocks on the size of core
dumps.
-d The number of Kilobytes on the size of the data
area.
-f The number of 512-byte blocks on files written by
child processes (files of any size can be read).
-m The number of Kilobytes on the size of physical
memory.
-n The number of file descriptors.
-p The number of 512-byte blocks for pipe buffering.
-s The number of Kilobytes on the size of the stack
area.
-t The number of seconds to be used by each process.
-v The number of Kilobytes for virtual memory.
-w The number of Kilobytes for the swap area.
If no option is given, -f is assumed.
umask [mask]
The user file-creation mask is set to mask (See umask.)
mask can either be an octal number or a symbolic value,
as described in chmod. If a symbolic value is given,
the new umask value is the complement of the result of
applying mask to the complement of the previous umask
value. If mask is omitted, the current value of the
mask is printed.
unalias name ...
The parameters given by the list of names are removed
from the alias list.
unset [-f] name ...
The parameters given by the list of names are unas-
signed, that is, their values and attributes are erased.
Read-only variables cannot be unset. If the -f flag is
set, the names refer to function names. Unsetting
ERRNO, LINENO, MAILCHECK, OPTARG, OPTIND, RANDOM,
SECONDS, TMOUT, and _ removes their special meaning even
if they are subsequently assigned.
{wait [job]
Waits for the specified job and reports its termination
status. If job is not given, all currently active child
processes are waited for. The exit status from this
command is that of the process waited for. (See Jobs
for a description of the format of job.)
whence [-pv] name ...
For each name, indicates how it would be interpreted if
used as a command name. The -v flag produces a more
verbose report. The -p flag does a path search for name
even if name is an alias, a function, or a reserved
word.
Invocation
If the shell is invoked by exec, and the first character of
argument zero ($0) is - (dash), the shell is assumed to be a
login shell and commands are read from /etc/profile and then
from either .profile in the current directory or
$HOME/.profile, if either file exists. Next, commands are
read from the file named by performing parameter substitu-
tion on the value of the ENV environment variable, if the
file exists. If the -s flag is not present and argument is
present, a path search is performed on the first argument to
determine the name of the script to execute. The script
argument must have read permission and any setuid and getgid
settings are ignored. Commands are then read, as described
in the following text.
See the FLAGS section for a complete description of flags
that can be interpreted by the shell when it is invoked.
FILES
/etc/profile
System profile.
$HOME/.profile
User profile.
/etc/passwd
Contains user information.
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.
4. If a command that is a tracked alias is executed, and
then 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 continues to
exec the original command. Use the -t flag of the
alias command to correct this situation.
5. Using the fc built-in command within a compound command
causes the whole command to disappear from the history
file.
6. The built-in .file command reads the whole file before
any commands are executed. Therefore, the alias and
unalias commands in the file do not apply to any func-
tions defined in the file.
7. Traps are not processed while a job is waiting for a
foreground process. Thus, a trap on CHLD is not exe-
cuted until the foreground job terminates.
EXIT VALUES
Errors detected by the shell, such as syntax errors, cause
the shell to return a nonzero exit status. Otherwise, the
shell returns the exit status of the last command executed.
(See also the exit command, described previously.) If the
shell is being used noninteractively, execution of the shell
file is abandoned. Run-time errors detected by the shell
are reported by printing the command or function name and
the error condition. If the line number that the error
occurred on is greater than 1, the line number is also
printed in [ ] (brackets) after the command or function
name.
RELATED INFORMATION
Commands: cat(1), cd(1), chmod(1), csh(1), echo(1),
env(1)/printenv(1), sh(1), stty(1), test(1), umask(1),
vi(1)/vedit(1)/view(1).
Functions: exec(2), fcntl(2), fork(2), ioctl(2),
ldr_install(2), ldr_remove(2), lseek(2), pipe(2), rand(3),
sigaction(2), umask(2), ulimit(3), wait(2).
Files: osf_rose(4), null(7).
The environ variable.
The OSF/1 User's Guide, which discusses the OSF/1 shells and
some useful shell functions.
"Using Internationalization Features" in the OSF/1 User's
Guide.
Acknowledgement and Disclaimer