ksh(1) ksh(1)
NAME
ksh, rksh, alias, bg, break, continue, fc, fg, jobs, let, print,
return, typeset, unalias, whence - Korn shell
SYNOPSIS
ksh [option ...] [file] [argument ...]
DESCRIPTION
This command description is divided into the following sections:
⊕ Major Korn shell features not available in the Bourne shell
⊕ Call options
⊕ Prompting
⊕ Definitions
⊕ Commands
⊕ Reserved words
⊕ Compound commands
⊕ Comments
⊕ Aliasing
⊕ Tilde substitution
⊕ Command substitution
⊕ Korn shell variables and parameter substitution
⊕ Blank interpretation
⊕ File name generation
⊕ Quoting metacharacters
⊕ Arithmetic evaluation
⊕ Conditional expressions
⊕ File attributes
⊕ String attributes and comparisons
⊕ Algebraic comparisons between integers
⊕ Negated and compound expressions
Page 1 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
⊕ I/O redirection
⊕ Environment
⊕ Functions
⊕ Jobs
⊕ Signals
⊕ Execution
⊕ Command re-entry
⊕ In-line editing options
⊕ emacs editing mode
⊕ vi editing mode
⊕ Input edit commands
⊕ Motion edit commands
⊕ Search edit commands
⊕ Text modification edit commands
⊕ Other edit commands
⊕ Built-in commands
The Korn shell ksh is a programmable command interpreter that inter-
prets and executes commands read from a terminal or a file.
rksh is a restricted version of the command interpreter ksh; it is
used to set up login names and execution environments whose capabili-
ties are more controlled than those of the standard shell. See OPTIONS
below for the meaning of arguments to the shell.
Like the standard shell sh(1) and the C shell csh(1), the Korn shell
ksh is a user interface to the operating system kernel. The Korn shell
is an extension of the standard Bourne shell and is essentially compa-
tible with the Bourne shell in terms of syntax and semantics. Bourne
shell scripts can therefore also be run in the Korn shell. The func-
tionality of the C shell is as powerful as that of the Korn shell, but
the C shell is more closely matched to the syntax of the C language. An
overview of the enhanced functionality of the Korn shell is provided
below for experienced users of the Bourne shell. Users who are not so
familiar with the Bourne shell will find more detailed explanations in
this manual under the general description of the Bourne shell sh and
under the individual descriptions of the Bourne shell built-ins.
Page 2 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
Major Korn shell features not available in the Bourne shell
- Two-way pipelines (|&) between commands
- Interactive selection from a word list with the select command
- The time statement
- Command name aliasing
- Tilde substitution for file names
- Extended command substitution syntax supporting arithmetic expres-
sions
- The built-in typeset command can be used to set attributes for
parameters to define their format, data type, etc.
- Support for one-dimensional arrays
- There are more automatically set parameters and more variables in
the Korn shell.
- The file name generation mechanism also supports pattern lists.
Patterns can be used to generate a single file name in I/O redirec-
tions.
- The built-in let command is available for integer arithmetic.
- Conditional expressions with similar functionality to the test com-
mand are provided as built-in statements.
- Functions can have local variables, are "exportable", and can be
located via a search path.
- Job control can be activated with the monitor option of the built-
in set command. You can thus access processes as easily as with the
jsh(1) shell (Bourne shell with job control).
- When the command line is processed, built-in commands are located
before functions.
- Positional parameters are saved before function calls and then
restored.
- Command re-entry: commands issued to an interactive Korn shell are
saved in a history file, which can be accessed using the built-in
fc command. Simple text substitution can be performed on the com-
mand line before it is executed. There is also an option for edit-
ing command lines (in emacs or vi mode) from the history file
before executing them.
Page 3 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
- When the shell is invoked as a login shell, the file named by the
value of the environment variable ENV can be called after
$HOME/.profile.
- Some of the built-in commands have extra functionality; others are
replaced by new commands or are not implemented.
Enhanced commands
___________________________________________________________________
| Command | Extra features |
|__________|_______________________________________________________|
| . | Arguments |
|__________|_______________________________________________________|
| : | Arguments |
|__________|_______________________________________________________|
| cd | Substitution |
|__________|_______________________________________________________|
| export | Value assignment |
|__________|_______________________________________________________|
| getopts | Shell variables |
|__________|_______________________________________________________|
| read | Two-way pipelines |
|__________|_______________________________________________________|
| readonly | Value assignment |
|__________|_______________________________________________________|
| set | Array assignments, etc. |
|__________|_______________________________________________________|
| shift | Arithmetic expressions |
|__________|_______________________________________________________|
| trap | Special signals |
|__________|_______________________________________________________|
| umask | Symbolic arguments like chmod |
|__________|_______________________________________________________|
| unset | No readonly variables |
|__________|_______________________________________________________|
| wait | Job control |
|__________|_______________________________________________________|
Page 4 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
New commands
___________________________________________________________________
| Command | Function |
|__________|_______________________________________________________|
| alias | Command aliasing |
|__________|_______________________________________________________|
| bg | Job control |
|__________|_______________________________________________________|
| fc | Access to history file |
|__________|_______________________________________________________|
| fg | Job control |
|__________|_______________________________________________________|
| jobs | Job control |
|__________|_______________________________________________________|
| kill | Job control |
|__________|_______________________________________________________|
| let | Integer arithmetic |
|__________|_______________________________________________________|
| print | Output mechanism like echo |
|__________|_______________________________________________________|
| typeset | Attributes for shell variables |
|__________|_______________________________________________________|
| unalias | Removing aliases |
|__________|_______________________________________________________|
| whence | Command classification |
|__________|_______________________________________________________|
OPTIONS
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 whose name is generated by parameter
substitution on the value of the shell variable ENV.
The following options are interpreted by ksh when it is invoked:
-c commandstring
Commands are read from commandstring.
-s If the -s option is present or if file and argument are omitted,
the Korn shell reads commands from standard input and writes its
output to standard error, and built-in ksh commands write to
standard output.
-i If the -i option is present or if standard input and output are
associated with a terminal, an interactive Korn shell is called.
In this case TERM is ignored (so that kill 0 does not kill an
interactive shell) and INTR is caught and ignored (so that wait
is interruptible). In all cases, QUIT is ignored by the shell.
-r The -r option is used to invoke a restricted Korn shell.
Page 5 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
The remaining options are described under the Korn shell built-in set.
-- If file begins with a minus sign (-), the end of the command-line
options must be marked with --.
Note: In earlier versions of the shell, a single minus sign had
the same effect that a double minus sign now has, namely to mark
the end of the list of options. While a single minus sign can
still be specified today, it does not have a recognizable effect.
file If the -s option is not present but file is, then a path search
is performed to locate the script file to be executed. The script
must have read permission. If the set-user-ID or set-group-ID bit
has been set for the script, it is ignored. Commands are then
read as described below.
argument
You can specify commands as arguments; the command name is passed
as argument zero. Commands are described further below.
If the Korn shell is invoked by the system call exec, and the
first character of argument zero is a minus sign (-), then the
shell is assumed to be a login shell.
rksh only
rksh is used to set up login names and execution environments whose
capabilities are more controlled than those of the standard shell. The
actions of rksh are identical to those of sh, except that the follow-
ing are disallowed:
- changing directory [see cd(1)],
- setting the value of SHELL, ENV, or PATH,
- specifying path or command names containing /,
- redirecting output (>, >|, <>, and >>).
The restrictions above are enforced after .profile and the ENV files
are interpreted.
When a command to be executed is found to be a shell procedure, rksh
invokes ksh to execute 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 execute permissions
in the same directory.
Page 6 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
The net effect of these rules is that the writer of the .profile has
complete control over user actions, by performing guaranteed setup
actions and leaving the user in an appropriate directory (probably not
the login directory).
The system administrator often sets up a directory of commands (i.e.,
/usr/rbin) that can be safely invoked by rksh. Some systems also pro-
vide a restricted editor red(1).
GENERAL
Prompting
When the Korn shell is used interactively, it prompts with the
expanded value of the PS1 variable before reading a command.
If at any time a newline is typed and further input is needed to com-
plete a command, then the secondary prompt is issued. The secondary
prompt is generally the value of the PS2 variable.
Definitions
A metacharacter is one of the following characters:
; & ( ) | < > new-line space tab
A blank is a tab or a space. An identifier is a sequence of letters,
digits or underscores, starting with a letter or underscore. Identif-
iers are used as names for functions and variables. A word is a
sequence of characters separated by one or more non-quoted metacharac-
ters.
Commands
A command is a sequence of characters in the programming language syn-
tax of the Korn shell. The shell reads each command and carries out
the desired action either directly or by invoking separate utilities.
A built-in (or special) command is a command that the Korn shell exe-
cutes without creating a separate process. Except for the side effects
documented below, most built-in commands can be implemented as
separate utilities.
A simple command is a sequence of blank-separated words which may be
preceded by a variable assignment list (see Environment below). The
first word specifies the name of the command to be executed. Except as
specified below, the remaining words are passed as arguments to the
invoked command.
The command name is passed as argument 0. The value of a simple com-
mand is its exit status if it terminates normally, or (octal)
200+status if it terminates abnormally [see signal(5) for a list of
status values].
Page 7 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
A pipeline is a sequence of one or more commands separated by the
vertical bar character | (pipe symbol). The standard output of each
command but the last is connected by a pipe system call to the stan-
dard input of the next command. Each command is run as a separate pro-
cess; the Korn shell waits for the last command to terminate. The exit
status of a pipeline is the exit status of the last command.
A command list is a sequence of one or more pipelines separated by the
symbols
;, &, &&, or ||
and optionally terminated by
;, &, or |&
The symbols, ;, &, and |& have equal precedence, which is lower than
that of && and ||. The symbols && and || also have equal precedence. A
semicolon (;) causes sequential execution of the preceding pipeline;
an ampersand (&) causes asynchronous execution of the preceding pipe-
line (i.e. the shell does not wait for that pipeline to finish). The
symbol |& after a command list causes asynchronous execution of the
preceding command or pipeline with a two-way pipe established to the
parent shell.
The -p option of the print and read built-ins (described below) allows
the parent shell to write to the standard input of the spawned command
and read from its standard input respectively. The symbols && and ||
cause the subsequent command list to be executed only if the preceding
pipeline returns a zero or non-zero value respectively. An arbitrary
number of newlines may appear in place of a semicolon as a delimiter
in a command list.
A command is either a simple command or one of the following compound
commands. Unless otherwise stated, the value returned by a command is
always that of the last simple command executed in it.
Reserved words
The following reserved words are only recognized as the first word of
a command provided they are not quoted.
if then elif else fi case esac for
select while until do done { } function
time [[ ]]
Words are only recognized if they are enclosed in delimiter characters
(blanks, punctuation marks etc.). Therefore, in the case of
{ commandlist;} for example, a blank must be entered after { and a
semicolon must be placed before }.
Page 8 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
Compound commands
______________________________________________________________________
for identifier [in wordlist];do commandlist;done
______________________________________________________________________
or
______________________________________________________________________
for identifier [in wordlist]
do commandlist
done
______________________________________________________________________
The for command can be used to repeatedly execute commandlist. Each
time a for loop is executed, identifier is set to the next word taken
from the wordlist. If wordlist is omitted, the commandlist is exe-
cuted once for each positional parameter ("$@") that is set. Execution
ends when there are no more words in the wordlist.
______________________________________________________________________
select identifier [in wordlist]
do commandlist
done
______________________________________________________________________
The select command can be used to repeatedly execute a given
commandlist under input control. select prints the set of words in
wordlist on standard output, each preceded by a number. The PS3
prompt is then printed, and a line is read from the standard input.
The content of the line read from standard input is saved in the vari-
able REPLY. If this line matches 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 the line is empty, the wordlist is
printed again, and identifier is set to the name of the shell script.
If in wordlist is omitted, then the positional parameters are used
instead (as is done with for loops). The select loop is executed
repeatedly until a break built-in or end-of-file is encountered.
Example:
The following Korn shell script can be used to selectively print
information on each individual file in the current directory:
Page 9 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
select file in `ls`
do
if [ -z "$file" ]
then
echo "Select number"
else
file $file
ls -lsid $file
fi
done
______________________________________________________________________
case word in
[[(]pattern[|pattern] ...)commandlist;;] ...
esac
______________________________________________________________________
The case command provides for conditional branching to a command list
on the basis of a pattern. case executes the commandlist associated
with the first pattern that matches word. The form of the patterns is
the same as that used for file name generation (see File name genera-
tion below).
Caution:
The optional left parenthesis preceding pattern must be specified
if case commands are used within command substitutions with
$(...). This produces paired parentheses constructs in $(...).
______________________________________________________________________
if commandlist1
then commandlist2
[elif commandlist3
then commandlist4] ...
[else commandlist5]
fi
______________________________________________________________________
The if command can be used to conditionally execute a number of dif-
ferent command lists. The first list following if (commandlist1) is
executed as the condition, and if it returns a zero exit status
(true), the list following the first then is executed (commandlist2).
Otherwise, the list following elif (commandlist3) is executed as the
next condition, and if its value is zero, the list following the next
then (commandlist4) is executed. Failing that, the else list
(commandlist5) is executed. If no else list or then list is executed,
the if command returns a zero exit status.
Page 10 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
______________________________________________________________________
while commandlist1
do commandlist2
done
until commandlist1
do commandlist2
done
______________________________________________________________________
The while and until commands define loops with exit conditions. A
while command repeatedly executes the condition commandlist1, and if
the exit status of the last command in the list is zero (i.e. true),
it executes the do list in the body of the loop (commandlist2); oth-
erwise the loop terminates. If no commands in commandlist2 (the do
list) are executed, the while command returns a zero exit status.
until may be used in place of while to negate the loop termination
test. The until command tests whether the exit condition is false
(non-zero) and terminates the loop as soon as it returns an exit
status of zero (true).
______________________________________________________________________
(commandlist)
______________________________________________________________________
Executes commandlist in a separate environment.
Caution:
If two adjacent left parentheses are needed for nesting, a space
must be inserted between them to avoid arithmetic evaluation (see
Command substitution below).
______________________________________________________________________
{ commandlist;}
______________________________________________________________________
commandlist is simply executed in the current Korn shell.
Caution:
Note that unlike the parentheses ( and ), the braces { and } are
reserved words and must be typed at the beginning of a line or
after a semicolon (;) in order to be recognized as such.
Page 11 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
______________________________________________________________________
[[ expression ]]
______________________________________________________________________
Evaluates the conditional expression and returns a zero exit status if
expression is true; otherwise 1.
See Conditional expressions below for a description of expression.
______________________________________________________________________
function identifier { commandlist;}
identifier() { commandlist;}
______________________________________________________________________
Defines a function named identifier. This name is used to call the
function like a command. The body of the function consists of the
commandlist that is enclosed within curly braces { and }.
Caution:
The left brace { must be followed by a space.
______________________________________________________________________
time pipeline
______________________________________________________________________
The commands in pipeline are executed and the elapsed time and the
user and system time are reported on standard error.
SUBSTITUTIONS AND VARIABLES
Comments
A word beginning with the hash character # causes that word and all
the following characters in the line to be ignored.
Aliasing
If the first word of a command is a defined alias, it is replaced by
the text of the alias. An alias name consists of any number of charac-
ters excluding metacharacters, quoting characters, file expansion
characters, parameter and command substitution characters, and the
equal sign =. The replacement string can contain any valid Korn shell
script including the metacharacters listed above. The first word of
each command in the replaced text will in turn be tested for aliases.
If the last character of the alias value is a blank, the word follow-
ing the alias will also be checked for alias substitution.
Page 12 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
Aliases can be used to redefine built-in commands but cannot be used
to redefine the reserved words listed above. Aliases can be created,
exported and listed on standard output with the alias command and can
be removed with the unalias command. Exported aliases remain in effect
for scripts invoked by name, but must be reinitialized for separate
invocations of the Korn shell.
Aliasing is performed when scripts are read, not while they are being
executed. Thus for an alias to take effect the alias definition com-
mand has to be executed before the command which references the alias
is read.
Aliases are frequently used as a short hand for full path names. An
option to the built-in alias command allows the value of the alias to
be automatically set to the full pathname of the corresponding com-
mand. 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 variable is reset. These
aliases remain tracked so that the next reference will redefine the
value. Several tracked aliases are compiled into the Korn shell. The
-h option of the built-in set command makes each referenced command
name into a tracked alias.
The following exported aliases are compiled into the Korn shell but
can be unset or redefined with unalias.
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'
Examples:
The following aliases could be defined to construct l, ll and lf:
alias l='/bin/ls -m'
alias ll='/bin/ls -l'
alias lf='/bin/ls -CF'
Page 13 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
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
the next / (slash) is checked to see if it matches a login name 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 slash, is
replaced by $HOME. A tilde followed by a plus sign or a minus sign is
replaced by $PWD and $OLDPWD, respectively.
In addition, tilde substitution is attempted when the value of a
"variable assignment" begins with a ~.
Example:
The command
vi ~/.profile
allows you to edit the .profile file in your login directory from any
location in your file tree.
Command substitution
There are two ways of substituting the standard output of a command
for a part of a word or a full word. In the first (new) form, the com-
mand is enclosed in parentheses and preceded by a dollar sign $(...).
In the second (old) form, the command is enclosed within backquotes
`...`. If the second form is used, the string between the backquotes
is processed for special quoting characters before the command is exe-
cuted (see Quoting metacharacters below). Trailing newlines are
removed for both forms.
The command substitution $(cat file) can be replaced by the equivalent
but faster $(<file). Command substitutions on built-in commands which
do not perform I/O redirection are carried out without a separate pro-
cess being spawned.
Example:
The following command can be used to edit all the files in a
directory which have names ending in .c and contain the string
include:
vi $( grep -l include *.c )
grep -l include *.c scans all .c files for the string include. The -l
option tells grep to list the names of all the files in which it finds
the string.
Page 14 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
An arithmetic expression enclosed in double parentheses and preceded
by a dollar sign, i.e. $((...)), is replaced by the value of the
arithmetic expression within the double parentheses.
Example:
This command will print the second-last parameter in a shell
script:
eval print \$$(( $#-1 ))
Korn shell variables and parameter substitution
A parameter is an identifier, one or more digits, or any of the fol-
lowing characters:
* @ # ? - $ !
A variable (a parameter denoted by an identifier) has a value and zero
or more attributes. Variables can be assigned values and attributes
with the built-in typeset command. The attributes supported by the
Korn shell are described under typeset. Exported parameters pass their
values and attributes to the environment.
The Korn shell supports one-dimensional arrays. An element of an array
variable is referenced by a subscript. A subscript is denoted by a
left square bracket [, followed by an arithmetic expression (see
Arithmetic evaluation below), followed by a right square bracket ].
To assign values to an array, you can use the built-in set command as
follows:
set -A name value ...
The value of all subscripts must be in the permissible range. Arrays
need not be declared; any reference to a variable with a valid sub-
script is legal, and an array will be created if necessary. Referenc-
ing an array without a subscript is equivalent to referencing element
zero.
name=value [name=value] ...
The value of a variable may be assigned in this form. If the
integer attribute is set for a variable, its value can be used
for arithmetic evaluations. Positional parameters (denoted by a
number) may be assigned values with the built-in set command.
Parameter $0 is set from argument zero when the shell is invoked.
Page 15 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
${parameter}
The dollar sign $ is used to introduce substitutable parameters.
The Korn shell reads all the characters from ${ to the matching }
as part of the same word even if it contains braces or metachar-
acters. 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 interpreted as part of its
name, or when a variable is subscripted. If parameter is one or
more digits, then it is a positional parameter. A positional
parameter with more than one digit must be enclosed in braces.
If parameter is defined by the character * or @, then all the
positional parameters, starting with $1, are substituted. The
first character of the IFS variable is used as the field separa-
tor (see below). If an array identifier with the subscript * or @
is used, the value for each of the elements is substituted
(separated by the same field separator character).
${#parameter}
If parameter is * or @, the number of positional parameters is
substituted. Otherwise, the length of the value of parameter is
substituted.
${#identifier[*]}
The number of elements in the array identifier is substituted.
${parameter:-word}
If parameter is set and is non-null, its value is substituted;
otherwise, word is substituted.
${parameter:=word}
If parameter is not set or is null, then it is set to word. The
value of the parameter is then substituted.
Positional parameters may not be assigned values in this way.
${parameter:?word}
If parameter is set and is non-null, its value is substituted;
otherwise, word is printed and the shell exits. If word is omit-
ted, a standard message is printed.
${parameter:+word}
If parameter is set and is non-null, word is substituted; other-
wise, the null string is substituted.
Page 16 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
${parameter#pattern}
${parameter##pattern}
If the Korn shell pattern matches the beginning of the value of
parameter, then the value of this substitution is the value of
parameter with the matched portion deleted; otherwise, the value
of parameter is substituted. In the first form, the smallest
matching pattern is deleted; in the second form, the largest
matching pattern is deleted.
${parameter%pattern}
${parameter%%pattern}
If the Korn shell pattern matches the end of the value of parame-
ter, then the value of this substitution is the value of parame-
ter with the matched portion deleted; otherwise, the value of
parameter is substituted. In the first form, the smallest match-
ing pattern is deleted; in the second form, the largest matching
pattern is deleted.
In the above, 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 dir is not set or is null:
echo ${dir:-$(pwd)}
If the colon is omitted from the above expressions, the Korn shell
only checks whether or not parameter is set; it does not check whether
it is equal to the null string.
The following parameters are automatically set by the Korn shell:
# The number of positional parameters (in decimal).
- All options supplied to the shell on invocation or by the set
command.
? The exit status returned by the last executed command.
$ The process ID of the current Korn shell.
Initially, the value of _ (underscore) is an absolute pathname of
the shell or script being executed as passed in the environment.
Thereafter, it is always assigned the last argument of the previ-
ous command. This parameter is not set for commands which run
asynchronously. The underscore parameter is also used to hold the
name of the matching MAIL file when checking for mail.
Example:
cat /usr/tmp/mydir/xyz* > all
tail $
Page 17 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
The tail command accesses the last file of the previous cat
command using $.
! The process number of the last command invoked as a background
process.
ERRNO
The value of errno as set by the most recently failed system
call. This value is system-dependent and is intended for debug-
ging 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 built-in
getopts command.
OPTIND
The index of the last option argument processed by the built-in
getopts command.
PPID The process number of the parent of the current Korn shell.
PWD The present working directory set by the cd command.
RANDOM
Each time this variable is referenced, a random integer, uni-
formly distributed between 0 and 32767, is generated. You can
initialize the sequence of random numbers by assigning a numeric
value to RANDOM.
REPLY
This variable is set by the select statement and by the built-in
read command when no arguments are supplied.
SECONDS
Each time this variable is referenced, the number of seconds
since the invocation of the Korn shell is returned. If this vari-
able is assigned a value, the value returned upon reference will
be the value that was assigned plus the number of seconds since
the assignment.
The following variables are used by the Korn shell:
CDPATH
The search path for the cd command.
Page 18 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
COLUMNS
If this variable is set, its value is used to define the width of
the edit window for the Korn 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, the corresponding option will be
turned on (see Built-in commands below, set).
ENV If this variable is set, parameter substitution is performed on
its value to generate the pathname of the script that will be
executed when the Korn shell is invoked (see Invocation below).
This file is typically used for alias and function definitions.
FCEDIT
The name of the default editor for the built-in fc command.
FPATH
The search path for function definitions. This path is searched
when a function with the -u attribute is referenced and when a
command is not found. If an executable file is found, it is read
and executed in the current environment.
IFS The Korn shell's internal field separator, used to separate com-
mand words which result from command or parameter substitution
and to separate words with the built-in read command. The value
of IFS is normally set to space, tab, and newline. The first
character of the IFS variable is used to separate arguments in
"$*" substitutions (see Quoting metacharacters below).
HISTFILE
If this variable is set when the Korn shell is invoked, its value
is the pathname of the file that will be used to store the com-
mand history (see Command re-entry below).
HISTSIZE
If this variable is set when the Korn shell is invoked, the shell
will remember the commands you enter (command history). The
number of previously entered commands that are accessible by this
shell will be greater than or equal to the given number. The
default is 128.
HOME The default argument (home directory) for the cd command.
Page 19 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
LINES
If this variable is set, its value is to determine the column
length for printing select lists. select lists will print verti-
cally until about two-thirds of LINES lines are filled.
MAIL If this variable is set to the name of a mail file and the
MAILPATH variable is not set, the Korn shell informs you of the
arrival of mail in the specified file.
MAILCHECK
The value of this variable specifies how often (in seconds) the
Korn shell should check for changes in the modification time of
any of the files specified by the MAILPATH or MAIL variables. The
default value for MAILCHECK is 600 seconds. When the specified
time has elapsed, the Korn shell checks the mail files before
issuing the next prompt.
MAILPATH
A colon-separated list of file names. If this variable is set,
the shell informs you of any modifications to the specified files
that have occurred within the last MAILCHECK seconds. Each file
name may be followed in the list by a question mark and a message
that is to be printed. The message will undergo parameter substi-
tution, with the variable $ defined as the name of the file that
has changed. The default message is: "you have mail in $".
PATH The search path for commands (see Execution below). You may not
change the value of this variable if you are using a restricted
Korn shell.
PS1 The value of this variable is expanded for parameter substitution
to define the Korn shell's primary prompt string. The default is
"$ ". An exclamation point in the primary prompt string will be
replaced by the command number (see Command re-entry below).
PS2 Secondary prompt string displayed by the Korn shell when further
input is expected after a newline character. The default is "> ".
PS3 Prompt string used within a select loop to prompt for the desired
number. The default is "#? ".
PS4 The value of this variable is expanded for parameter substitution
and precedes each line of an execution trace. The default execu-
tion trace prompt is "+ ".
SHELL
The pathname of the Korn shell is kept in the environment. On
Korn shell invocation, the shell will be made a restricted shell
if the basename of this variable matches the pattern *r*sh* [see
basename(1)].
Page 20 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
TMOUT
If TMOUT is set to a value greater than zero, the Korn shell will
automatically terminate if a command is not entered within the
prescribed number of seconds after issuing the PS1 prompt.
(Caution: the Korn shell may have been compiled with a maximum
bound for this value which cannot be exceeded).
VISUAL
If the value of this variable ends in emacs, gmacs, or vi, the
corresponding option will be turned on (see Built-in commands
below, set).
The Korn shell assigns default values to the following variables:
PATH, PS1, PS2, MAILCHECK, TMOUT and IFS.
The HOME, MAIL and SHELL variables are set by login.
Blank interpretation
After parameter and command substitution, the results of substitutions
are scanned for field separator characters and split into distinct
arguments where such characters are found. Explicit null arguments
(e.g. "" or '') are retained. Implicit null arguments (those resulting
from parameters that have no values) are removed.
File name generation
Following substitution, each command word is scanned for the asterisks
(*), queries (?), and left square brackets ([), unless the -f option
has been set (see set). If any of these characters appears in a word,
the word is regarded as a pattern. The word is then replaced by lexi-
cographically sorted file names that match the pattern. If no matching
file name is found, the word is left unchanged. Note that when a pat-
tern is used for file name generation, the dot character (.) at the
start of a file name or immediately following a slash (/), as well as
the slash character itself, must be matched explicitly. In other
instances of pattern matching, the slash and the dot are not treated
specially.
* Matches any string, including the null string.
? Matches any single character. (Slashes and dots are treated spe-
cially; see above.)
Page 21 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
[...]
Matches any one of the characters enclosed within the square
brackets.
A pair of characters separated by a minus sign (-) matches any
character lexically between the pair, inclusive. A minus sign can
be included in the set of characters to be matched as long as it
is the first or last character.
If the first character following the left bracket is a an excla-
mation point, the enclosed set of characters is negated: any
character not enclosed is matched.
A pattern list is a list of one or more patterns separated from each
other by a | (vertical bar). Composite patterns can be formed with one
or more of the following constructs:
?(pattern-list)
Optionally matches any one occurrence 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.
Quoting metacharacters
Each of the metacharacters listed above (see Definitions above) has a
special meaning to the Korn shell and acts as a word separator unless
it is quoted. A single character may be quoted (i.e. made to stand for
itself) by preceding it with a \ (backslash). The \newline pair is
ignored or removed by the Korn shell. 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 a backslash quotes another
backslash, a backquote (`), a double quote ("), and a dollar sign ($).
The meaning of $* and $@ is identical when not quoted or when used as
a variable assignment value or as a file name. However, if they are
enclosed in double quotes and used as a command argument, their mean-
ings differ as follows: "$*" is equivalent to "$1 $2 ...", where the
blank is the first character of the IFS variable, whereas "$@" is
equivalent to "$1" "$2"..., which means that individual command-line
arguments are preserved.
Page 22 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
Inside backquotes, a backslash quotes another backslash, a backquote
and a dollar sign. If the backquotes occur within double quotes, a
backslash also quotes a double quote.
The special meaning of reserved words or aliases can be removed by
quoting any character of the reserved word. The recognition of func-
tion names or built-in command names cannot be suppressed in this way.
Arithmetic evaluation
The built-in let command provides a mechanism for performing integer
arithmetic. Evaluations are performed using long arithmetic. Constants
are of the form [base#]n, where base is a decimal number between two
and thirty-six representing the arithmetic base, and n is a number in
that base. If base# is omitted, base 10 is used.
An arithmetic expression uses much the same syntax, precedence, and
associativity as the C language. All the integral operators, other
than ++, --, ?:, and the comma are supported. Variables can be refer-
enced by name within an arithmetic expression without using the param-
eter substitution syntax (the $ character). When a variable is refer-
enced, its value is evaluated as an arithmetic expression.
An internal integer representation of a variable can be specified as
an attribute with the -i option of the built-in typeset command.
Arithmetic evaluation is performed on the value of each assignment to
a variable with the -i attribute. If you do not specify an arithmetic
base, the first assignment to the variable determines the arithmetic
base. This base is used when parameter substitution is performed.
Since many of the arithmetic operators must be quoted for the Korn
shell, an alternative form of the let command is provided. For any
command which begins with a double left parenthesis ((, all the char-
acters until a matching double right parenthesis )) are treated as a
quoted expression. Thus ((a=a+b)) is equivalent to let "a=a+b".
Conditional expressions
A conditional expression can be used to test attributes of files and
to compare algebraic expressions and strings. In the Korn shell, con-
ditional expressions are specified as part of a compound command of
the form [[...]]. Blank interpretation and file name generation are
not performed on the words of the conditional expression between [[
and ]]. Each conditional expression can be constructed from one or
more of the following unary or binary expressions:
File attributes
In each of the expressions below, if file is of the form /dev/fd/n,
where fd is the file descriptor and n is an integer, then the test is
applied to the open file whose descriptor number is n.
Page 23 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
-a file
(access) True if file exists.
-b file
(block device) True if file exists and is a block special file.
-c file
(character device) True if file exists and is a character special
file.
-d file
(directory) True if file exists and is a directory.
-f file
(file) True if file exists and is an ordinary file.
-g file
(group ID) True if file exists and has its set-group-ID bit set.
-k file
(sticky) True if file exists and is has its sticky bit set.
-o option
(option) True if the named option is turned on (option can be set
with set). You must use the full option name, e.g. errexit.
-p file
(pipe) True if file exists and is a FIFO special file or a pipe.
-r file
(read) True if file exists and the current process has read per-
mission for it.
-s file
(size) True if file exists and has a size greater than zero.
-t fildes
(terminal) True if file descriptor number fildes is open and is
associated with a terminal.
-u file
(user ID) True if file exists and has its set-user-ID bit set.
-w file
(write) True if file exists and the current process has write
permission for it.
-x file
(execute) True if file exists and the current process has execute
permission for it. If file exists and is a directory, then the
current process must have permission to search in the directory.
Page 24 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
-G file
(group) True if file exists and its group matches the effective
group ID of the current process.
-L file
(symbolic link) True if file exists and is a symbolic link.
-O file
(owner) True if file exists and is owned by the effective user ID
of the current process.
-S file
(socket) True if file exists and is a socket.
file1 -nt file2
(newer than) True if file1 exists and is newer than file2.
file1 -ot file2
(older than) True if file1 exists and is older than file2.
file1 -ef file2
(equal file) True if file1 and file2 exist and are links to the
same file.
String attributes and comparisons
-n string
(non-zero) True if string exists and is not a null string, i.e.
if the length of the string is greater than 0.
-z string
(zero) True if the specified string is a null string, i.e. if the
length of the string is 0.
string = pattern
True if string matches pattern.
string != pattern
True if string does not match pattern.
string1 < string2
True if string1 comes before string2 in the ASCII collating
sequence.
string1 > string2
True if string1 comes after string2 based in the ASCII collating
sequence.
Page 25 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
Algebraic comparisons between integers
expr1 -eq expr2
(equal) True if expr1 is equal to expr2.
expr1 -ne expr2
(not equal) True if expr1 is not equal to expr2.
expr1 -lt expr2
(less than) True if expr1 is less than expr2.
expr1 -gt expr2
(greater than) True if expr1 is greater than expr2.
expr1 -le expr2
(less than or equal) True if expr1 is less than or equal to
expr2.
expr1 -ge expr2
(greater than or equal) True if expr1 is greater than or equal to
expr2.
Negated and compound expressions
A compound expression can be constructed from the above expressions
with any of the following mechanisms. The mechanisms are listed in
decreasing order of precedence:
( expression )
True if expression is true. The enclosed expression can be a sin-
gle expression or a group of concatenated expressions.
! expression
Negation: true if expression is false.
expression1 && expression2
Logical AND: True if expression1 and expression2 are both true.
expression1 || expression2
Logical OR: True if either expression1 or expression2 is true.
I/O redirection
Before a command is executed, its input and output may be redirected
by means of a special notation interpreted by the Korn shell. The fol-
lowing arguments may appear anywhere in a simple command or may pre-
cede or follow a command. They are not passed on to the invoked com-
mand, but are interpreted by the shell. Command and parameter substi-
tution occurs before the specified file or file descriptor is used.
File name generation is performed only if the pattern matches a single
file. Blank interpretation is not performed.
Page 26 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
<file
Redirects the standard input (file descriptor 0) of a command to
file, so that input to the command is read from file.
>file
Redirects the standard output (file descriptor 1) of a command to
file, so that output from the command is written to file. If the
file does not exist, it is created. If it does exist, is a regu-
lar file, and the noclobber option is set (see Built-in commands
below, set -o), this causes an error. If noclobber is not set,
the file is truncated to zero length and its existing contents
are lost.
>|file
Same as >file, except that it overrides the noclobber option.
>>file
Redirects the standard output (file descriptor 1) of a command to
file, so that output from the command is written to file. If the
file exists, output is appended to it; otherwise, the file is
created.
<>file
Opens file for reading and writing as standard input.
<<[-]string
Introduces a "here document" (explained below). No parameter sub-
stitution, command substitution or file name generation is per-
formed on string. Input to the Korn shell is read up to (but
excluding) a line that literally matches string or to an end-of-
file. The resulting document, called a "here document", becomes
the standard input for the command.
If any character of string is quoted, all characters in the here
document are treated as quoted.
Caution:
The string marking the last line must not be quoted.
If no characters of string are quoted:
- parameter and command substitution is performed,
- escaped newlines (\newline) are ignored, and
- a backslash must be used to quote backslashes, dollar signs,
backquotes and the first character of string if they are to be
treated literally in the text.
If - is appended to <<, then all leading tabs are stripped from
string and from each line in the here document.
Page 27 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
<&digit
>&digit
In the first form, the standard input is duplicated from file
descriptor digit, i.e. is read from the file associated with
digit. The second form does the same for the standard output.
<&-
>&- The first form closes the standard input for the command, so that
EOF is the only input to the command. The second form closes the
standard output for the command, so that the command does not
write any output.
<&p
>&p The input from the co-process in a two-way pipeline is redirected
to standard input. Similarly, the output to the co-process is
redirected to standard output.
If one of the above redirections is preceded by a digit, the file
descriptor number referred to is that specified by the digit (instead
of the default 0 for stdin and 1 for stdout).
Example:
To open file descriptor 2 (stderr) for writing as a duplicate of
file descriptor 1 (stdout):
... 2>&1
The order in which redirections are specified is significant. The Korn
shell evaluates each redirection in terms of the association (file
descriptor, file) at the time of evaluation. For example:
... 1>file 2>&1
first associates standard output (file descriptor 1) with file and
then associates standard error (file descriptor 2) with the file asso-
ciated with file descriptor 1 (i.e. file).
In other words, both the standard output and the error messages from
the command are written to file.
If the order were reversed, file descriptor 2 would be associated with
the terminal (assuming file descriptor 1 had been), file descriptor 1
with file. This would mean that only the standard output would be
written to file, not the error messages.
If a command is started in the background with & and job control is
not active, the default standard input for the command is the empty
file /dev/null. If job control is active, the environment for the exe-
cution of a command contains the file descriptors of the invoking Korn
shell as modified by input/output specifications.
Page 28 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
You can set commands or pipelines to run in the background from within
a script. They can then communicate with your program. To spawn a co-
process of this type, you put the operator & after the command. You
can only use two-way pipes in scripts, not on the command line.
A group of commands can only be called once as a two-way pipe. If you
terminate the original process (e.g. using kill -9 PID) and then later
again try to write a command to a two-way pipe, a subshell will be
called, but the process will be stopped and the error message "ksh:
bad file unit number" will be issued.
EXECUTION ENVIRONMENT
Environment
The environment of a process consists of 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 Korn shell-style identifiers; the
values must be character strings (including the null string). The Korn
shell interacts with the environment in several ways. On invocation,
the shell scans the environment and creates a variable for each name
found, giving it the corresponding value and marking it for export.
Executed commands inherit the environment. If the user modifies the
values of these variables or creates new ones using the export or
typeset -x commands, they become part of the environment. The environ-
ment seen by any executed command is thus composed of any name=value
pairs originally inherited by the shell, whose values may be modified
by the current shell, plus any additions that have been marked in
export or typeset -x commands.
The environment for any simple command or function may be augmented by
prefixing it with one or more variable assignments. A variable assign-
ment argument is a word of the form identifier=value.
command sees the following lines as equivalent:
TERM=450 command arguments
(export TERM; TERM=450; command arguments)
(Some built-in commands deviate from this rule. These commands are
marked + or ++ in the section on Built-in commands below.)
If the -k option was set on Korn shell invocation or with the built-in
set command, all variable assignment arguments are exported to the
environment, even if they occur after the command name.
Example:
The following example first prints a=b c and then c:
echo a=b c
set -k
echo a=b c
Page 29 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
This feature is intended for use with scripts written for early ver-
sions of the Bourne shell. It is best not to use it in new scripts,
since the -k option may no longer be supported in future releases.
Functions
The reserved word function (see Compound commands above) is used to
define Korn shell functions. Shell functions are read in and stored
internally. Alias names are resolved when the function is read. Func-
tions are executed like commands, with arguments passed as positional
parameters (see Execution below).
Functions execute in the same process as the caller and share all open
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; the condition is then
passed on to the caller. A trap on EXIT set inside a function is exe-
cuted after completion of the function in the environment of the caller.
Variables are usually shared between the calling program and the func-
tion. However, the built-in typeset command can be used within a func-
tion to define local variables whose scope includes the current func-
tion and all functions it calls.
The built-in return command is used to return from function calls.
Errors that occur within functions return control to the caller.
Function identifiers or names can be listed with the -f or +f option
of the built-in typeset command. The text of functions may also be
listed with the -f option. Functions can be undefined with the -f
option of the built-in unset command.
Functions are usually not accessible when the Korn shell executes a
shell script.
The -xf option of the typeset command allows a function to be marked
for export. These functions can then be used in scripts that are exe-
cuted without a separate invocation of the Korn 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.
Example:
The following function named lh lists the top two levels of the
directory hierarchy in which you are located or which you specify
as an argument. Regular files are ignored as arguments.
Page 30 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
function lh
{
for i in ${*:-.}
do
if [[ -d $i ]]
then
print $i:
cd $i
ls -CF $( ls )
cd - >/dev/null
fi
done
}
The for loop processes each of the specified arguments in succession.
If you have not specified an argument, $* is set to the current direc-
tory (.).
If a directory is present, its name and contents are listed as fol-
lows: cd $i switches to the directory to be listed; $( ls ) is
replaced by the content of the directory $i, and ls -CF directorylist
lists the files, followed by the contents of the directories, with
flags to indicate executables and directories. The subsequent cd com-
mand silently returns to the initial directory (before the first cd $i).
Jobs
If the monitor option of the built-in set command is turned on, an
interactive Korn shell associates a job with each pipeline. It main-
tains a table of current jobs, which you can written to standard out-
put with the built-in jobs command, and assigns them small integer
numbers. When a job is started asynchronously with &, the shell prints
a line of the form:
[1] 1234
indicating that the job which was started asynchronously was job
number 1 and had one (top-level) process, whose process ID was 1234.
If one job is running and you want to start other jobs, you can simply
press <CTRL-Z>. This sends a STOP signal to the current job. The shell
will then normally indicate that the job has been "Stopped", and will
issue another prompt. You can then manipulate the state of this job by
putting it in the background with the bg command, or you can leave it
in the stopped state, run some other commands and then eventually
bring the job back into the foreground with the foreground command fg.
<CTRL-Z> takes effect immediately and is like an interrupt with
<CTRL-D> in that pending output and unread input are discarded when it
is typed.
Page 31 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
A background job will stop if it tries to read from the terminal.
Background jobs are normally allowed to produce output, but you can
stop this with the command stty tostop. If you set this stty option,
background jobs will stop when they try to produce output.
There are several ways to reference jobs in the shell. A job can be
referenced by the process ID of any of its processes or by one of the
following expressions:
%number
the job with the given job number
%string
any job whose command line begins with string
%?string
any job whose command line includes string
%% the current job
%+ equivalent to %%
%- the previous job
The Korn shell registers changes in the status of jobs immediately. 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 option is turned on, each background job that com-
pletes triggers any trap set for CHLD.
If you try to exit the Korn shell while jobs are running in the back-
ground or stopped, you will be warned with the message: You have
stopped (running) jobs.
You may then use the jobs command to obtain an overview of the current
situation. If you do this or immediately try to exit again, the shell
will not warn you a second time, and the stopped jobs will be ter-
minated.
Signals
The INT and QUIT signals for an invoked background command (&) are
ignored if the job monitor option is not active. Otherwise, signals
have the values inherited by the Korn shell from its parent (see also
the built-in trap command below).
Page 32 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
Execution
Each time a command is executed, the substitutions described above are
carried out in the following order:
- Quoting
- Parameter substitution
- Tilde substitution
- Aliasing
- File name generation
- I/O redirection
- Command substitution
If the command name matches the name of one of the built-in commands,
it is executed within the current Korn shell process. Next, the com-
mand 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 com-
pletes or executes a built-in return command, the positional parameter
list is restored and any trap set on EXIT within the function is exe-
cuted. The exit status is that of the last command executed in the
function. A function is also executed in the current Korn shell pro-
cess. If a command name is not a built-in command or a user-defined
function, a process is spawned and an attempt is made to execute the
command via the system call exec.
The shell variable PATH defines the search path for the directory con-
taining 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 speci-
fied 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, 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 contain a shell script.
A subshell is spawned to read it. Any non-exported aliases, functions
and variables are removed in this case. A parenthesized command is
executed in a sub-shell without removing non-exported quantities.
Page 33 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
COMMAND PROCESSING
Command re-entry
The text of the last HISTSIZE commands entered from a terminal is
saved in a history file. The default value for HISTSIZE is 128. If the
HISTFILE variable is not set or if the file denoted by its value is
not writable, the file $HOME/.shhistory is used to save the command
history. A Korn shell can access the commands of all interactive
shells which use the same history file. The built-in fc command can be
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 may be specified. If you do not specify an editor
program as an argument to fc, the value of the variable FCEDIT is
used. If FCEDIT is not defined, /usr/bin/ed is used. The edited com-
mands are printed and re-executed when you leave the editor.
Specifying -s skips the edit phase. In this case, a variable of the
form old=new can be used to modify the command before it is executed.
If, for example, you enter fc -s nonsense=sense c, the last command
that began with the character c is executed. Before this takes place
however, the first occurrence of nonsense in the command is replaced
by sense.
In-line editing options
Normally you simply type in a command line and terminate it with a
newline character. However, if the vi option is active (see set
below), you can also edit command lines.
This editing option is automatically selected when the VISUAL or
EDITOR variable is assigned a value that ends with emacs, gmacs, or
vi.
The editing features require the terminal to have the following capa-
bilities:
- it must accept "return" as a carriage return without a line feed,
and
- 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 mode uses the concept of a window on the current line. The
window width is the value of COLUMNS if it is defined, or 80 charac-
ters if it is not. If the line is longer than the window width minus
two, you are notified by a mark displayed at the end of the window. As
you move the cursor across a window boundary, the window moves to
center about the cursor position.
Page 34 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
The following marks are used:
> if the line extends beyond the right side of the window
< if the line extends beyond the left side of the window
* if the line extends beyond both sides of the window
The search commands in each edit mode provide access to the history
file. Only strings are matched, not patterns, except that a caret (^)
as the first character of a string restricts the match to begin at the
first character in the line.
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 ^T. To
edit, the user moves the cursor to the point needing correction and
then inserts or deletes characters or words as needed. All the editing
commands are control characters or escape sequences. The notation for
control characters is caret (^) followed by the character. For exam-
ple, ^F is the notation for <CTRL-f>. This is entered by depressing
"f" while holding down the "CTRL" (control) key. The "SHIFT" key is
not depressed. (The notation ^? indicates the DEL (delete) key.)
The notation for escape sequences is M- followed by a character. For
example, M-f (pronounced Meta f) is entered by depressing 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). Neither the "RETURN" nor the "LINEFEED" key is entered
after edit commands except when noted.
^F Move cursor forward (right) one character.
M-f Move cursor forward one word. (The emacs editor's idea of a word
is a string of characters consisting of only letters, digits and
underscores.)
^B Move cursor backward (left) one character.
M-b Move cursor backward one word.
^A Move cursor to start of line.
^E Move cursor to end of line.
^]char
Move cursor forward to character char on current line.
Page 35 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
M-^]char
Move cursor back to character char on current line.
^X^X Interchange the cursor and mark.
erase
(User defined erase character as defined by the stty(1) command,
usually ^H or #.) Delete previous character.
^D Delete current character.
M-d Delete current word.
M-^H (Meta-backspace) Delete previous word.
M-h Delete previous word.
M-^? (Meta-DEL) Delete previous word (if your interrupt character is
^? (DEL, the default) then this command will not work).
^T Transpose current character with next character in emacs mode.
Transpose two previous characters in gmacs mode.
^C Capitalize current character.
M-c Capitalize current word.
M-l Change the current word to lower case.
^K Delete from the cursor to the end of the line. If preceded by a
numerical parameter whose value is less than the current cursor
position, then delete from given position up to the cursor. If
preceded by a numerical parameter whose value is greater than the
current cursor position, then delete from cursor up to given cur-
sor position.
^W Kill from the cursor to the mark.
M-p Push the region from the cursor to the mark on the stack.
kill (User defined kill character as defined by the stty command, usu-
ally ^G or @.) Kill the entire current line. If two kill charac-
ters are entered in succession, all kill characters from then on
cause a line feed.
^Y Restore last item removed from line. (Yank item back to the
line.)
^L Line feed and print current line.
^@ (Null character) Set mark.
Page 36 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
M-space
(Meta space) Set mark.
^J (Newline) Execute the current line.
^M (Return) Execute the current line.
eof End-of-file character, normally ^D, is processed as an end-of-
file only if the current line is null.
^P Fetch previous command. Each time ^P is entered the previous com-
mand back in time is accessed. Moves back one line when not on
the first line of a multi-line command.
M-< Fetch the least recent (oldest) history line.
M-> Fetch the most recent (youngest) history line.
^N Fetch next command line. Each time ^N is entered the next command
line forward in time is accessed.
^Rstring
Reverse search history for a previous command line containing
string. If a parameter of zero is given, the search is forward.
string is terminated by a "RETURN" or "NEWLINE". If string is
preceded by a ^, 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 a parameter of zero
reverses the direction of the search.
^O Operate - Execute the current line and fetch the next line rela-
tive to current line from the history file.
M-digits
(Escape) Define numeric parameter, the digits are taken as a
parameter to the next command. The commands that accept a parame-
ter are ^F, ^B, erase, ^C, ^D, ^K, ^R, ^P, ^N, ^], M-., M-^], M-
, M-b, M-c, M-d, M-f, M-h, M-l and M-^H.
M-letter
Soft-key - Your alias list is searched for an alias by the name
letter and if an alias of this name is defined, its value will
be inserted on the input queue. The letter must not be one of the
above meta-functions.
M-]letter
Soft-key - Your alias list is searched for an alias by the name
letter and if an alias of this name is defined, its value will
be inserted on the input queue. The can be used to program func-
tions keys on many terminals.
Page 37 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
M-. 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.
M- Same as M-..
M-* Attempt file name generation on the current word. An asterisk is
appended if the word doesn't match any file or contain any spe-
cial pattern characters.
M-ESC
File name 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 / is appended if the
file is a directory and a space is appended if the file is not a
directory.
M-= List files matching current word pattern if an asterisk were
appended.
^U Multiply parameter of next command by 4.
\ Escape next character. Editing characters, the user's erase, kill
and interrupt (normally ^?) characters may be entered in a com-
mand line or in a search string if preceded by a \. The \ removes
the next character's editing features (if any).
^V Display version of the shell.
M-# Insert a # at the beginning of the line and execute it. This
causes a comment to be inserted in the history file.
vi editing mode
There are two typing modes:
- When you enter a command you are in input mode.
- When you press the <ESCAPE> key, you enter control mode.
In this mode you can edit by moving the cursor to the point needing
correction and then inserting or deleting characters. As with vi, most
commands accept an optional repeat count prior to the command.
The initial setting on most systems in vi mode is input mode. Entering
<ESCAPE> terminates the input mode and allows you to modify the com-
mand line. This scheme offers the combined advantages of input mode as
an initial setting and the type-ahead echoing of raw mode.
Page 38 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
Input edit commands
By default the editor is in input mode.
<BACKSPACE>
<BACKSPACE> represents the erase character as defined by the stty
command.) Deletes the character to the left of the cursor.
<CTRL-W>
Deletes the previous blank-delimited word.
<CTRL-D>
Terminates the Korn shell, unless the ignoreeof option is set
(see set below).
<CTRL-V>
Escapes the next character. Editing characters and the erase and
kill characters may be entered in a command line or in a search
string if preceded by a <CTRL-V>. The <CTRL-V> removes the next
character's editing features (if it has any).
\ Escapes the next erase or kill character.
Motion edit commands
These are commands for moving the cursor. A count is equivalent to
repeating the command the specified number of times.
[count]l
Cursor one character forward (right).
[count]w
Cursor one alphanumeric word forward (right).
[count]W
Cursor to the beginning of the next word that follows a blank.
[count]e
Cursor to end of word.
[count]E
Cursor to end of the current blank-delimited word.
[count]h
Cursor one character back (left).
[count]b
Cursor one word back (left).
[count]B
Cursor to preceding blank-delimited word.
Page 39 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
[count]|
Cursor to column count.
[count]fc
Finds the next occurrence of character c in the current line.
[count]Fc
Finds the previous occurrence of 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 command given
with f, F, t or T.
[count],
Reverses the last single-character find command count times.
0 Cursor to start of line.
^ Cursor to first visible non-blank character in line.
$ Cursor to end of line.
Search edit commands
These are commands for accessing your command history file:
[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 command number count. The default is the least recent
history command.
Page 40 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
/string
Searches backward through the history file for an earlier command
including string. string is terminated by a newline character. If
string is preceded by a caret (^), the matched line must begin
with string. If string is null, the previous string will be used.
?string
Same as /, but searching forward.
n Searches for the next line matching the last search string.
N Search for next line matching the last search string, but in
reverse direction. Searches the history file for the string
entered with the previous / command.
Text modification edit commands
These are commands for modifying the command line.
a Enters input mode and inserts 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 that motion
would move the cursor to 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 the line and
enters input mode.
S Equivalent to cc.
D Deletes the current character through the end of the line.
Equivalent to d$.
[count]dmotion
d[count]motion
Deletes the current character through the character that motion
would move to. 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 (count copies of) the previous text modification before
the cursor.
Page 41 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
[count]p
Places (count copies of) the previous text modification after the
cursor.
R Enters input mode and overwrites existing text from the current
character onward.
[count]rcharacter
Replaces the next count character(s) starting at the current cur-
sor position with character and advances the cursor to the last
replaced character.
[count]x
Deletes the current character (and the next count minus 1 charac-
ters).
[count]X
Deletes the preceding (count) character(s).
[count].
Repeats the previous text modification command (count times).
[count]~
Inverts the case of the (count) character(s) starting at the
current cursor position and advances the cursor count characters.
[count]
Appends the last word (or word number count) of the previous com-
mand and enters input mode.
* Attempts file name generation with the current word by appending
an asterisk to it. If no match is found, the terminal bell rings.
Otherwise, the word is replaced by the matching file name and
input mode is entered.
\ Filename completion: replaces the current word with the longest
common prefix of all file names matching the current word with an
asterisk appended. If the match is unique, a slash is appended if
the file is a directory and a space is appended if the file is
not a directory.
Other edit commands
[count]ymotion
y[count]motion
Yanks (copies) the current character through the character that
motion would move the cursor to and puts them in the delete
buffer. The text and the cursor position are left unchanged.
Y Yanks text from the current character position to the end of the
line. Equivalent to y$.
Page 42 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
u Undoes the last text modification command.
U Undoes all the text modification commands performed on the com-
mand line.
[count]v
Reads count lines from the history file into the input buffer
using the command:
fc -e ${VISUAL:-$(EDITOR:-vi}} count.
If count is omitted, the current line is used.
<CTRL-L>
(line feed) Outputs a line feed and prints the current line. This
command only works in command mode.
<CTRL-J>
(newline) Executes the current line, regardless of the current
mode.
<CTRL-M>
(carriage return) Executes the current line, regardless of the
current mode.
# Sends the line after inserting a # (hash character) in front of
the line. Useful for causing the current line to be inserted in
the history without being executed.
= Lists the file names that would match the current word if an
asterisk were appended to it.
@letter
Searches the alias list for an alias named letter, and if it
finds one, uses its value as input.
Built-in commands
In Korn shell documentation, built-in commands are sometimes referred
to as special commands. The term "built-in command" is preferred here
for consistency with csh and sh.
The following simple commands are executed in the Korn shell itself.
Input/output redirection is permitted. Unless otherwise indicated, the
output is written to standard output, and the exit status is zero
unless there is a syntax error.
Commands that are preceded by one or two plus characters (+ or ++) in
the description are treated specially in the following ways:
- Variable assignment lists preceding the command name remain in
effect when the command completes.
Page 43 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
- I/O redirections are processed after variable assignments.
- Errors cause a script that contains them to abort.
- ++ only:
Words that are in the form of a variable assignment (name=value)
are expanded with the same rules as a variable assignment.
This means that tilde substitution is performed after the equal
sign, but word splitting (by blank interpretation) and file name
generation are not.
The commands with + are: : (colon), . (dot), break, continue, eval,
exec, exit, newgrp, return, shift, times, trap, wait.
The commands with ++ are: alias, export, readonly, typeset.
+: [arg ...]
This command simply expands parameters in arg.
+. file [arg ...]
Reads the entire file and executes the commands it contains in
the current Korn shell environment. The search path specified by
PATH is used to find the directory containing file.
If any arguments arg are given, they become the positional param-
eters; otherwise, the positional parameters are unchanged. The
exit status is the exit status of the last command executed.
[ Test conditions, see test(1).
++alias [-t] [name]
alias with no arguments writes the list of aliases in the form
name=value to standard output.
-t 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 remain tracked. Without the -t option, the
name=value pair is printed for each name in the argument
list for which no value is given.
++alias [-x] [name=[value]]...
A space at the end of value causes the next word in the command
line to be checked for alias substitution.
-x Used to set or list exported aliases. An exported alias is
defined for scripts invoked by name.
The exit status is non-zero if no value is defined for name.
Page 44 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
bg [job ...]
Moves each specified job into the background. If job is not
specified, the last stopped job is moved into the background. The
format of job is as described under Jobs above.
+break [num]
Exits from the enclosing for, while, until or select loop. If num
is specified, execution is resumed in the numth enclosing loop.
break 0 causes an exit from the outermost loop. break 1 is
equivalent to break.
cd [dir] Format 1
cd old new Format 2
Format 1: Change directory using CDPATH
cd changes the current directory to dir. If you specify a minus
sign (-) for dir, the directory is changed to the previous direc-
tory. The PWD variable is set to the current directory, and
OLDPWD is set to the previous value of PWD. The shell variable
CDPATH defines the search path for the directory containing dir.
As in the case of PATH, alternative directory names listed in
CDPATH are separated by colons (:). The default path is the null
string, which corresponds to the current directory. Note that the
current directory is specified by a null path name, which can
appear anywhere in CDPATH, even after the equal sign. If dir
begins with a slash, the search path is not used. Otherwise, each
directory in the search path is searched for dir in the given
order.
Format 2: Change directory with text substitution
cd substitutes the string new for the string old in the current
directory name (PWD) and tries to change to this new directory.
+continue [num]
Resumes execution at the next iteration of the enclosing for,
while, until or select loop. If num is specified, then execution
is resumed at the numth enclosing loop. continue 0 resumes execu-
tion after the outermost loop. continue 1 is equivalent to
continue.
command [-p] commandname [argument ...] Format 1
command [-v| -V] commandname Format 2
Refer to the description of the command(1) command.
echo [arg ...]
Refer to the description of the echo(1) command.
Page 45 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
+eval [arg ...]
The arguments are read as input to the Korn shell, and the
resulting commands are executed. Thus there are two stages of
argument evaluation.
+exec [arg ...] Format 1
exec [redirection ...] Format 2
Format 1: Overlay Korn shell
If arg is given, the command specified by the arguments is exe-
cuted in place of the current Korn shell without a new process
being spawned. I/O redirection, if specified, is carried out by
the current Korn shell and then applies to the executed command.
Format 2: I/O redirection
If redirection is given, the effect of this command is to modify
file descriptors as described in the section on I/O redirection
above. In this case, any file descriptor numbers greater than 2
that are opened with this mechanism are closed when another pro-
gram is invoked.
+exit [num]
This command terminates the Korn shell with the exit status
specified by num. If num is omitted, the exit status is that of
the last command executed. An end-of-file will also cause the
shell to exit, provided the ignoreeof option has not been set
(see set below).
++export [name=[value]]... Format 1
export [-p] Format 2
The given names are marked for automatic export to any new
environment. If export is invoked without arguments, all vari-
ables marked for exported are listed on standard output. -p gen-
erates a portable format with export statements, that can be used
to backup and restore a particular status.
false
See let 0 or the false(1) command.
fc [-e ename] [-lnr] [--] [first [last]] Format 1
fc [-s] [--] [old=new] [commando] Format 2
Format 1: Edit commands from the history file
The range of commands from first to last in the last HISTSIZE
commands typed at the terminal is selected for editing and subse-
quent execution. The first and last arguments may be specified as
numbers or as strings.
Page 46 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
A positive number stands for the number of the command; a nega-
tive number is interpreted as an offset from the current command
number.
A string is used to locate the most recent command starting with
the given string. If last is not specified, it is set to first;
if first is not specified either, the default is the previous
command for editing and -16 for listing.
-e editor
editor is the name of the editor to be used. If the editor
name is not supplied, the value of the variable FCEDIT is
used.
If FCEDIT is not set, the default editor /usr/bin/ed is
invoked.
-l Lists the specified commands on standard output. The com-
mands are not edited or executed. -l cannot be combined with
-e.
-n Suppresses command numbers when listing commands with the -l
option.
-r Reverses the order in which the commands are presented.
-- If the first argument begins with a minus sign (-), the end
of the command-line options must be marked with --.
Format 2: Re-execute commands
The command is re-executed with new substituted for old.
-s The commands are executed without calling an editor first.
fg [job ...]
Moves each job specified is into the foreground. If no job is
specified, The last job that was stopped or moved into the back-
ground is moved into the foreground. The format of job is as
described under Jobs above.
getopts optstring name [arg ...]
getopts checks arg for legal options. If arg is omitted, the
positional parameters are used. An option argument begins with a
plus or minus sign. The options are ended by an argument not
beginning with a plus or minus sign, or by the argument --.
optstring contains the letters that getopts recognizes as
options. If a letter is followed by a colon, that option is
expected to have an argument. The options can be separated from
the arguments by blanks.
Page 47 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
Each time getopts is invoked, it assigns the next option letter
it finds to the variable name, with a plus sign prepended to it
if the option begins with a plus sign. The index of the next
argument is stored in OPTIND. The option argument, if any, is
stored in OPTARG.
A colon at the start of optstring causes getopts to store the
letter of an invalid option in OPTARG, and to set name to ? for
an unknown option, or to : when a required option is missing.
Otherwise, getopts prints an error message. The exit status is
non-zero when there are no more options.
jobs [-lnp] [job ...]
This command is only available on systems that support job con-
trol. It lists information (sequence, status, and calling com-
mand) about each given job, or about all active jobs if job is
omitted.
-l Lists process IDs in addition to the normal information.
-n Displays only those jobs that have stopped or exited since
the last invocation of the jobs command.
-p Lists only the process group.
See the Jobs section above for a description of the format
of job.
kill [-s signal] job ... Format 1
kill -l [number] Format 2
Format 1: Send signals to processes
Sends the TERM signal or the signal specified as signal to the
job or process identified by job. Signals are defined by name (as
listed in the file /usr/include/signal.h, without the SIG pre-
fix). If the TERM or HUP signal is to be sent to a stopped job or
process, a CONT signal will be sent to it first. The job argument
can be the process ID of a process that is not a member of one of
the active jobs.
The format of job is as described under Jobs above.
Format 2: List signal numbers and names
kill -l lists all signal numbers and their symbolic names on the
standard output, one per line. If number is specified, only the
signal with the corresponding signal number is output.
Page 48 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
let argument ...
Each argument is an arithmetic expression. The results obtained
on evaluation are output. The exit status is 0 if the value of
the last expression is non-zero, and 1 otherwise.
login [loginname [environment ...]]
Refer to the description of the login(1) command.
+newgrp [-l] [--] [group]
Equivalent to exec /usr/bin/newgrp ... group. newgrp makes the
number of the specified group the current group number and over-
laps itself with a shell.
-l newgrp overlaps the current shell with a login shell.
-- must be specified if group begins with -.
print[ -Rnprsu[fildes]] [arg ...]
print is the output mechanism of the Korn shell. If it is invoked
with no options or with the option - or --, the arguments are
printed on standard output as explained in the echo command
description.
-R or -r
In raw mode, the escape conventions of echo are ignored. The
-R option prints all subsequent arguments and options except
for the -n option.
-n No newline is added to the output.
-p The arguments are written to the pipe of the process spawned
with |&, not to standard output.
-s The arguments are written to the history file, not to stan-
dard output.
-ufildes
Arguments are written to the single-digit file descriptor
fildes, not to standard output.
pwd See print -r - $PWD or the pwd(1) command.
read [-prs] [-u [fildes]] [--] [name?prompt] [name ...]
read is the input mechanism of the Korn shell. It reads one line
from standard input and breaks it into fields, assigning the
first field to the first name, the second field to the second
name, etc., with leftover fields being assigned to the last name.
If name is omitted, REPLY is used as the default name.
Page 49 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
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 unless an end-of-file is
encountered.
-r The backslash \ must not be treated as a special character.
-p The input line is read from the pipe of the process spawned
with |&, not from standard input. An end-of-file from the
pipe causes cleanup for this process so that a new process
can be spawned with |&.
-s Saves the input as a command in the history file.
-u Input is read from the single-digit file descriptor fildes,
not from standard input. The file descriptor can be opened
with the built-in exec command. The default value of fildes
is 0.
-- If name begins with a minus sign (-), the end of the
command-line options must be marked with --.
++readonly [name=value] [name ...] Format 1
readonly [-p] Format 2
The variables specified by name are marked readonly. The values
of these variables cannot be changed by subsequent assignment.
If you call readonly without any arguments, all read-only vari-
ables are written to the standard output. -p generates a portable
format with read-only statements, that can be used to back up and
restore a particular status.
+return [num]
Causes a shell function to return to the invoking script. The
return status is num or that of the last command executed. If
return is invoked while not in a function or a script executed
with the dot command, it has the same effect as an invocation of
exit.
set [option ...] [arg ...]
The set command can be used for three purposes:
- to set positional parameters
- to list variables on standard output
- to set Korn shell options
If the -A option is not specified, the positional parameters are
assigned new values from the arguments in arg. The first argument
is assigned to $1, the second to $2, etc.
Page 50 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
If neither option nor arg is given, the names and values of all
variables are listed on standard output.
The Korn shell options may be changed during a session. A minus
sign before the option letters turns on the corresponding
options; a plus sign turns them off. The current set of options
may be found in the variable $-. These options can also be used
upon invocation of the Korn shell. The available options are as
follows:
-A name
Array assignment: unsets the variable name and assigns new
values sequentially from the list of arguments given in arg.
If +A is used, the variable name is not unset first.
-a All subsequent variables that are defined are automatically
exported.
-b The user is informed of all completed background processes.
-C If the output is redirected with >, no existing files are
overwritten.
-e If a command has a non-zero exit status, the ERR trap, if
set, is executed and the Korn shell exits.
-f Disables file name generation.
-h Each command executed is placed in the alias list as a
tracked alias.
-k All variable assignment arguments are placed in the environ-
ment for a command, not just those that precede the command
name.
-m Background jobs are run in a separate process group, and a
report line is printed upon completion. The exit status of
background jobs is reported in a completion message. This
option is turned on automatically for an interactive Korn
shell.
-n Reads commands and check them for syntax errors, but does
not execute them. This option is ignored by an interactive
Korn shell.
-o argument
argument can be one of the following option names:
allexport
Same as -a.
Page 51 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
bgnice
All background jobs are run at a lower priority. This
is the default mode.
emacs
The commands are edited in emacs mode.
errexit
Same as -e.
gmacs
As for emacs. See the section emacs editing mode above.
ignoreeof
The Korn shell will not exit on encountering an end-
of-file. The built-in exit command must be used.
interactive
Interactive Korn shell.
keywords
Same as -k.
markdirs
All directory names resulting from file name generation
have a trailing slash appended.
monitor
Same as -m.
noclobber
Prevents output redirection with > from overwriting
existing files. Corresponds to -C.
noexec
Same as -n.
noglob
Same as -f.
nolog
Function definitions are not saved in the history file.
notify
Corresponds to -b.
nounset
Same as -u.
privileged
Same as -p.
Page 52 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
restricted
Restricted Korn shell. See chapter rksh only above.
trackall
Same as -h.
verbose
Same as -v.
vi Puts you in the insert mode of a vi style in-line edi-
tor until you press <ESCAPE>. This puts you in command
mode. A newline character sends the line.
viraw
In vi mode, each character is processed as soon as it
is typed.
xtrace
Same as -x.
-p If the effective user ID (group ID) is not equal to the real
UID (GID), processing of $HOME/.profile is disabled and the
file /etc/suidprofile is used instead of the ENV file.
Turning this option off with +p causes the effective UID and
GID to be set to the real UID and GID.
-s Sorts the positional parameters lexicographically.
Note that this option is not the same as the -s option that
can be used when invoking the Korn shell.
-t Terminates the Korn shell after reading and executing one
command.
-u Unset parameters are treated as errors when substitution is
performed.
-v The Korn shell prints input lines as it reads them.
-x Commands and their arguments are printed as they are exe-
cuted.
- Turns off the -x and -v options and stops examining argu-
ments for options. The rest of the command line is taken as
arg.
-- Stops any of the options being changed; useful in setting $1
to a value beginning with -. If no arguments follow this
option, the positional parameters are unset.
Page 53 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
+shift [number]
The positional parameters from $number+1 onward are renamed $1
and so on, i.e. the values of the positional parameters are
shifted to the left. The default value for number is 1. $0 is not
affected by this command. The number argument can be any arith-
metic expression that evaluates to a positive integer less than
or equal to $#.
test See Conditional expressions above or the test(1) command.
+times
Prints the accumulated user and system times for the current Korn
shell and for processes run from the shell.
+trap [cmd] [sig ...]
cmd is a command or list of commands to be read and executed when
the Korn shell receives signal(s) sig.
(Note that cmd is scanned twice, once when the shell executes the
trap command and once when cmd is executed in response to a sig-
nal.)
Each sig can be given as a number or as the name of the signal
(see kill).
trap commands are executed in order of signal number. Any attempt
to set a trap on a signal that was ignored on invocation of the
current shell is ineffective. If cmd is omitted or is in the form
of a minus sign (-), all trap(s) on sig are reset to their origi-
nal values. If cmd is the null string (""), the associated signal
is ignored by the Korn shell and by the commands it invokes. If
sig is ERR, cmd will be executed whenever a command has a non-
zero exit status. If sig is DEBUG, cmd will be executed after
each command. If sig is 0 or EXIT and the trap statement is exe-
cuted inside the body of a function, cmd is executed after the
function completes. If sig is 0 or EXIT for a trap set outside
any function, cmd is executed on termination of the shell.
The trap command with no arguments writes a list of commands
associated with each signal number to standard output.
true See : or the true(1) command.
++typeset [option ...] [name[=value]]...
The typeset command can be used for two purposes:
- to list variable names and other optional information on stan-
dard output,
- to set attributes and values for shell variables.
Page 54 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
If neither option nor name[=value] is given, the names and attri-
butes of all variables are listed on standard output.
If there are options but no name arguments, all variables which
have these options set are listed along with their attributes.
Using a plus sign instead of a minus sign stops the values from
being printed.
option can be used to assign one or more attributes to the vari-
able name[=value]. When typeset is invoked inside a function, a
new instance of the variable name is created. The value and its
attribute are restored when the function completes.
Using a minus sign before the option letters turns on the
corresponding attributes; a plus sign turns them off.
The following attributes may be specified:
-H This option allows for UNIX-style mapping of file names to
host names on non-UNIX machines.
-L[num]
Left-justifies value and removes leading blanks.
If num is non-zero, it defines the length of the field; oth-
erwise, the field length is determined by the length of the
first value assignment.
This length is used for subsequent assignments. When the
variable is reassigned, it is padded to the right with
blanks or truncated as necessary.
Leading zeros are removed if the -Z option is also set. The
-L option turns off the -R option.
-R[num]
Right-justifies value and pads it with leading blanks.
If num is non-zero, it defines the length of the field; oth-
erwise, the field length is determined by the length of the
first value assignment. This length is used for subsequent
assignments.
When the variable is reassigned, the field is either padded
to the left with blanks or truncated from the end.
The -R option turns off the -L option.
Page 55 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
-Z[num]
Right-justifies the value and pads it with leading zeros if
the first non-blank character is a digit and the -L option
has not been set. If num is non-zero, it defines the length
of the field; otherwise, the field length is determined by
the length of the first value assignment.
-f The names refer to function names rather than variable
names. The Korn shell stores the functions in the
.shhistory file. Consequently, you cannot display a func-
tion definition on the screen if .shhistory does not exist
or if the nolog option was not set when the function was
read. No assignments can be made, and the only other valid
options in combination with -f are:
-t Turns on execution tracing for the function.
-u Causes the function to be marked undefined. The FPATH
variable is searched to find the function definition
the next time the function is referenced.
-x Allows the function definition to remain in effect
across Korn shell scripts invoked by name. In other
words, the function is exported.
-i[num]
The variable is an integer. This option makes arithmetic
faster. If num is non-zero, it defines the output arithmetic
base; otherwise, the first assignment determines the output
base.
-l All uppercase characters are converted to lowercase. The -u
option is turned off.
-r The given variables are marked readonly, which means that
their values cannot be changed by subsequent assignment.
-t Tags the variables. Tags are user-definable and have no spe-
cial meaning to the Korn shell.
-u All lowercase characters are converted to uppercase charac-
ters. The -l option is turned off.
-x The given names are marked for automatic export to any new
environment.
ulimit [option ...] Format 1
ulimit [option ...] limit Format 2
ulimit can be used to list or set resource limits for your
processes. These limits are described in getrlimit(2).
Page 56 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
Format 1: List resource limits
ulimit lists the limits specified by option (see below) on stan-
dard output. The options may be combined in any order. The -a
option can be used to list all limits.
Format 2: Set resource limits
ulimit sets the limit specified by the option to limit. The
string unlimited requests the largest valid limit. Limits may be
set for only one resource at a time. Any user may set a soft
limit to any value below the hard limit. Any user may lower a
hard limit, but only the system administrator may raise a hard
limit [see su(1)].
The -H option specifies a hard limit. The -S option specifies a
soft limit. If neither option is specified, ulimit will set both
limits and list the soft limit.
The following options specify the resource whose limits are to be
listed or set. If no option is given, -f is assumed.
-c maximum core file size (in 512-byte blocks)
-d maximum size of data segment or heap (in Kbytes)
-f maximum file size (in 512-byte blocks)
-n maximum number of file descriptors plus 1
-s maximum size of stack segment (in Kbytes)
-t maximum CPU time (in seconds)
-v maximum size of virtual memory (in Kbytes)
umask [-S] [--] [mask]
umask sets or displays the current user file-creation mode mask.
If mask is omitted, the current value of the mask is written to
standard output. If a mask is specified, the mode mask is set
accordingly [see umask(1)]. mask can be either an octal number or
a symbolic value as described in chmod(1). If a symbolic value is
used, the new umask value is the complement of the result of
applying mask to the complement of the previous umask value.
-S Symbolic output in the format u=rightsuser, g=rightsgroup,
o=rightsother, whereby rights* is output as a combination
of the letters r, w, x.
-- If mask begins with a minus sign (-), the end of the
command-line options must be marked with --.
Page 57 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
unalias [-a] [name ...]
The named variables are removed from the alias list. If -a is
specified, all alias definitions are removed from the alias
table.
unset [-fv] name ...
The named variables are unassigned, i.e. their values and attri-
butes are erased. Read-only variables cannot be unset. Unsetting
ERRNO, LINENO, MAILCHECK, OPTARG, OPTIND, RANDOM, SECONDS, TMOUT
and removes their special meaning even if they are subsequently
assigned to. If the -f option is set, then the names refer to
function names, while in the case of -v they refer to the names
of variables.
+wait [job ...]
Waits for the specified job to terminate and report its exit
status. If job is not given, all currently active child processes
are waited for. The exit status of wait is that of the process
waited for. The format of job is as described under Jobs above.
whence [-pv] name ...
Indicates how each name would be interpreted if used as a command
name.
-v produces a more detailed report.
-p does a path search for name even if name is an alias, a
function, or a reserved word.
EXIT STATUS
The Korn shell normally returns the exit status of the last command
executed [see exit(1)].
1-125 Errors detected by the Korn shell, such as syntax errors, cause
it to return a non-zero exit status. If the Korn shell is being
used non-interactively, execution of the shell script is
aborted. Runtime 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
one, the line number is also printed in square brackets ([...])
after the command or function name.
126 The specified command exists, but could not be invoked.
127 The specified command could not be found by a non-interactive
shell.
FURTHER DIFFERENCES BETWEEN KORN SHELL - BOURNE SHELL
Since the Korn shell (ksh) and Bourne shell (sh) do not always behave
in the same way, the shell scripts also behave differently (see also
chapter Major Korn shell features not available in the Bourne shell
above).
Page 58 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
The following differences are known to exist at present:
1. If an exit is executed in a loop (for, until, while) and if the
input is read from a file, the Bourne shell quits the loop and the
Korn shell ends the script. Example of a while loop:
while read i
do
echo $i
if [ "$i" = "end" ]
then
exit 199
fi
done < inputfile
retflag=$?
echo $retflag
2. The Shell cd built-in behaves differently when metacharacters (*,
?) are used.
The current directory contains the subdirectories dircmd, dirlib
and dirhead.
cd dir*
The Korn shell generates the error message "bad argument count",
and the Bourne shell changes to the directory with the first pat-
tern matching (dircmd).
3. Call parameters are interpreted differently.
Invoking at the shell level:
((/tmp/shelltest add "-po XON") 2>&1)
Korn shell:
$1 = add
$2 = -po
$1 = XON
Bourne shell:
$1 = add
$2 = -po XON
4. In the Korn shell, time is a keyword at the start of a line (like
if, then etc.; cf. above, section Reserved words). In the Bourne
shell, on the other hand, time is a standard user command
(/usr/bin). The following deviations regarding time can be dis-
tinguished.
Page 59 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
The behavior of the
time pipeline
command varies. In the case of the Korn shell, the pipeline com-
mands are executed and then the elapsed time, the user and system
time for these commands are reported as statistics to standard
error.
With the Bourne shell, time is only executed for the first pipeline
command and the statistics are output beforehand.
Thus in the case of the Korn shell, if you issue the
time ls | pg
call, you will first see the output of ls and the pg input must
then be performed. It is only when everything has ended that the
statistics are output for ls and pg.
With the Bourne shell, the statistics are output first, followed by
the output of ls and the input for pg [cf. xpg4sh(1)].
5. The Korn shell supplies the function name for a shell script func-
tion in $0 while the Bourne shell also supplies the name of the
shell script.
For example, in the following shell script called test.sh:
dummy()
{
echo $0
}
dummy
The Korn shell echoes dummy, the Bourne shell echoes test.sh [cf.
xpg4sh(1)].
FILES
/etc/passwd
/etc/profile
/etc/suidprofile
$HOME/.profile
/tmp/sh*
/dev/null
Page 60 Reliant UNIX 5.44 Printed 11/98
ksh(1) ksh(1)
SEE ALSO
cat(1), cd(1), chmod(1), colon(1), cut(1), dot(1), echo(1), env(1),
newgrp(1), paste(1), stty(1), test(1), umask(1), vi(1), xpg4sh(1),
dup(2), exec(2), fork(2), getrlimit(2), ioctl(2), lseek(2), pipe(2),
signal(2), ulimit(2), umask(2), wait(2), rand(3C), a.out(4),
profile(4), environ(5), signal(5).
M. I. Bolski and D. G. Korn, The Korn-Shell Command and Programming
Language
Page 61 Reliant UNIX 5.44 Printed 11/98