xref: /386bsd/usr/local/man/man1/ksh.1 (revision a2142627)
ksh.1,v 1.1.1.1 1993/05/21 05:37:44 cgd Exp
.nr OJ 1 \" Job Control .nr OE 1 \" Command Editing .nr OB 1 \" BSD enhanced ulimit options
KSH 1 "April 1992"
NAME
ksh - Bourne / Korn Shell (Public Domain)
SYNOPSIS
ksh [-st] [-c command] [file [argument ...]]
INTRODUCTION
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.

DESCRIPTION
Command syntax
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 separate words and tokens.

In the following syntax, { ... }? indicates an optional thing, { ... }* indicates zero or more repetitions, { ... | ... } indicates alternatives.

\\$1

..

statement:
.S "( list )" .S "{ list ; }" .S "for name { in { word }* }? do list ; done" .S "{ while | until } list ; do list ; done" .S "if list ; then list ; { elif list ; then list ; }* { else list ; }?fi" .S "case name in { ( word { | word } ) list ;; }* esac" .S "function name { list ; }" .S "name () { list ; }" .S "time pipe" The opening parenthesis of the pattern is optional. Redirection may occur at the beginning or end of a statement.
command:
.S "{ name=word }* { word }*" Redirection may occur anywhere in a command.
list:
.S "cond" .S "cond ; list" .S "cond & list"
cond:
.S "pipe" .S "pipe && cond" .S "pipe || cond"
pipe:
.S "statement { | statement }*"
Alias expansion
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.
Shell variables
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 profile 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 determin what command line edit mode to use. Note that this is not strictly ksh compatible behaviour.
IFS
Internal field separator, used during substitution and the read command.
HOME
The default directory for the cd 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.
COLUMNS
The width to use for the commandline editing (emacs mode only).
HISTFILE
The name of the file to read initial history from. The default is "$HOME/.pdksh_hist". When the shell exits it will overwrite this file with its current history. This behaviour will almost certainly cause grief when multiple shells are being run by the same user. Making the file read-only will allow each shell to start with a set history and avoid overwriting the file.
HISTSIZE
The number of history items to save in HISTFILE.
Substitution
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 number 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 # substition, but deleting from the end of the value.
Expressions
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 following operators:

"== != <= < > >= + - * / % ! ( )"
Command execution
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 \(dg 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 parameter 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 previous working directory is used. If path is .., the shell changes directory to the parent directory, 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 current 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 specifing 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 specified, the $FCEDIT editor, then executed by the shell.
"fc -e - [-g] [old=new] [command]"
Re-execute the selected command (the previous command by default) after performing the optional substitution 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 expressions 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 \eb, \ef, \en, \er, \et, \ev, and \e### (# is an octal digit). \ec 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]"

\t\\$1\t\\$2\t\\$3 ..

"set [\(+-[a-z]] [\(+-o keyword] ..."
Set (-) or clear (+) a shell option: .O -a allexport "all new variable are created with export attribute" .O -e errexit "exit on non-zero status [incorrect]" .O "" bgnice "background jobs are run with lower priority" .O "" emacs "BRL emacs-like line editing"\} .O "" ignoreeof "shell will not exit of EOF, must use exit" .O -k keyword "variable assignments are recognized anywhere in command" .O "" markdirs "[not implemented]" .O -m monitor "job control enabled (default for interactive shell)" .O -n noexec "compile input but do not execute (ignored if interactive)" .O -f noglob "don't expand filenames" .O -u nounset "dollar expansion of unset variables is an error" .O -v verbose "echo shell commands on stdout when compiling" .O -h trackall "add command pathnames to hash table" .O "" vi "VI-like line editing" .O -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 variables. 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. \t-i\tThe variable's value is stored as an integer.

\t-x\tThe variable is exported to the enviroment.

\t-r\tThe variable is read-only cannot be reassigned a value.

\t-t\tTrace (not implemented).

\t-f\tList functions instead of variable. .IP "ulimit [-f] [value]"

"ulimit \*(OK -\*(OZ \*(CK \*(OK n \*(CK"

"\w'-- 'u" 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 written 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
Job control features are enabled by the -m or -o monitor flags. When job control is enabled, and the system supports job control, background commands and foreground commands that have been stopped (usually by a SIGTSTP signal generated by typing ^Z\^ ) are placed into separate individual "process groups" . The following commands are used to manipulate these process groups:

0

