ksh
Bourne / Korn Shell (Public Domain)
TEST
SYNOPSIS
DESCRIPTION
AUTHOR
GETOPTS
NAME
SYNOPSIS
DESCRIPTION
EXAMPLE
SEE ALSO
WARNING
DIAGNOSTICS
ksh [-st] [-c command] [file [argument ...]]
This document only summarizes the System V, release 2
shell features. All of the System V features except for
``restricted mode'' are implemented. See also the BUGS
section.
Features of the Korn shell are described in more detail.
Only a subset of the Korn shell features are currently
implemented.
The ``#'' character begins a one-line comment, unless the
``#'' occurs inside a word. The tokens ``;'', ``|'',
``&'', ``;;'', ``||'', ``&&'', ``('', and ``)'' stand by
themselves. A word is a sequence of any other non-
whitespace characters, which may also contain quoted
strings (quote character are ``''', ``"'', ```'', or a
matching ``${ }'' or ``$( )'' pair). A name is an
unquoted word made up of letters, digits, or ``_''. Any
number of whitespace characters (space and tab) may sepa-
rate words and tokens.
In the following syntax, { ... }? indicates an optional
thing, { ... }* indicates zero or more repetitions, { ...
| ... } indicates alternatives.
statement:
( list )
{ list ; }
for name { in { word }* }? do list ; done
select name { in { word }* }? do list ; done
{ while | until } list ; do list ; done
if list ; then list ; { elif list ; then list ; }*
{ else list ; }?fi
case name in { ( word { | word } ) list ;; }* esac
function name { list ; }
name () { list ; }
time pipe
The opening parenthesis of the pattern is optional.
Redirection may occur at the beginning or end of a
statement.
command:
{ name=word }* { word }*
Redirection may occur anywhere in a command.
list:
cond
cond ; list
cond & list
cond:
pipe
pipe && cond
pipe || cond
pipe:
statement { | statement }*
The select statement provides an automatic method of pre-
senting the user with a menu selection from several
options. The words given in the list are printed on stan-
dard error, each preceded by a number. Typing the number
on standard input sets the variable name to the word that
was selected. The data that was typed is preserved in a
variable called REPLY. The contents of the loop are then
executed using the selected value. A new prompt PS3 is
used to indicate that a number should be typed in to
choose a value from the menu.
Menus will continue to be presented until an interrupt is
received or end-of-file is typed on input.
Alias expansion occurs when the first word of a statement
is a defined alias, except when that alias is already
being expanded. It also occurs after the expansion of an
alias whose definition ends with a space.
Csh provides a filename expansion method known as alterna-
tion. This has been added into this version of ksh. When
performing filename substitution, you can get the shell to
create a set of strings for you. For example,
`exampl{a,b,c,d,e}' will expand to ``exampla examplb exam-
plc exampld example''. A comma separated set of strings
in curly braces will be expanded into a set of strings
that are passed into the command. The strings are not
sorted.
The following standard special variables exist: !, #, $,
-, ?.
_ In interactive use this parameter is set to the
last word of the previous command. When a command
is executed this parameter is set to the full path
of the command and placed in the environment for
the command. See also MAILPATH.
CDPATH The search path for the cd command.
ENV If this variable is set at start-up (after any pro-
file files are executed), the expanded value is
used as shell start-up file. It typically contains
function and alias definitions.
FCEDIT The editor used by the fc command. During startup
the shell checks the value of FCEDIT, EDITOR and
finally VISUAL to try and determine what command
line edit mode to use. Note that this is not
strictly ksh compatible behaviour.
COLUMNS
The width to use for the commandline editing (emacs
mode only).
HISTFILE
The name of the file used to store history. If
defined, history will be loaded from this file on
startup. Also, several invocations of the shell
running on the same machine will share history if
their HISTFILE variables all point at the same
file.
HISTSIZE
The number of commands normally stored for history,
default 128.
HOME The default directory for the cd command.
IFS Internal field separator, used during substitution
and the read command.
MAIL If set, the user will be informed of the arrival of
mail in the named file. This variable is ignored
if the MAILPATH variable is set.
MAILCHECK
How often, in seconds, the shell will check for
mail in the file(s) specified by MAIL or MAILPATH.
If 0, the shell checks before each prompt. The
default is 600 seconds.
MAILPATH
A list of files to be checked for mail. The list
is colon separated, and each file may be followed
by a ? and a message to be printed if new mail has
arrived. Command and parameter substitution is
performed on the message, and the parameter $_ is
set to the name of the file. The default message
is ``you have mail in $_''.
PATH The search path for executable commands and .'d
files.
PPID The process number of the parent of the shell.
PS1 PS2
PS1 is the primary prompt for interactive shells.
Dollar substitution is performed, and ! is replaced
with the command number (see fc).
PWD OLDPWD
The current and previous working directories.
RANDOM A random integer. The random number generator may
be seeded by assigning an integer value to this
variable.
SECONDS
The number of seconds since the shell timer was
started or reset. Assigning an integer value to
this variable resets the timer.
In addition to the System Vr2 substitutions, the following
are available.
$(command)
Like `command`, but no escapes are recognized.
$(<file)
Equivalent to $(cat file), but without forking.
${#var}
The length of the string value of var, or the num-
ber of arguments if var is * or @.
${var#pattern} ${var##pattern}
If pattern matches the beginning of the value of
var, the matched text is deleted from the result of
substitution. A single # results in the shortest
match, two #'s results in the longest match.
${var%pattern} ${var%%pattern}
Like # substitution, but deleting from the end of
the value.
Expressions can be used with the let command, as numeric
arguments to the test command, and as the value of an
assignment to an integer variable.
Expression may contain alpha-numeric variable identifiers
and integer constants and may be combined with the follow-
ing operators:
== != <= < > >= + - * / % ! ( )
After evaluation of keyword assignments and arguments, the
type of command is determined. A command may execute a
shell function, a shell built-in, or an executable file.
Any keyword assignments are then performed according to
the type of command. In function calls assignments are
local to the function. Assignments in built-in commands
marked with a |- persist, otherwise they are temporary.
Assignments in executable commands are exported to the
sub-process executing the command.
Even on systems where the exec() family does not support
#! notation for scripts, ksh can be configured to fake
it.
There are several built-in commands.
: Only expansion and assignment are performed. This
is the default if a command has no arguments.
. file Execute the commands in file without forking. The
file is searched in the directories of $PATH.
Passing arguments is not implemented.
alias [name=value ...]
Without arguments, alias lists all aliases and
their values. For any name without a value, its
value is listed. Any name with a value defines an
alias, see "Alias Expansion" above. Korn's tracked
aliases are not implemented, but System V command
hashing is (see "hash").
alias -d [name=value ...]
Directory aliases for tilde expansion, eg.
alias -d fac=/usr/local/usr/facilities
cd ~fac/bin
break [levels]
builtin command arg ...
Command is executed as a built-in command.
cd [path]
Set the working directory to path. If the parame-
ter CDPATH is set, it lists the search path for the
directory containing path. A null path means the
current directory. If path is missing, the home
directory ($HOME) is used. If path is -, the pre-
vious working directory is used. If path is ..,
the shell changes directory to the parent direc-
tory, as determined from the value of PWD. The PWD
and OLDPWD variables are reset.
cd old new
The string new is substituted for old in the cur-
rent directory, and the shell attempts to change to
the new directory.
continue [levels]
echo ...
Echo is replaced with the alias echo='print' in the
Korn shell.
eval command ...
exec command arg ...
The executable command is executed without forking.
If no arguments are given, any IO redirection is
permanent.
exit [status]
fc [-e editor] [-lnr] [first [last]]
First and last select commands. Commands can be
selected by history number, or a string specifying
the most recent command starting with that string.
The -l option lists the command on stdout, and -n
inhibits the default command numbers. The -r
option reverses the order of the list. Without -l,
the selected commands can be edited by the editor
specified with the -e option, or if no -e is speci-
fied, the $FCEDIT editor, then executed by the
shell.
fc -e - [-g] [old=new] [command]
Re-execute the selected command (the previous com-
mand by default) after performing the optional sub-
stitution of old with new. If -g is specified, all
occurrences of old are replaced with new. This
command is usually accessed with the predefined
alias r=``fc -e -''.
getopts
See the attached manual page.
hash [-r] [name ...]
Without arguments, any hashed executable command
pathnames are listed. The -r flag causes all
hashed commands to be removed. Each name is
searched as if it were a command name and added to
the hash table if it is an executable command.
kill [-signal] process ...
Send a signal (TERM by default) to the named
process. The signal may be specified as a number
or a mnemonic from <signal.h> with the SIG prefix
removed.
let [expression ...]
Each expression is evaluated, see "Expressions"
above. A zero status is returned if the last
expression evaluates to a non-zero value, otherwise
a non-zero status is returned. Since may expres-
sions need to be quoted, (( expr )) is syntactic
sugar for let "expr".
print [-nreun] [argument ...]
Print prints its arguments on the standard output,
separated by spaces, and terminated with a newline.
The -n option eliminates the newline.
By default, certain C escapes are translated.
These include \b, \f, \n, \r, \t, \v, and \### (#
is an octal digit). \c is equivalent to the -n
option. This expansion may be inhibitted with the
-r option, and may be re-enabled with the addition
of the -e option.
read [-run] name ...
The first variable name may be of the form
name?prompt.
readonly [name ...]
return [status]
set [+-[a-z]] [+-o keyword] ...
Set (-) or clear (+) a shell option:
-a allexport all new variable are
created with export attribute
-e errexit exit on non-zero sta-
tus [incorrect]
bgnice background jobs are
run with lower priority
emacs BRL emacs-like line
editing
ignoreeof shell will not exit
of EOF, must use exit
-k keyword variable assignments
are recognized anywhere in command
markdirs [not implemented]
-m monitor job control enabled
(default for interactive shell)
-n noexec compile input but do
not execute (ignored if interactive)
-f noglob don't expand file-
names
-u nounset dollar expansion of
unset variables is an error
-v verbose echo shell commands
on stdout when compiling
-h trackall add command pathnames
to hash table
vi VI-like line editing
-x xtrace echo simple commands
while executing
set [--] arg ...
Set shell arguments.
shift [number]
test See the attached manual page.
times
trap [handler] [signal ...]
typeset [+-irtx] [name[=value] ...]
If no arguments are given, lists all variables and
their attributes.
If options but no names are given, lists variables with
specified attributes, and their values if unless ``+'' is
used.
If names are given, set the attributes of the named vari-
ables. Variables may also be assigned a value. If used
inside a function, the created variable are local to the
function.
The attributes are as follows. -iThe variable's value is
stored as an integer.
-xThe variable is exported to the environment.
-rThe variable is read-only cannot be reassigned a value.
-tTrace (not implemented).
-fList functions instead of variable.
ulimit [ -<OZ> ] [ n ]
-c Impose a size limit of n blocks on the size of
core dumps.
-d Impose a size limit of n blocks on the size of
the data area.
-f Impose a size limit of n blocks on files writ-
ten by the shell and its child processes
(files of any size may be read).
-m Impose a soft limit of n blocks on the size of
physical memory.
-t Impose a time limit of n seconds to be used by
each process.
If no option is given, -f is assumed. If n is
omitted, the current limit is printed. As far as
ulimit is concerned, a ``block'' is 512 bytes.
You may lower your own resource limit, but only a
super-user (see su(1M)) can raise a limit.
umask [value]
unalias name ...
The aliases for the given names are removed.
unset [-f] name ...
wait [process-id]
whence [-v] name ...
For each name, the type of command is listed. The
-v flag causes function and alias values to be
listed.
Job control features are enabled by the -m or -o monitor
flags. When job control is enabled, and the system sup-
ports job control, background commands and foreground com-
mands that have been stopped (usually by a SIGTSTP signal
generated by typing ^Z) are placed into separate individ-
ual process groups. The following commands are used to
manipulate these process groups:
jobs Display information about the controlled
jobs. The job number is given preceeded by
a percent sign, followed by a plus sign if
it is the ``current job'', or by a minus
sign if it is the ``previous job'', then
the process group number for the job, then
the command.
kill [-signal] job ...
Send a signal (TERM by default) to the
named job process group.
fg [ job ] Resume the stopped foreground job in the
foreground. If the process group n is not
specified then the ``current job'' is
resumed.
bg [ job ] Resume the stopped foreground job in the
background. If the process group n is not
specified then the ``current job'' is
resumed.
The fg, bg, kill, and wait commands may refer to jobs with
the following ``percent'' sequences. The percent sign is
optional with the fg and bg commands.
%+(%-) If there is a ``current job'' (``previous
job''), then that job is selected.
%n If the specified job number is one of the known
jobs, then that job is selected.
%string If the string matches the initial part of a
job's command, then that job is selected.
%?string As above, but the string may match any portion
of the command.
If the system does not support job control, monitor mode
enables job reporting. The jobs and kill commands func-
tions as above, and you will be informed when background
jobs complete. Fg and bg are not available.
When the emacs option is set, interactive input line edit-
ing is enabled. This mode is slightly different from the
emacs mode in AT&T's KornShell. In this mode various
editing commands (typically bound to one or more control
characters) cause immediate actions without waiting for a
new-line. Several editing commands are bound to particu-
lar control characters when the shell is invoked; these
bindings can be changed using the following commands:
bind The current bindings are listed.
bind [ string ] = [ editing-command ]
The specified editing command is bound
to the given string, which should con-
sist of a control character (which may
be written using ``caret notation''
^x), optionally preceded by one of the
two prefix characters. Future input
of the string will cause the editing
command to be immediately invoked.
Note that although only two prefix
characters (normal ESC and ^X) are
supported, some multi-character
sequences can be supported:
bind '^[['=prefix-2
bind '^XA'=up-history
bind '^XB'=down-history
bind '^XC'=forward-char
bind '^XD'=backward-char
will bind the arrow keys on an ANSI
terminal, or xterm. Of course some
escape sequences won't work out quite
that nicely.
bind -m [ string ] = [ substitute ]
The specified input string will after-
wards be immediately replaced by the
given substitute string, which may
contain editing commands.
The following editing commands are available; first the
command name is given followed by its default binding (if
any) using caret notation (note that the ASCII ESC charac-
ter is written as ^[), then the editing function performed
is described. Note that editing command names are used
only with the bind command. Furthermore, many editing
commands are useful only on terminals with a visible cur-
sor. The default bindings were chosen to resemble corre-
sponding EMACS key bindings. The users tty characters
(eg. erase) are bound to reasonable substitutes.
abort ^G Useful as a response to a
request for a search-
history pattern in order
to abort the search.
auto-insert Simply causes the charac-
ter to appear as literal
input. (Most ordinary
characters are bound to
this.)
backward-char ^B Moves the cursor backward
one character.
backward-word ^[b Moves the cursor backward
to the beginning of a
word.
beginning-of-line ^A Moves the cursor to the
beginning of the input
line (after the prompt
string).
complete ^[^[ Automatically completes as
much as is unique of the
hashed command name or the
file name containing the
cursor. If the entire
remaining command or file
name is unique a space is
printed after its comple-
tion, unless it is a
directory name in which
case / is postpended. If
there is no hashed command
or file name with the cur-
rent partial word as its
prefix, a bell character
is output (usually causing
a ``beep'').
complete-command ^X^[ Automatically completes as
much as is unique of the
hashed command name having
the partial word up to the
cursor as its prefix, as
in the complete command
described above. Only
command and function names
seen since the last hash
-r command are available
for completion; the hash
command may be used to
register additional names.
complete-file ^[^X Automatically completes as
much as is unique of the
file name having the par-
tial word up to the cursor
as its prefix, as in the
complete command described
above.
copy-last-arg ^[_ The last word of the pre-
vious command is inserted
at the cursor. Note I/O
redirections do not count
as words of the command.
delete-char-backward ERASE Deletes the character
before the cursor.
delete-char-forward Deletes the character
after the cursor.
delete-word-backward ^[ERASE Deletes characters before
the cursor back to the
beginning of a word.
delete-word-forward ^[d Deletes characters after
the cursor up to the end
of a word.
down-history ^N Scrolls the history buffer
forward one line (later).
Each input line originally
starts just after the last
entry in the history
buffer, so down-history is
not useful until either
search-history or up-
history has been per-
formed.
end-of-line ^E Moves the cursor to the
end of the input line.
eot ^_ Acts as an end-of-file;
this is useful because
edit-mode input disables
normal terminal input
canonicalization.
eot-or-delete ^D Acts as eot if alone on a
line; otherwise acts as
delete-char-forward.
exchange-point-and-mark ^X^X Places the cursor where
the mark is, and sets the
mark to where the cursor
was.
forward-char ^F Moves the cursor forward
one position.
forward-word ^[f Moves the cursor forward
to the end of a word.
kill-line KILL Deletes the entire input
line.
kill-to-eol ^K Deletes the input from the
cursor to the end of the
line.
kill-region ^W Deletes the input between
the cursor and the mark.
list ^[? Prints a sorted, colum-
nated list of hashed com-
mand names or file names
(if any) that can complete
the partial word contain-
ing the cursor. Directory
names have / postpended to
them, and executable file
names are followed by *.
list-command ^X? Prints a sorted, colum-
nated list of hashed com-
mand names (if any) that
can complete the partial
word containing the cur-
sor.
list-file Prints a sorted, colum-
nated list of file names
(if any) that can complete
the partial word contain-
ing the cursor. File type
indicators are postpended
as described under list
above.
newline ^J and ^M Causes the current input
line to be processed by
the shell. (The current
cursor position may be
anywhere on the line.)
newline-and-next ^O Causes the current input
line to be processed by
the shell, and the next
line from history becomes
the current line. This is
only useful after an up-
history or search-history.
no-op QUIT Does nothing.
prefix-1 ^[ Introduces a 2-character
command sequence.
prefix-2 ^X Introduces a 2-character
command sequence.
quote ^^ The following character is
taken literally rather
than as an editing
command.
redraw ^L Reprints the prompt string
and the current input
line.
search-character ^] Search forward in the cur-
rent line for the next
keyboard character.
search-history ^R Enter incremental search
mode. The internal his-
tory list is searched
backwards for commands
matching the input. An
initial ``^'' in the
search string anchors the
search. The escape key
will leave search mode.
Other commands will be
executed after leaving
search mode (unless of
course they are prefixed
by escape, in which case
they will almost certainly
do the wrong thing). Suc-
cessive search-history
commands continue search-
ing backward to the next
previous occurrence of the
pattern. The history
buffer retains only a
finite number of lines;
the oldest are discarded
as necessary.
set-mark-command ^]<space> Search forward in the cur-
rent line for the next
keyboard character.
stuff On systems supporting it,
pushes the bound character
back onto the terminal
input where it may receive
special processing by the
terminal handler.
stuff-reset Acts like stuff, then
aborts input the same as
an interrupt.
transpose-chars ^T Exchanges the two charac-
ters on either side of the
cursor, or the two previ-
ous characters if the cur-
sor is at end of line.
up-history ^P Scrolls the history buffer
backward one line (ear-
lier).
yank ^Y Inserts the most recently
killed text string at the
current cursor position.
yank-pop ^[y Immediately after a yank,
replaces the inserted text
string with the next pre-
vious killed text string.
~/.profile
/etc/profile
Sh(1) on System V or Sun OS.
UNIX Shell Programming, Stephan G. Kochan, Patrick H.
Wood, Hayden.
KornShell: Command and Programming Language (not yet pub-
lished), Morris Bolsky and David Korn.
Based on the public domain 7th edition Bourne shell.
System V and Korn modifications by Eric Gisin, with con-
tributions by Ron Natalie, Arnold Robbins, Doug Gwyn, Erik
Baalbergen, AT&T (getopt(3)), John McMillan, Simon Gerraty
and Peter Collinson.
Csh-style alternations are implemented. Variable arrays
are not implemented. Variable attributes other than inte-
ger are not implemented. The ERR and EXIT traps are not
implemented for functions. Alias expansion is inhibited
at the beginning of an alias definition in the AT&T ver-
sion. Korn evaluates expressions differently [elaborate].
Interactive shells may occasionally hang while waiting for
a job in the BSD version.
The 8th bit is stripped in emacs mode.
Quoting double-quote (") characters inside back-quote (`)
inside double-quotes does not behave properly. Why are
you doing this?
The emacs mode can ``lose'' stty command done by the user.
Unsetting special variables may cause unexpected results.
Functions declared as having local scope really have
global scope.
Here documents inside functions do not work correctly.
Exit on error (set -e or set -o errexit) does not work
correctly.
test - test condition (Korn and 8th edition)
test expression
[ expression ]
Test evaluates the expression and returns zero status if
true, and non-zero status otherwise. It is normally used
as the controlling command of the if and while statements.
The following basic expressions are available.
-r file file exists and is
readable
-w file file exists and is
writable
-x file file exists and is
executable
-f file file is a regular
file
-d file file is a directory
-c file file is a character
special device
-b file file is a block spe-
cial device
-p file file is a named pipe
-u file file mode has setuid
bit
-g file file mode has setgid
bit
-k file file mode has sticky
bit
-s file file is not empty
-L file file is a symbolic
link
-S file file is a socket
file -nt file first file is newer
than second file
file -ot file first file is older
than second file
file -ef file first file is the
same file as second file
-t filedes file descriptor is a
tty device
string string is not null
-z string string is null
-n string string is not null
string = string strings are equal
string != string strings are not equal
number -eq number numbers compare equal
number -ne number numbers compare not
equal
number -ge number numbers compare
greater than or equal
number -gt number numbers compare
greater than
number -le number numbers compare less
than or equal
number -lt number numbers compare less
than
The above basic expressions may be combined with the fol-
lowing operators.
expr -o expr logical or
expr -a expr logical and
! expr logical not
( expr ) grouping
Erik Baalbergen. Modified by Arnold Robbins.
getopts - parse command options
getopts optstring name [arg ...]
getopts is used by shell procedures to parse positional
parameters and to check for legal options. It supports
all applicable rules of the command syntax standard (see
Rules 3-10, intro(1)). It should be used in place of the
getopt(1) command. (See the WARNING, below.)
optstring must contain the option letters the command
using getopts will recognize; if a letter is followed by a
colon, the option is expected to have an argument which
should be separated from it by white space.
Each time it is invoked, getopts will place the next
option in the shell variable name and the index of the
next argument to be processed in the shell variable
OPTIND. Whenever the shell or a shell procedure is
invoked, OPTIND is initialized to 1.
When an option requires an option-argument, getopts places
it in the shell variable OPTARG.
If an illegal option is encountered, ? will be placed in
name.
When the end of the options is encountered, getopts exits
with a non-zero exit status. The special option ``--''
may be used to delimit the end of the options.
By default, getopts parses the positional parameters. If
extra arguments (arg ...) are given on the getopts command
line, getopts will parse them instead.
So all new commands will adhere to the command syntax
standard described in intro(1), they should use getopts(1)
or getopt(3C) to parse positional parameters and check for
options that are legal for that command (see WARNINGS,
below).
The following fragment of a shell program shows how one
might process the arguments for a command that can take
the options a or b, as well as the option o, which
requires an option-argument:
while getopts abo: c
do
case $c in
a|b) FLAGS=$FLAGS$c;;
o) OARG=$OPTARG;;
\?) echo $USAGE 1>&2
exit 2;;
esac
done
shift OPTIND-1
This code will accept any of the following as equivalent:
cmd -a -b -o "xxx z yy" file
cmd -a -b -o "xxx z yy" -- file
cmd -ab -o "xxx z yy" file
cmd -ab -o "xxx z yy" -- file
intro(1), sh(1).
getopt(3C) in the Programmer's Reference Manual.
UNIX System V Release 3.0 Release Notes.
Although the following command syntax rule (see intro(1))
relaxations are permitted under the current implementa-
tion, they should not be used because they may not be sup-
ported in future releases of the system. As in the EXAM-
PLE section above, a and b are options, and the option o
requires an option-argument:
cmd -aboxxx file (Rule 5 violation: options with
option-arguments must not be grouped with other options)
cmd -ab -oxxx file (Rule 6 violation: there must be
white space after an option that takes an option-argument)
Changing the value of the shell variable OPTIND or parsing
different sets of arguments may lead to unexpected
results.
getopts prints an error message on the standard error out-
put when it encounters an option letter not included in
optstring.
radek@sci.muni.cz