"\w'kill \*(OK job \*(CK 'u" 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 \*(OK job \*(CK Resume the stopped foreground job in the foreground. If the process group n is not specified then the ``current job'' is resumed.

bg \*(OK job \*(CK 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.

0

"\w'bg \*(OK n \*(CK 'u" %+ ( %- ) 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 functions as above, and you will be informed when background jobs complete. Fg and bg are not availiable.

"Interactive Input Line Editing"
When the emacs option is set, interactive input line editing 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 particular control characters when the shell is invoked; these bindings can be changed using the following commands:

0

2i bind The current bindings are listed.

bind \*(OK string \*(CK = \*(OK editing-command \*(CK The specified "editing command\^" is bound to the given string , which should consist 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 '^XC'=backward-char

will bind the arrow keys on an ANSI terminal. Of course some escape sequences won't work out quite that nicely.

bind -m \*(OK string \*(CK = \*(OK substitute \*(CK The specified input string will afterwards 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 character is written as \s-1^[\s0\|), then the editing function performed is decribed. Note that "editing command" names are used only with the bind command. Furthermore, many "editing commands" are useful only on terminals with a visible cursor. The default bindings were chosen to resemble corresponding EMACS key bindings. The users tty characters (eg. erase) are bound to reasonable substitutes.

0

"\w'delete-word-backward ^[\|ERASE 'u" 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 character 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 completion, unless it is a directory name in which case / is postpended. If there is no hashed command or file name with the current 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 partial word up to the cursor as its prefix, as in the complete command described above.

copy-last-arg ^[\|_ The last word of the previous 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 performed.

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, columnated list of hashed command names or file names (if any) that can complete the partial word containing the cursor. Directory names have / postpended to them, and executable file names are followed by \(** .

list-command ^X\|? Prints a sorted, columnated list of hashed command names (if any) that can complete the partial word containing the cursor.

list-file Prints a sorted, columnated list of file names (if any) that can complete the partial word containing 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 current line for the next keyboard character.

search-history ^R Enter incremental search mode. The internal history 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). Successive search-history commands continue searching 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 current line for the next keyboard character.

stuff ^T\} stuff\} On systems supporting it, pushes the bound character back onto the terminal input where it may receive special processing by the terminal handler. ^T ``mini-systat'' feature, for example.\}

stuff-reset Acts like stuff\^ , then aborts input the same as an interrupt.

transpose-chars\} transpose-chars ^T\} Exchanges the two characters on either side of the cursor, or the two previous characters if the cursor is at end of line.

up-history ^P Scrolls the history buffer backward one line (earlier).

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 previous killed text string.

FILES
~/.profile

/etc/profile

SEE ALSO
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 published)," Morris Bolsky and David Korn.

AUTHORS
Based on the public domain 7th edition Bourne shell.

System V and Korn modifications by Eric Gisin, with contributions by Ron Natalie, Arnold Robbins, Doug Gwyn, Erik Baalbergen, AT&T (getopt(3)), John McMillan and Simon Gerraty.

DIFFERENCES FROM AT&T VERSION
The select statement is not implemented. Variable arrays are not implemented. Variable attributes other than integer 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 version. Korn evaluates expressions differently [elaborate].
BUGS
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 1 "January 1988" "Korn shell"

\\$1\t\\$2 ..

NAME
test - test condition (Korn and 8th edition)
SYNOPSIS
test expression

[ expression ]

DESCRIPTION
Test\f evalutates 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.

.X "-r file" "file exists and is readable" .X "-w file" "file exists and is writable" .X "-x file" "file exists and is executable" .X "-f file" "file is a regular file" .X "-d file" "file is a directory" .X "-c file" "file is a character special device" .X "-b file" "file is a block special device" .X "-p file" "file is a named pipe" .X "-u file" "file mode has setuid bit" .X "-g file" "file mode has setgid bit" .X "-k file" "file mode has sticky bit" .X "-s file" "file is not empty" .X "-L file" "file is a symbolic link" .X "-S file" "file is a socket" .X "file -nt file" "first file is newer than second file" .X "file -ot file" "first file is older than second file" .X "file -ef file" "first file is the same file as second file" .X "-t filedes" "file descriptor is a tty device"
.X "string" "string is not null" .X "-z string" "string is null" .X "-n string" "string is not null" .X "string = string" "strings are equal" .X "string != string" "strings are not equal"
.X "number -eq number" "numbers compare equal" .X "number -ne number" "numbers compare not equal" .X "number -ge number" "numbers compare greater than or equal" .X "number -gt number" "numbers compare greater than" .X "number -le number" "numbers compare less than or equal" .X "number -lt number" "numbers compare less than"

The above basic expressions may be combined with the following operators.

.X "expr -o expr" "logical or" .X "expr -a expr" "logical and" .X "! expr" "logical not" .X "( expr )" "grouping"
AUTHOR
Erik Baalbergen. Modified by Arnold Robbins. .rn LP P
GETOPTS 1 "January 1988" "Korn shell"
NAME
getopts - parse command options
SYNOPSIS
getopts optstring name [arg ...]
DESCRIPTION
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 \s-1WARNING\s0 , 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 \s-1OPTIND\s0 . Whenever the shell or a shell procedure is invoked, \s-1OPTIND\s0 is initialized to 1 .

When an option requires an option-argument, getopts places it in the shell variable \s-1OPTARG\s0 .

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 \s-1WARNINGS\s0 , below).

EXAMPLE
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:

.ss 18
while getopts abo: c
do
 case $c in
 a\(bvb) FLAGS=$FLAGS$c;;
 o) OARG=$OPTARG;;
 \e?) echo $USAGE 1>&2
 exit 2;;
 esac
done
shift OPTIND-1
.ss 12

This code will accept any of the following as equivalent:

.ss 18
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
.ss 12
SEE ALSO
intro(1), sh(1).

getopt(3C) in the "Programmer's Reference Manual" .

"UNIX System V Release 3.0 Release Notes" .

WARNING
Although the following command syntax rule (see intro (1)) relaxations are permitted under the current implementation, they should not be used because they may not be supported in future releases of the system. As in the \s-1EXAMPLE\s0 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 \s-1OPTIND\s0 or parsing different sets of arguments may lead to unexpected results.

DIAGNOSTICS
getopts prints an error message on the standard error output when it encounters an option letter not included in optstring .