ksh

NAME

ksh - public domain Korn shell

SYNOPSIS

ksh [+-abCefhikmnprsuvxX] [+-o option] [[-c command-string
	[command-name] | -s | file ] [argument ...]]

DESCRIPTION

The ksh(1) utility is a command interpreter that is intended for both interactive and shell script use. Its command language is a superset of the sh(1) shell language.

The version here contains the features of the ksh88 version, dated 11/16/88.

SHELL STARTUP

The following options can be specified only on the command line:

-c command-string
The shell executes the command or commands contained in command-string.
-i
Interactive mode.
-l
Login shell — see interactive mode.
-s
The shell reads commands from standard input; all non-option arguments are positional parameters.
-r
Restricted mode.

In addition to the options already mentioned, the options described in the set built-in command can also be used on the command line.

If neither the -c nor the -s option is specified, the first non-option argument specifies the name of a file from which the shell reads commands. If there are no non-option arguments, the shell reads commands from standard input. The name of the shell (that is, the contents of the $0 parameter ) is determined as follows:

If the -c option is used and there is a non-option argument, it is used as the name. If commands are being read from a file, the file is used as the name. Otherwise, the name with which the shell was called (that is, argv[0]) is used.

A shell is "interactive" if the -i option is used, or if both standard input and standard error are attached to a tty. An interactive shell has job control enabled (if available), ignores the INT, QUIT, and TERM signals, and prints prompts before reading input (see PS1 and PS2 parameters). For non-interactive shells, the trackall option is on by default (see set(1) command).

A shell is "restricted" if the -r option is used, or if either the basename of the name with which the shell is invoked or the SHELL parameter is rsh. The following restrictions apply after the shell processes any profile and $ENV files:

A shell is "privileged" if the -p option is used. The real user identifier (UID) or group identifier (GID) does not match the effective UID or GID (see getuid(2), getgid(2)). A privileged shell processes neither the $HOME/.profile nor the ENV parameter. Instead, it processes the file /etc/suid_profile. Clearing the privileged option causes the shell to set its effective UID (GID) to its real UID (GID).

If the basename of the name the shell is called with (that is, argv[0]) starts with -, or if the -l option is used, the shell is assumed to be a login shell. The shell then reads and executes the contents of /etc/profile and $HOME/.profile if they exist and are readable.

If the ENV parameter is set when the shell starts (or, in the case of login shells, after any profiles are processed), its value is subjected to parameter, command, arithmetic, and tilde substitution. The resulting file (if any) is read and executed. If ENV parameter is not set (and not null) and ksh(1) was compiled with the DEFAULT_ENV macro defined, the file named in that macro is included (after the above mentioned substitutions have been performed).

The exit status of the shell is 127 if the command file specified on the command line could not be opened, or non-zero if a fatal syntax error occurred during the execution of a script. In the absence of fatal errors, the exit status is that of the last command executed, or zero, if no command is executed.

COMMAND SYNTAX

The shell begins parsing its input by breaking it into "words." Words, which are sequences of characters, are delimited by unquoted white-space characters (space, tab, and newline) or meta-characters (< >, |, ;, &, (, and )). Aside from delimiting words, spaces and tabs are ignored; newlines usually delimit commands. Use the meta-characters to build the following tokens:

Token Use
<, <&, <<, >, >&, >>, and so on Specify redirections (see the section on input/output redirection)
| Create pipelines
|& Create co-processes (see the section on co-processes)
; Separate commands
& Create asynchronous pipelines
&& and || Specify conditional execution
;; Used in case statements
( .. ) Create subshells
(( ..)) Used in arithmetic expressions

White-space characters and and meta-characters can be quoted individually using a backslash (\), or in groups, using double (") or single(') quotes. The following characters are also treated specially by the shell, and must be quoted if they are to represent themselves: \, ", ', #, $, ', ~, {, }, *, ?, and [. The first three of these are the above mentioned quoting characters (see the section on quoting). #, if used at the beginning of a word, introduces a comment — everything after the # up to the nearest newline is ignored. $ introduces parameter, command, and arithmetic substitutions (see the section on substitution). ' introduces an old-style command substitution (see the section on substitution). ~ begins a directory expansion (see the section on tilde expansion). { and } delimit csh(1) style alternations (see the section on brace expansion). The characters *, ? and [ are used in file-name generation (see the section on file-name patterns).

As words and tokens are parsed, the shell builds commands, of which there are two basic types: simple commands, typically programs that are executed; and compound commands, such as for and if statements, grouping constructs, and function definitions.

A simple command consists of some combination of parameter assignments (see the section on parameters), input/output redirections (see the section on input/output redirection), and command words. The only restriction is that parameter assignments come before any command words. The command words, if there are any, define the command that is to be executed and its arguments. The command can be a shell built-in command, a function, or an external command; that is, a separate executable file that is located using the PATH parameter (see the section on command execution). Note that all command constructs have an exit status: for external commands, this is related to the status returned by wait(3). The exit status of other command constructs (built-in commands, functions, compound-commands, pipelines, lists, and such) are all well defined and are described where the construct is described. The exit status of a command consisting only of parameter assignments is that of the last command substitution performed during the parameter assignment, or zero if there were no command substitutions.

Commands can be chained together using the | token to form pipelines, in which the standard output of each command but the last is piped (see pipe(2)) to the standard input of the following command. The exit status of a pipeline is that of its last command. A pipeline can be prefixed by the ! reserved word, which causes the exit status of the pipeline to be logically complemented: if the original status was 0, the complemented status will be 1, and if the original status was not 0, the complemented status will be 0.

Lists of commands can be created by separating pipelines using any of the following tokens: &&, ||, &, |&, and ;. The first two are for conditional execution: cmd1 && cmd2 executes cmd2 only if the exit status of cmd1 is zero; || is the opposite — cmd2 is executed only if the exit status of cmd1 is non-zero. && and || have equal precedence, which is higher than that of &, |&, and ;, which also have equal precedence. The & token causes the preceding command to be executed asynchronously; that is, the shell starts the command, but does not wait for it to complete (the shell does keep track of the status of asynchronous commands — for more information about this, see "Job control"). If an asynchronous command is started when job control is disabled (that is, in most scripts), the command is started with signals INT and QUIT ignored, and with input redirected from /dev/null. (However, redirections specified in the asynchronous command have precedence.) The |& operator starts a co-process, which is special kind of asynchronous process (see the section on co-processes). Note that a command must follow the && and || operators; a command need not follow &, |&, or ;. The exit status of a list is that of the last command executed, except for asynchronous lists, which have an exit status of 0.

Compound commands are created using the following reserved words. These words are only recognized if they are unquoted and if they are used as the first word of a command (that is, they cannot be preceded by parameter assignments or redirections):

case else function then !
do esac if time [[
done fi in until {
elif for select while }

Some shells (but not this one) execute control structure commands in a subshell when one or more of their file descriptors are redirected, so any environment changes inside them might fail. To be portable, the exec statement should be used instead to redirect file descriptors before the control structure.

In the following compound-command descriptions, command lists (denoted as list) that are followed by reserved words must end with a semicolon (;), a newline or a (syntactically correct) reserved word. For example, the following are all valid:


{ echo foo; echo bar; }
{ echo foo; echo bar<newline>}
{ { echo foo; echo bar; } }

The next example is not valid:

{ echo foo; echo bar }
( list )
Execute list in a subshell. There is no implicit way to pass environment changes from a subshell back to its parent.
{ list }
Compound construct; list is executed, but not in a subshell. Note that { and } are reserved words, not meta-characters.
case word in [ [(] pattern [| pattern] ... ) list ;; ] ... esac
The case statement attempts to match word against one or more specified patterns; the list associated with the first successfully matched pattern is executed. Patterns used in case statements are the same as those used for file-name patterns, except that the restrictions regarding . and / are dropped. Note that any unquoted space before and after a pattern is stripped; any space with a pattern must be quoted. Both the word and the patterns are subject to parameter, command, tilde, and arithmetic substitution.

For historical reasons, open and close braces can be used instead of in and esac (for example, case $foo { *) echo bar; }). The exit status of a case statement is that of the executed list; if no list is executed, the exit status is zero.

for name [ in word ... term ] do list done
Where term is either a newline or a semicolon (;). For each word in the specified word list, the parameter name is set to the word, and list is executed. If in is not used to specify a word list, positional parameters ($1, $2, and so on) are used instead. For historical reasons, open and close braces can be used instead of do and done (such as for i; { echo $i; }). The exit status of a for statement is the last exit status of list; if list is never executed, the exit status is zero.
if list then list [elif list then list] ... [else list] fi
If the exit status of the first list is zero, the second list is executed; otherwise the list following the elif, if any, is executed with similar consequences. If all the lists following the if and each elif fail (that is, exit with non-zero status), the list following the else is executed. The exit status of an if statement is that of nonconditional list that is executed. If no nonconditional list is executed, the exit status is zero.
select name [ in word ... term ] do list done
Where term is either a newline or a semicolon (;). The select statement provides an automatic method of presenting the user with a menu and selecting from it. An enumerated list of the specified words is printed on standard error, followed by a prompt (PS3, normally '#? '). A number corresponding to one of the enumerated words is then read from standard input, name is set to the selected word (or is unset if the selection is not valid), REPLY is set to what was read (leading/trailing space is stripped), and list is executed. If a blank line (that is, zero or more IFS characters) is entered, the menu is reprinted without executing list. When list completes, the enumerated list is printed if REPLY is null, the prompt is printed, and so on. This process is repeated until an end-of-file is read, an interrupt is received, or a break statement is executed inside the loop. If in word ... is omitted, the positional parameters are used (such as "$1", "$2", and so on). For historical reasons, open and close braces can be used instead of do and done (for example, select i; { echo $i; }). The exit status of a select statement is zero if a break statement is used to exit the loop; otherwise, it is non-zero.
time pipeline
The shell executes the pipeline and writes to standard error the elapsed time, the user time, and the system time for the command.

Redirections after the pipeline affect the last command in the pipeline, not the time(1) command.

until list do list done
This works like while, except that the body is executed only while the exit status of the first list is non-zero.
while list do list done
A while is a prechecked loop. Its body is executed as often as the exit status of the first list is zero. The exit status of a while statement is the last exit status of the list in the body of the loop. If the body is not executed, the exit status is zero.
function name { list }
Defines the function name. (See Functions later in this topic.) Note that redirections specified after a function definition are performed whenever the function is executed, not when the function definition is executed.
name () command
Mostly the same as function. (See Functions later in this topic.)
(( expression ))
The arithmetic expression expression is evaluated. Equivalent to let "expression". See the section on arithmetic expressions and the let command.
[[ expression ]]
Similar to the test and [ ... ] commands (described later), with the following exceptions:

QUOTING

Quoting is used to prevent the shell from treating characters or words specially. There are three methods of quoting. First, backslash (\) quotes the following character, unless it is at the end of a line, in which case both the \ and the newline are stripped. Second, a single quote (') quotes everything up to the next single quote (this can span lines). Third, a double quote (") quotes all characters, except $, ' and \, up to the next unquoted double quote. The characters $ and ' inside double quotes have their usual meaning (that is, parameter, command, or arithmetic substitution) except that no field splitting is carried out on the results of double-quoted substitutions. If a \ inside a double-quoted string is followed by \, $, ', or ", it is replaced by the second character. If it is followed by a newline, both the \ and the newline are stripped. Otherwise, both the \ and the character following are unchanged.

See POSIX mode in this topic for a special rule regarding sequences of the form "...'...\"...'..".

ALIASES

There are two types of aliases: normal command aliases and tracked aliases. Command aliases are usually used as an abbreviation for a long or frequently used command. The shell expands command aliases (that is, it substitutes the alias name for its value) when it reads the first word of a command. An expanded alias is reprocessed to check for more aliases. If a command alias ends in a space or tab, the following word is also checked for alias expansion. The alias expansion process stops when a word that is not an alias is found, when a quoted word is found, or when an alias word that is currently being expanded is found.

The following command aliases are defined automatically by the shell:


autoload='typeset -fu'
functions='typeset -f'
hash='alias -t'
history='fc -l'
integer='typeset -i'
local='typeset'
nohup='nohup '
r='fc -e -'
stop='kill -STOP'
suspend='kill -STOP $$'
type='whence -v'

Tracked aliases allow the shell to remember where it found a particular command. The first time the shell does a path search for a command that is marked as a tracked alias, it saves the full path of the command. The next time the command is executed, the shell checks the saved path to ensure that it is still valid, and if so, avoids repeating the path search. Tracked aliases can be listed and created using alias -t. Note that changing the PATH parameter clears the saved paths for all tracked aliases. If the trackall option is set (that is, set -o trackall or set -h), the shell tracks all commands. This option is set automatically for non-interactive shells. For interactive shells, only the following commands are automatically tracked: cat(1), cc(1), chmod(1), cp(1), date(1), ed(1), emacs(1), grep(1), ls(1), mail(1), make(1), mv(1), pr(1), rm(1), sed(1), sh(1), vi(1) and who(1). (Note that emacs(1) is not currently part of Windows Services for UNIX, and that cc(1) is available only in the Software Development Kit.)

SUBSTITUTION

The first step the shell takes in executing a simple command is to perform substitutions on the words of the command. There are three kinds of substitution: parameter, command, and arithmetic. Parameter substitutions, which are described in detail in the next section, take the form $name or ${...}. Command substitutions take the form $(command) or 'command'. Arithmetic substitutions take the form $((expression)).

If a substitution appears outside of double quotes, the results of the substitution are generally subject to word or field splitting, according to the current value of the IFS parameter. The IFS parameter specifies a list of characters that are used to break a string up into several words; any characters from the set space, tab, and newline that appear in the IFS characters are called IFS white space. Sequences of one or more IFS white-space characters, in combination with zero or one non-IFS white-space character delimit a field. As a special case, leading and trailing IFS white space is stripped (that is, no leading or trailing empty field is created by it); leading or trailing non-IFS white space does create an empty field.

For example: if IFS is set to '<space>:', the sequence of characters '<space>A<space>:<space><space>B: :D' contains four fields: 'A', 'B', '' and 'D'. If the IFS parameter is set to the null string, no field splitting is done. If the parameter is unset, the default value of space, tab, and newline is used.

The results of substitution are, unless otherwise specified, also subject to brace expansion and file-name expansion (see the relevant sections that follow).

A command substitution is replaced by the output generated by the specified command, which is run in a subshell. For $(command) substitutions, normal quoting rules are used when command is parsed. However, for the 'command' form, a \ followed by any of $, ', or \ is stripped (a \ followed by any other character is unchanged). As a special case, in command substitutions, a command of the form < file is interpreted to mean substitute the contents of file ($(< foo) has the same effect as $(cat foo), but it is carried out more efficiently because no process is started).

It should be noted that $(command) expressions are currently parsed by finding the matching parenthesis, regardless of quoting. It is hoped that this will soon be corrected.

Arithmetic substitutions are replaced by the value of the specified expression. For example, the command echo $((2+3*4)) prints 14. (See "Arithmetic Expressions" for a description of an expression.)

PARAMETERS

Parameters are shell variables; they can be assigned values and their values can be accessed using a parameter substitution. A parameter name is either one of the special single punctuation or digit character parameters described later, or a letter followed by zero or more letters or digits ('_' counts as a letter). Parameter substitutions take the form $name or ${name}, where name is a parameter name. If substitution is performed on a parameter that is not set, a null string is substituted unless the nounset option (set -o nounset or set -u) is set, in which case an error occurs.

Parameters can be assigned values in a variety of ways. First, the shell implicitly sets some parameters, like #, and PWD. This is the only way the special single-character parameters are set. Second, parameters are imported from the shell's environment at startup. Third, parameters can be assigned values on the command line. For example, DOG=cat sets the parameter DOG to cat. Multiple parameter assignments can be given on a single command line and they can be followed by a simple command, in which case the assignments are in effect only for the duration of the command (such assignments are also exported; the implications of this are discussed later). Both the parameter name and the = must be unquoted for the shell to recognize a parameter assignment. The fourth way of setting a parameter is with the export, readonly and typeset commands (see their descriptions in the command execution section). Fifth, for and select loops set parameters as well as the getopts, read and set -A commands. Sixth, parameters can be assigned values using assignment operators inside arithmetic expressions or using the ${name=value} form of parameter substitution.

Parameters with the export attribute (set using the export or typeset -x commands, or by parameter assignments followed by simple commands) are put in the environment (see environ(5)) of commands run by the shell as name=value pairs. The order in which parameters appear in the environment of a command is unspecified. When the shell starts up, it extracts parameters and their values from its environment and automatically sets the export attribute for those parameters.

Modifiers can be applied to the ${name} form of parameter substitution:

${name:-word}
If name is set and not null, it is substituted; otherwise, word is substituted.
${name:+word}
If name is set and not null, word is substituted; otherwise, nothing is substituted.
${name:=word}
If name is set and not null, it is substituted; otherwise, it is assigned word and the resulting value of name is substituted.
${name:?word}
If name is set and not null, it is substituted; otherwise, word is printed on standard error (preceded by name:), and an error occurs (usually causing termination of a shell script, function, or .-script). If word is omitted, the string 'parameter null or not set' is used instead.

In the above modifiers, the : can be omitted, in which case the conditions only depend on name being set (as opposed to set and not null). If word is needed, parameter, command, arithmetic, and tilde substitution are performed on it; if word is not needed, it is not evaluated.

The following forms of parameter substitution can also be used:

${#name}
The number of positional parameters if name is *, @, or is not specified, or the length of the string value of parameter name.
${#name[*]}, ${#name[@]}
The number of elements in the array name.
${name#pattern}, ${name##pattern}
If pattern matches the beginning of the value of parameter name, the matched text is deleted from the result of substitution. A single # results in the shortest match, two number signs (#) result in the longest match.
${name%pattern}, ${name%%pattern}
Like ${..#..} substitution, but it deletes from the end of the value.

The following special parameters are implicitly set by the shell and cannot be set directly using assignments:

!
Process identifier (PID) of the last background process started. If no background processes have been started, the parameter is not set.
#
The number of positional parameters (such as $1, $2, and so on).
$
The PID of the shell, or the PID of the original shell if it is a subshell.
-
The concatenation of the current single-letter options (see the set command for a list of options).
?
The exit status of the last non-asynchronous command executed. If the last command was killed by a signal, $? is set to 128 plus the signal number.
0
The name with which the shell was invoked (that is, argv[0]), or the command-name if it was invoked with the -c option and the command-name was supplied, or the file argument, if it was supplied. If the posix option is not set, $0 is the name of the current function or script.
1 ... 9
The first nine positional parameters that were supplied to the shell, function, or .-script. Further positional parameters can be accessed using ${number}.
*
All positional parameters (except parameter 0); that is, $1 $2 $3.... If used outside of double quotes, parameters are separate words (which are subjected to word splitting). If used within double quotes, parameters are separated by the first character of the IFS parameter (or the empty string if IFS is null).
@
Same as $*, unless it is used inside double quotes, in which case a separate word is generated for each positional parameter. If there are no positional parameters, no word is generated ("$@" can be used to access arguments, verbatim, without loosing null arguments or splitting arguments with spaces).

The following parameters are either set, not used by the shell, or both:

_ (underscore)
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 is placed in the command's environment. When MAILPATH messages are evaluated, this parameter contains the name of the file that changed (see MAILPATH parameter).
CDPATH
Search path for the cd(1) built-in command. Works the same way as PATH for those directories not beginning with / in cd(1) commands. Note that if CDPATH is set and does not contain . or an empty path, the current directory is not searched.
COLUMNS
Set to the number of columns on the terminal or window. Currently set to the cols value as reported by stty(1) if that value is non-zero. This parameter is used by the interactive line-editing modes, and by select, set -o and kill -l commands to format information in columns.
EDITOR
If the VISUAL parameter is not set, this parameter controls the command-line editing mode for interactive shells. See VISUAL parameter for information about how this works.
ENV
If this parameter is found to be set after any profile files are executed, the expanded value is used as a shell start-up file. It typically contains function and alias definitions.
ERRNO
Integer value of the shell's errno variable; indicates the reason the last system call failed.
EXECSHELL
If set, this parameter is assumed to contain the shell that is to be used to execute commands that execve(3) fails to execute and that do not start with a '#! shell' sequence.
FCEDIT
The editor used by the fc command.
FPATH
Like PATH, but used when an undefined function is executed to locate the file defining the function. It is also searched when a command cannot be found using PATH. See the section on functions for more information.
HISTFILE
The name of the file used to store history. When assigned to, history is loaded from the specified file. Also, several invocations of the shell running on the same computer will share history if their HISTFILE parameters all point at the same file.

If HISTFILE is not set, no history file is used. This is different from the original Korn shell, which uses $HOME/.sh_history. In the future, ksh(1) might also use a default history file.

HISTSIZE
The number of commands normally stored for history,; the is default 128.
HOME
The default directory for the cd command, and the value substituted for an unqualified ~ For more information, see the section on tilde expansion.
IFS
Internal field separator, used during substitution and by the read command to split values into distinct arguments. It is usually set to space, tab, and newline. See the section on substitution for details.

This parameter is not imported from the environment when the shell is started.

KSH_VERSION
The version of shell and the date the version was created (readonly). (See also the version commands in Emacs interactive input line editing and Vi interactive input line editing.)
LINENO
The line number of the function or shell script that is currently being executed.
LINES
Set to the number of lines on the terminal or window.
MAIL
If set, the user will be informed of the arrival of mail in the named file. This parameter is ignored if the MAILPATH parameter is set.
MAILCHECK
How often, in seconds, the shell will check for mail in the file or files specified by MAIL or MAILPATH. If 0, the shell checks before each prompt. The default is 600 (10 minutes).
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, parameter, and arithmetic substitution is performed on the message; during substitution, the parameter $_ contains the name of the file. The default message is: you have mail in $_.
OLDPWD
The previous working directory. Unset if cd has not successfully changed directories since the shell started, or if the shell does not know where it is.
OPTARG
When using getopts, it contains the argument for a parsed option if one is required.
OPTIND
The index of the last argument processed when using getopts. Assigning 1 to this parameter causes getopts to process arguments from the beginning the next time it is invoked.
PATH
A colon-separated list of directories that are searched when looking for commands and .script files. An empty string resulting from a leading or trailing colon, or two adjacent colons is treated as a '.', the current directory.
PATH_WINDOWS
A colon-separated list of directories and suffixes. When attempting to resolve an external command name, the shell searches PATH first. If it fails to find a matching command executable, it searches the directories in PATH_WINDOWS for matching files with the specified suffixes.
POSIXLY_CORRECT
If set, this parameter causes the posix option to be enabled. See POSIX mode.
PPID
The process identifier (PID) of the shell's parent (readonly).
PS1
PS1 is the primary prompt for interactive shells. Parameter, command, and arithmetic substitutions are performed, and ! is replaced with the current command number (see fc command). Default is '$ '.
PS2
Secondary prompt string, by default '> ', used when more input is needed to complete a command.
PS3
Prompt used by select statement when reading a menu selection. Default is '#? '.
PS4
Used to prefix commands that are printed during execution tracing (see set -x command). Parameter, command, and arithmetic substitutions are performed before it is printed. Default is '+ '.
PWD
The current working directory. May be unset or null if shell does not know where it is.
RANDOM
A simple random-number generator. Every time RANDOM is referenced, it is assigned the next number in a random number series. The point in the series can be set by assigning a number to RANDOM (see rand(3)).
REPLY
Default parameter for the read command if no names are given. Also used in select loops to store the value that is read from standard input.
SECONDS
The number of seconds since the shell started, or, if the parameter has been assigned an integer value, the number of seconds since the assignment, plus the value that was assigned.
TMOUT
If set to a positive integer in an interactive shell, it specifies the maximum number of seconds the shell will wait for input after printing the primary prompt (PS1). If the time is exceeded, the shell exits.
TMPDIR
The directory shell in which temporary files are created. If this parameter is not set or does not contain the absolute path of a writable directory, temporary files are created in /tmp. (The root of the directory depends upon where the Interix distribution is installed.)
VISUAL
If set, this parameter controls the command-line editing mode for interactive shells. If the last component of the path specified in this parameter contains the string vi, emacs, or gmacs, the vi, emacs or gmacs (Gosling emacs) editing mode is enabled, respectively.

TILDE EXPANSION

Tilde expansion, which is done in parallel with parameter substitution, is done on words starting with an unquoted tilde character (~). The characters following the tilde, up to the first /, if any, are assumed to be a login name. If the login name is empty, + or -, the value of the HOME, PWD, or OLDPWD parameter is substituted, respectively. Otherwise, the password file is searched for the login name, and the tilde expression is substituted with the user's home directory. If the login name is not found in the password file, or if any quoting or parameter substitution occurs in the login name, no substitution is performed.

In parameter assignments (those preceding a simple command or those occurring in the arguments of alias, export, readonly, and typeset), tilde expansion is done after any unquoted colon (:), and login names are delimited by colons.

The home directory of previously expanded login names are cached and reused. The alias -d command can be used to list, change, and add to this cache (for example, 'alias -d fac=/local/facilities; cd ~fac/bin').

On a Windows system, tilde expansion depends upon the contents of the local password database. If the login name comes from another domain (even if you are logged into that domain), it is not checked for information, and the tilde is not properly expanded. As previously mentioned, you can use the alias -d command to add login names.

BRACE EXPANSION (ALTERATION)

Brace expressions take the form prefix(str1,...,strN)suffix.

They are expanded to N words, each of which is the concatenation of prefix, stri and suffix (for example, 'a{c,b{X,Y},d}e' expands to four word: ace, abXe, abYe, and ade). As noted in the example, brace expressions can be nested, and the resulting words are not sorted. Brace expressions must contain an unquoted comma (,) for expansion to occur (that is, {} and {foo} are not expanded). Brace expansion is carried out after parameter substitution and before file-name generation.

FILE-NAME PATTERNS

A file-name pattern is a word containing one or more unquoted ? or * characters or [..] sequences. Once brace expansion has been performed, the shell replaces file-name patterns with the sorted names of all the files that match the pattern. (If no files match, the word is left unchanged.) The pattern elements have the following meanings:

?
Matches any single character.
*
Matches any sequence of characters.
[..]
Matches any of the characters inside the brackets. Ranges of characters can be specified by separating two characters by a -. For example, [a0-9] matches the letter a or any digit. To represent itself, a - must either be quoted or be the first or last character in the character list. Similarly, a ] must be quoted or the first character in the list if it is to represent itself instead of the end of the list. Also, a ! appearing at the start of the list has special meaning (described later); to represent itself it must be quoted or appear later in the list.
[!..]
Like [..], except it matches any character not inside the brackets.
*(pattern| ... |pattern)
Matches any string of characters that matches zero or more occurrences of the specified patterns. Example: the pattern *(foo|bar) matches the strings '', 'foo', 'bar', and 'foobarfoo'
+(pattern| ... |pattern)
Matches any string of characters that matches one or more occurrences of the specified patterns. Example: the pattern +(foo|bar) matches the strings 'foo', 'bar', and 'foobarfoo'
?(pattern| ... |pattern)
Matches the empty string or a string that matches one of the specified patterns. Example: the pattern ?(foo|bar) only matches the strings '', 'foo', and 'bar'.
@(pattern| ... |pattern)
Matches a string that matches one of the specified patterns. Example: the pattern @(foo|bar) only matches the strings 'foo' and 'bar'.
!(pattern| ... |pattern)
Matches any string that does not match one of the specified patterns. Examples: the pattern !(foo|bar) matches all strings except 'foo' and 'bar'; the pattern !(*) matches no strings; the pattern !(?)* matches all strings.

Currently, ksh(1) never matches . and .., but the original ksh, Bourne sh and bash do, so this might change.

Note that none of the above pattern elements match either a period (.) at the start of a file name or a slash (/), even if they are explicitly used in a [..] sequence. Also, the names . and .. are never matched, even by the pattern .*.

If the markdirs option is set, any directories that result from file-name generation are marked with a trailing /.

The POSIX character classes (that is, [:class-name:] inside a [..] expression) are not yet implemented.

INPUT/OUTPUT REDIRECTION

When a command is executed, its standard input, standard output, and standard error (file descriptors 0, 1 and 2, respectively) are normally inherited from the shell. Three exceptions to this are: commands in pipelines, for which standard input, standard output, or both, are those set up by the pipeline; asynchronous commands created when job control is disabled, for which standard input is initially set to be from /dev/null; and commands for which any of the following redirections have been specified:

> file
Standard output is redirected to file. If file does not exist, it is created. If it does exist, is a regular file, and the noclobber option is set, an error occurs. Otherwise, the file is truncated. This means that the command cmd < foo > foo will open foo for reading and then truncate it when it opens it for writing; it will do so before cmd gets a chance to actually read foo.
>| file
Same as >, except the file is truncated, even if the noclobber option is set.
>> file
Same as >, except an existing file is appended to instead of being truncated. Also, the file is opened in append mode, so output is always written to the end of the file (see open(3)).
< file
Standard input is redirected from file, which is opened for reading.
<> file
Same as <, except the file is opened for reading and writing.
<< marker
After reading the command line containing this kind of redirection (called a here document), the shell copies lines from the command source into a temporary file until a line matching marker is read. When the command is executed, standard input is redirected from the temporary file. If marker contains no quoted characters, the contents of the temporary file are processed as if enclosed in double quotes each time the command is executed, so parameter, command, and arithmetic substitutions are performed, along with backslash (\) escapes for $, ', \ and \newline. If multiple here documents are used on the same command line, they are saved in order.
<<- marker
Same as <<, except leading tabs are stripped from lines in the here document.
<& fd
Standard input is duplicated from file descriptor fd. fd can be a single digit, indicating the number of an existing file descriptor; the letter p, indicating the file descriptor associated with the output of the current co-process; or the character -, indicating standard input is to be closed.
>& fd
Same as <&, except the operation is done on standard output.

In any of the above redirections, the file descriptor that is redirected (that is, standard input or standard output) can be explicitly given by preceding the redirection with a single digit. Parameter, command, and arithmetic substitutions; tilde substitutions; and file-name generation are all performed on the file, marker and fd arguments of redirections. Note, however, that the results of any file-name generation are only used if a single file is matched. If multiple files match, the word with the unexpanded file-name generation characters is used. In restricted shells, redirections that can create files cannot be used.

For simple commands, redirections can appear anywhere in the command. For compound commands (such as if statements), redirections must appear at the end. Redirections are processed after pipelines are created and in the order in which they are given, so:

cat /foo/bar 2>&1 > /dev/null | cat -n
will print an error with a line number prepended to it.

ARITHMETIC EXPRESSIONS

Integer arithmetic expressions can be used with the let command, inside $((..)) expressions, inside array references (for example, name[expr]), as numeric arguments to the test command, and as the value of an assignment to an integer parameter.

Expression can contain alphanumeric parameter identifiers, array references, and integer constants. Expressions can be combined with the following C operators (listed and grouped in increasing order of precedence).

Unary operators: + - ! ~ ++ --
Binary operators: ,
= *= /= %= += -= <<= >>= &= ^= |=
||
&&
|
^
&
== !=
< <= >= >
<< >>
+ -
* / %
Ternary operator: ?: (Precedence is immediately higher than assignment)
Grouping operators: ( )

Integer constants can be specified with arbitrary bases using the notation base#number, where base is a decimal integer specifying the base, and number is a number in the specified base.

The operators are evaluated as follows:

unary +
Result is the argument (included for completeness).
unary -
Negation.
!
Logical not; the result is 1 if argument is zero, 0 if not.
~
Arithmetic (bit-wise) not.
++
Increment; must be applied to a parameter (not a literal or other expression); the parameter is incremented by 1. When used as a prefix operator, the result is the incremented value of the parameter. When used as a postfix operator, the result is the original value of the parameter.
--
Decrement; similar to ++, except the parameter is decremented by 1.
,
Separates two arithmetic expressions; the left-hand side is evaluated before the right. The result is the value of the expression on the right-hand side.
=
Assignment; variable on the left is set to the value on the right.
*= /= %= += -= <<= >>= &= ^= |=
Assignment operators; <var> <op>= <expr> is the same as <var> = <var> <op> ( <expr> ).
||
Logical OR; the result is 1 if either argument is non-zero, 0 if not. The right argument is evaluated only if the left argument is zero.
&&
Logical AND; the result is 1 if both arguments are non-zero, 0 if not. The right argument is evaluated only if the left argument is non-zero.
|
Arithmetic (bit-wise) or.
^
Arithmetic (bit-wise) exclusive-or.
&
Arithmetic (bit-wise) and.
==
Equal; the result is 1 if both arguments are equal, 0 if not.
!=
Not equal; the result is 0 if both arguments are equal, 1 if not.
<
Less than; the result is 1 if the left argument is less than the right, 0 if not.
<= >= >
Less than or equal, greater than or equal, greater than. See <.
<< >>
Shift left (right). The result is the left argument with its bits shifted left (right) by the amount given in the right argument.
+ - * /
Addition, subtraction, multiplication, and division.
%
Remainder. The result is the remainder of the division of the left argument by the right. The sign of the result is unspecified if either argument is negative.
<arg1> ? <arg2> : <arg3>
If <arg1> is non-zero, the result is <arg2>, otherwise <arg3>.

CO-PROCESSES

A co-process, which is a pipeline created with the |& operator, is an asynchronous process that the shell can both write to (using print -p) and read from (using read -p). The input and output of the co-process can also be manipulated using >&p and <&p redirections, respectively. Once a co-process has been started, another cannot be started until the initial co-process exits, or the co-process input has been redirected using an exec n>&p redirection. If the input of a co-process is redirected in this way, the next co-process to be started will share the output with the first co-process, unless the output of the initial co-process has been redirected using an exec n<&p redirection.

The following additional considerations apply to co-processes:

FUNCTIONS

Functions are defined using either Korn shell function name syntax or the Bourne/POSIX shell name() syntax. (The differences between the two forms are described later.) Functions are like .-scripts in that they are executed in the current environment. Unlike .-scripts, however, shell arguments (such as positional parameters, $1, and so on) are never visible inside them. When the shell is determining the location of a command, functions are searched after special built-in commands and before regular and non-regular built-ins, and before the PATH is searched.

An existing function can be deleted using unset -f function-name. A list of functions can be obtained using typeset +f, and the function definitions can be listed using typeset -f. autoload (which is an alias for typeset -fu) can be used to create undefined functions. When an undefined function is executed, the shell searches the path specified in the FPATH parameter for a file with the same name as the function, which, if found is read and executed. If after executing the file, the named function is found to be defined, the function is executed. Otherwise, the normal command search is continued. That is, the shell searches the regular built-in command table and PATH. If a command is not found using PATH, an attempt is made to autoload a function using FPATH (this is an undocumented feature of the original Korn shell).

Functions can have two attributes, trace and export, that can be set with typeset -ft and typeset -fx, respectively. When a traced function is executed, the shell's xtrace option is turned on for the functions duration. Otherwise, the xtrace option is turned off. The export attribute of functions is currently not used. In the original Korn shell, exported functions are visible to shell scripts that are executed.

Since functions are executed in the current shell environment, parameter assignments made inside functions are visible after the function completes. If this is not the effect you want, use the typeset command inside a function to create a local parameter. Special parameters (such as $$, $!), however, cannot be scoped in this way.

The exit status of a function is that of the last command executed in the function. A function can be made to finish immediately using the return command. This can also be used to explicitly specify the exit status.

Functions defined with the function reserved word are treated differently in the following ways from functions defined with the () notation:

POSIX MODE

The shell is intended to be POSIX compliant. In some cases, however, POSIX behavior is contrary either to the original Korn shell behavior or to user convenience. How the shell behaves in these cases is determined by the state of the posix option (set +o posix). If it is on, the POSIX behavior is followed; otherwise, it is not. The posix option is set automatically when the shell starts up if the environment contains the POSIXLY_CORRECT parameter.

The following is a list of things that are affected by the state of the posix option.

\ inside double quoted '..' command substitutions
In posix mode, the \" is interpreted when the command is interpreted; in non-posix mode, the \ is stripped before the command substitution is interpreted. For example, echo "'echo \"hi\"'" produces '"hi"' in posix mode, 'hi' in non-posix mode. To prevent problems, use the $(...) form of command substitution.
kill -l output
In posix mode, signal names are listed on a single line; in non-posix mode, signal numbers, names and descriptions are printed in columns. In the future, a new option (-v perhaps) will be added to distinguish the two behaviors.
fg exit status
In posix mode, the exit status is 0 if no errors occur; in non-posix mode, the exit status is that of the last foregrounded job.
getopts
In posix mode, options must start with a -; in non-posix mode, options can start with either - or +, but if one starts with + they must all start with +.
brace expansion (also known as alternation)
In posix mode, brace expansion is disabled; in non-posix mode, brace expansion enabled. Note that set -o posix (or setting the POSIXLY_CORRECT parameter) automatically turns the braceexpand option off; it can be explicitly turned on later.
set -
In posix mode, this does not clear the verbose or xtrace options; in non-posix mode, it does.
set exit status
In posix mode, the exit status of set is 0 if there are no errors; in non-posix mode, the exit status is that of any command substitutions performed in generating the set command. For example, 'set -- 'false'; echo $?' prints 0 in posix mode and 1 in non-posix mode. This construct is used in most shell scripts that use the old getopt(1) command.
argument expansion of alias, export, readonly and typeset commands
In posix mode, normal argument expansion is done; in non-posix mode, field splitting, file globbing, brace expansion, and (normal) tilde expansion are turned off, and assignment tilde expansion is turned on.
signal specification
In posix mode, signals can be specified as digits only if signal numbers match POSIX values (that is, HUP=1, INT=2, QUIT=3, ABRT=6, KILL=9, ALRM=14, and TERM=15); in non-posix mode, signals can be always digits.
alias expansion
In posix mode, alias expansion is only carried out when reading command words; in non-posix mode, alias expansion is carried out on any word following an alias that ended in a space. For example, the following 'for' loop uses parameter i in posix mode, j in non-posix mode:

alias a='for ' i='j'
a i in 1 2; do echo i=$i j=$j; done

COMMAND EXECUTION

After evaluation of command-line arguments, redirections, and parameter assignments, the type of command is determined: a special built-in command, a function, a regular built-in command, or the name of a file to execute found using the PATH parameter. The checks are made in the above order. Special built-in commands differ from other commands in that the PATH parameter is not used to find them, an error during their execution can cause a non-interactive shell to exit, and parameter assignments that are specified before the command are kept after the command completes. In addition, if the posix option is turned off (see set command) some special commands are very special in that no field splitting, file globbing, brace expansion or tilde expansion is preformed on arguments that look like assignments. Regular built-in commands are different only in that the PATH parameter is not used to find them.

The original ksh and POSIX differ somewhat in which commands are considered special or regular. These are shown in the following tables:

POSIX special commands
. continue exit return trap
: eval export set unset
break exec readonly shift
Additional ksh special commands
builtin times typeset
Very Special commands (non-posix mode)
alias readonly set typeset
POSIX regular commands
alias command fg kill umask
bg false getopts read unalias
cd fc jobs true wait
Additional ksh regular commands
[ let pwd ulimit
User commands
echo print test whence

In the future, the additional ksh special and regular commands might be treated differently from the POSIX special and regular commands.

Once the type of the command has been determined, any command-line parameter assignments are performed and exported for the duration of the command.

The following describes the special and regular built-in commands:

. file [arg1 ...]
Execute the commands in file in the current environment. The file is searched for in the directories of PATH. If arguments are given, the positional parameters can be used to access them while file is being executed. If no arguments are given, the positional parameters are those of the environment in which the command is used.
: [ ... ]
The null command. Exit status is set to zero.
alias [ -d | -t [-r] ] [-x] [name1[=value1] ...]

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 the section on aliases).

The -x option sets the export attribute of an alias, or, if no names are given, lists the aliases with the export attribute (exporting an alias currently has no effect).

The -t option indicates that tracked aliases are to be listed/set (values specified on the command line are ignored for tracked aliases). The -r option indicates that all tracked aliases are to be reset.

The -d causes directory aliases, which are used in tilde expansion, to be listed or set (see the section on tilde expansion).

bg [job ...]
Resume the specified stopped job or jobs in the background. If no jobs are specified, %+ is assumed. This command is only available on systems that support job control. See the section on job control for more information.
bind [-m] [key[=editing-command] ...]
Set or view the current emacs command-editing key bindings/macros. See the section on emacs interactive input line editing for a complete description.
break [level]
break exits the innermost for, select, until, or while loop specified by level. level defaults to 1.
builtin command [arg1 ...]
Execute the built-in command command.
cd [-LP] [dir]
Set the working directory to dir. If the parameter CDPATH is set, it lists the search path for the directory containing dir. A null path means the current directory. If dir is missing, the home directory $HOME is used. If dir is -, the previous working directory is used (see the OLDPWD parameter). If the -L option (logical path) is used, or if the physical option (see set command) is not set, references to .. in dir are relative to the path used get to the directory. If the -P option (physical path) is used, or if the physical option is set, .. is relative to the file-system directory tree. The PWD and OLDPWD parameters are updated to reflect the current and old wording directory, respectively.
cd [-LP] old new
The string new is substituted for old in the current directory, and the shell attempts to change to the new directory.
command [-pvV] cmd [arg1 ...]
If neither the -v nor -V options are given, cmd is executed exactly as if the command had not been specified, with two exceptions. First, cmd cannot be a shell function. Second, special built-in commands lose their specialness; that is, redirection and utility errors do not cause the shell to exit, and command assignments are not permanent. If the -p option is given, a default search path is used instead of the current value of PATH. The actual value of the default path is system dependent: on POSIX systems, it is the value returned by getconf CS_PATH.

If the -v option is given, instead of executing cmd, information about what would be executed is given, and the same is done for arg1 ...). For special and regular built-in commands and functions, their names are simply printed. For aliases, a command that defines them is printed. For commands found by searching the PATH parameter, the full path of the command is printed. If no command is be found, (that is, the path search fails), nothing is printed and command exits with a non-zero status. The -V option is like the -v option, except it is more verbose.

continue [levels]
continue jumps to the beginning of the innermost for, select, until, or while loop specified by level. level defaults to 1.
echo [-neE] [arg ...]
Prints its arguments (separated by spaces) followed by a newline, to standard out. The newline is suppressed if any of the arguments contain the backslash sequence \c. See print command for a list of other backslash sequences that are recognized.

The options are provided for compatibility with Berkeley Software Distribution (BSD) shell scripts: -n suppresses the trailing newline, -e enables backslash interpretation (a no-op, since this is normally done), and -E suppresses backslash interpretation.

eval command ...
The arguments are concatenated (with spaces between them) to form a single string that the shell then parses and executes in the current environment.
exec [command [arg ...]]
The command is executed without forking, replacing the shell process.

If no arguments are given, any input/output (I/O) redirection is permanent and the shell is not replaced. Any file descriptors greater than two that are opened or duplicated in this way are not made available to other executed commands (that is, commands that are not built-in to the shell).

exit [status]
The shell exits with the specified exit status. If status is not specified, the exit status is the current value of the ? parameter.
export [-p] [parameter[=value]] ...
Sets the export attribute of the named parameters. Exported parameters are passed in the environment to executed commands. If values are specified, the named parameters also assigned.

If no parameters are specified, the names of all parameters with the export attribute are printed one per line unless the -p option is used, in which case export commands defining all exported parameters, including their values, are printed.

false
A command that exits with a non-zero status.
fc [-e editor | -l [-n]] [-r] [first [last]]
first and last select commands from the history. 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 are edited by the editor specified with the -e option, or if no -e is specified, the editor specified by the FCEDIT parameter (if this parameter is not set, /bin/ed is used), and then executed by the shell.
fc [-e - | -s] [-g] [old=new] [prefix]
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 -'.
fg [job ...]
Resume the specified job or jobs in the foreground. If no jobs are specified, %+ is assumed. This command is only available on systems that support job control. See the section on job control for more information.
getopts optstring name [arg ...]
getopts is used by shell procedures to parse the specified arguments (or positional parameters, if no arguments are given) and to check for legal options. optstring contains the option letters that getopts is to recognize. If a letter is followed by a :, the option is expected to have an argument. Arguments containing options must all start with either a - or a +. Options that do not take arguments can be grouped in a single argument. If an option takes an argument, and the option character is not the last character of the argument in which it is found, the remainder of the argument is taken to be the option's argument. Otherwise, the next argument is the option's argument.

Each time getopts is invoked, it places the next option in the shell parameter name and the index of the next argument to be processed in the shell parameter OPTIND. If the option was introduced with a +, the option placed in name is prefixed with a +. When an option requires an argument, getopts places it in the shell parameter OPTARG. When an illegal option or a missing option argument is encountered, a question mark or a colon is placed in name (indicating an illegal option or missing argument, respectively), and OPTARG is set to the option character that caused the problem. An error message is also printed to standard error if optstring does not begin with a colon.

When the end of the options is encountered, getopts exits with a non-zero exit status. Options end at the first (non-option argument) argument that does not start with a -, or when a -- argument is encountered.

Option parsing can be reset by setting OPTIND to 1 (this is done automatically whenever the shell or a shell procedure is invoked).

It should be noted that changing the value of the shell parameter OPTIND to a value other than 1, or parsing different sets of arguments without resetting OPTIND can lead to unexpected results.

hash [-r] [name ...]
Without arguments, any hashed executable command path names are listed. The 3f-r option causes all hashed commands to be removed from the hash table. Each name is searched as if it where a command name and added to the hash table if it is an executable command.
jobs [-lpn] [job ...]
Display information about the specified jobs; if no jobs are specified, all jobs are displayed. The -n option causes information to be displayed only for jobs that have changed state since the last notification. If the -l option is used, the process identifier (PID) of each process in a job is also listed. The -p option causes only the process group of each job to be printed. See the section on job control for the format of job and the displayed job.
kill [-s signame | -signum | -signame ] { job | pid | -pgrp } ...
Send the specified signal to the specified jobs, PIDs, or process groups. If no signal is specified, the signal TERM is sent. If a job is specified, the signal is sent to the job's process group. See the section on job control for the format of job.
kill -l [exit-status ...]
Print the name of the signal that killed a process that exited with the specified exit-statuses. If no arguments are specified, a list of all the signals, their numbers, and a short description of them is printed.
let [expression ...]
Each expression is evaluated (see the section on arithmetic expressions). If all expressions are successfully evaluated, the exit status is 0 (1) if the last expression evaluated to non-zero (zero). If an error occurs during the parsing or evaluation of an expression, the exit status is greater than 1. Since expressions might need to be quoted, let "expr" can be written as (( expr )).
print [-nprsu n | -R [-en]] [argument ...]
print prints its arguments on the standard output, separated by spaces, and terminated with a newline. The -n option suppresses the newline. By default, certain C escapes are translated. These include \b, \f, \n, \r, \t, \v, and \0###. (Note that # is an octal digit, of which there may be 0 to 3.) \c is equivalent to using the -n option. \ expansion can be inhibited with the -r option. The -s option prints to the history file instead of standard output, the -u option prints to file descriptor n (n defaults to 1 if omitted), and the -p option prints to the co-process (see the section on co-processes).

The -R option is used to emulate, to some degree, the BSD echo command, which does not process \ sequences unless the -e option is given. As above, the -n option suppresses the trailing newline.

pwd [-LP]
Print the present working directory. If -L option is used, or if the physical option (see set command) is not set, the logical path is printed (that is, the path passed to cd when changing the current directory). If -P option (physical path) is used or the physical option is set, the path determined from the file system (by following .. directories to the root directory) is printed.
read [-prsu n] [parameter ...]
Read a line of input from standard input, separate the line into fields using the IFS parameter (see the section on substitution), and assign each field to the specified parameters. If there are more parameters than fields, the extra parameters are set to null. Alternatively, if there are more fields than parameters, the last parameter is assigned the remaining fields (inclusive of any separating spaces). If no parameters are specified, the REPLY parameter is used. If the input line ends in a backslash (\) and the -r option was not used, the backslash and newline are stripped and more input is read. If no input is read, read exits with a non-zero status.

To display a prompt, append a question mark and the prompt to the first parameter (for example, read nfoo?'number of foos: ').

The -un and -p options cause input to be read from file descriptor n or the current co-process, respectively. (See the section on co-processes for more information.) If the -s option is used, input is saved to the history file.

readonly [-p] [parameter[=value]] ...
Sets the read-only attribute of the named parameters. If values are given, parameters are set to them before setting the attribute. Once a parameter is made read-only, it cannot be unset, and its value cannot be changed.

If no parameters are specified, the names of all parameters with the read-only attribute are printed one per line, unless the -p option is used, in which case readonly commands defining all read-only parameters, including their values, are printed.

return [status]
Returns from a function or . script, with exit status status. If no status is given, the exit status of the last executed command is used. If used outside of a function or . script, it has the same effect as exit. Note that ksh(1) treats both profile and $ENV files as . scripts, while the original Korn shell only treats profiles as . scripts.
set [+-abCefhkmnpsuvxX] [+-o [option]] [+-A name] [--] [arg ...]
The set command can be used to set (-) or clear (+) shell options, set the positional parameters, or set an array parameter. Options can be changed using the +-o option syntax, where option is the long name of an option, or using the +-letter syntax, where letter is the option's single-letter name (not all options have a single-letter name). The following table lists both option letters (if they exist) and long names, along with a description of what the option does.
Option letter Long name Description
-A Sets the elements of the array parameter name to arg ...; if -A is used, the array is reset (that is, emptied) first. If +A is used, the first N elements are set (where N is the number of args), and the rest are left untouched.
-a allexport All new parameters are created with the export attribute.
-b notify Print job notification messages asynchronously instead of just before the prompt. Only used if job control is enabled (-m).
-C noclobber Prevent > redirection from overwriting existing files (>| must be used to force an overwrite).
-e errexit Exit (after executing the ERR trap) as soon as an error occurs or a command fails (that is, exits with a non-zero status). This does not apply to commands whose exit status is explicitly tested by a shell construct, such as if, until, while, &&, or || statements.
-f noglob Do not expand file-name patterns.
-h trackall Create tracked aliases for all executed commands (see the section on aliases). On by default for non-interactive shells.
-i interactive Enable interactive mode. This can only be set/unset when the shell is invoked.
-k keyword Parameter assignments are recognized anywhere in a command.
-l login The shell is a login shell. This can only be set/unset when the shell is invoked (see the section on shell startup).
-m monitor Enable job control (default for interactive shells).
-n noexec Do not execute any commands. Useful for checking the syntax of scripts (ignored if interactive).
-p privileged Set automatically if, when the shell starts, the read user identifier (UID) or group identifier (GID) does not match the effective UID or GID, respectively. (See the section on shell startup for a description of what this means.)
-r restricted Enable restricted mode. This option can only be used when the shell is invoked. (See the section on shell startup for a description of what this means.)
-s stdin If used when the shell is invoked, commands are read from standard input; set automatically if the shell is invoked with no arguments. When -s is used in the set command, it causes the specified arguments to be sorted before assigning them to the positional parameters (or to array name, if -A is used).
-u nounset Referencing of an unset parameter is treated as an error unless one of the -, +, or = modifiers is used.
-v verbose Write shell input to standard error as it is read.
-x xtrace Print commands and parameter assignments when they are executed, preceded by the value of PS4.
-X markdirs Mark directories with a trailing / during file-name generation.
bgnice Background jobs are run with lower priority.
braceexpand Enable brace expansion (also known as alternation).
cmd_intitle Displays the current command line in the title bar of the terminal window.
emacs Enable BRL emacs-like command-line editing (interactive shells only); see the section on emacs interactive input line editing.
gmacs Enable gmacs-like (Gosling emacs) command-line editing (interactive shells only); currently identical to emacs editing except that transpose (^T) acts slightly differently.
ignoreeof The shell will not exit on when it reaches the end of the file; exit must be used.
nohup Do not kill running jobs with a HUP signal when a login shell exists. Currently set by default, but this will change in the future to be compatible with the original Korn shell (which does not have this option, but does send the HUP signal).
nolog No effect in the original Korn shell; this prevents function definitions from being stored in the history file.
physical Causes the cd and pwd commands to use 'physical' (the file system's) .. directories instead of 'logical' directories (that is, the shell handles .., which allows the user to be oblivious of symlink links to directories). Clear by default. Setting this option does not effect the current value of the PWD parameter; only the cd command changes PWD. See the cd and pwd commands for more details.
posix Enable posix mode. See POSIX mode.
vi Enable vi-like command-line editing (interactive shells only).
viraw No effect. In most implementations of the Korn shell, unless the viraw option was set, the vi command-line mode would let the tty driver do the work until ESC (^[) was entered. The Interix ksh(1) utility is always in viraw mode.
vi-esccomplete In vi command-line editing, do command / file-name completion when escape (^[) is entered in command mode.
vi-show8 Prefix characters with the eighth-bit set with 'M-'. If this option is not set, characters in the range 128-160 are printed as is, which can cause problems.
vi-tabcomplete In vi command-line editing, do command / file-name completion when tab (^I) is entered in insert mode.

These options can also be used upon invocation of the shell. The current set of options (with single-letter names) can be found in the parameter -. set -o with no option name will list all the options, including whether each is on or off; set +o will print the long names of all options that are currently on.

Remaining arguments, if any, are positional parameters and are assigned, in order, to the positional parameters (such as 1 and 2). If options are ended with --, and there are no remaining arguments, all positional parameters are cleared. If no options or arguments are given, the values of all names are printed. For unknown historical reasons, a lone - option is treated specially: it clears both the -x and -v options.

shift [number]
Shifts positional parameters. Positional parameter 1 will be assigned the value of parameter (1+number), parameter 2 will be assigned the value of parameter (2+number), and so on. The parameters represented by the numbers $# down to $#-n+1 will be unset, and the parameter "#" will be updated to reflect the new number of positional parameters. The value number must be an unsigned decimal integer less than or equal to the value of the special parameter "#". If number is not given, it is assumed to be 1. If numberis 0, the positional and special parameters will not be changed.
test expression
[ expression ]

test evaluates the expression and returns zero status if true, 1 status if false, and greater than 1 if there was an error. It is usually used as the condition command of if and while statements. The following basic expressions are available:

Expression Description
str str has non-zero length. There is the potential for problems if str turns out to be an operator (for example, -r ). It is generally better to use a test like [ X"str" != X ] instead (double quotes are used in case str contains spaces or file-globbing characters).
-r file file exists and is readable.
-w file file exists and is writable.
-x file file exists and is executable.
-a file file exists. (This option is obsolete and might disappear in future versions.)
-e file file exists.
-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 special device.
-p file file is a named pipe.
-u file file's mode has setuid bit set.
-g file file's mode has setgid bit set.
-k file file's mode has sticky bit set.
-s file file is not empty.
-O file file's owner is the shell's effective UID.
-G file file's group is the shell's effective GID
-h file file is a symbolic link.
-L file file is a symbolic link.
-S file file is a socket.
-o option Shell option is set (see set command for list of options). As a non-standard extension, if the option starts with a !, the test is negated; the test always fails if option does not exist (thus [-o foo -o -o !foo ] returns true only if option foo exists). The total number of operands to the [ command determines whether -o is interpreted as the option test or the OR binary operator.
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 fd File descriptor is a tty device. Default value of fd is 1.
string string is not empty.
-z string string is empty.
-n string string is not empty.
string = string Strings are equal.
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, in which unary operators have precedence over binary operators, can be combined with the following operators (listed in increasing order of precedence):

Operator Description
expr -o expr Logical or
expr -a expr Logical and
! expr Logical not
(expr) Grouping

On operating systems not supporting /dev/fd/n devices (where n is a file descriptor number), the test command will attempt to fake it for all tests that operate on files (except the -e test). That is, [ -w /dev/fd/2 ] tests to determine whether file descriptor 2 is writable.

Note that some special rules are applied (courtesy of POSIX) if the number of arguments to test or [ ... ] is less than five: if leading ! arguments can be stripped so that only one argument remains, a string length test is performed (again, even if the argument is a unary operator); if leading ! arguments can be stripped so that three arguments remain and the second argument is a binary operator, the binary operation is performed (even if first argument is a unary operator, including an unstripped !).

It is a common mistake to use if [ $foo = bar ], which fails if parameter foo is null or unset, if it has embedded spaces (that is, IFS characters), or if it is a unary operator like ! or -n. Use tests like if [ "X$foo" = Xbar ] instead.

times
Print the accumulated user and system times used by the shell and by processes that have exited which the shell started.
trap [handler signal ...]
Sets trap handler that is to be executed when any of the specified signals are received. The handler argument is either a null string, indicating the signals are to be ignored; a minus (-), indicating that the default action is to be taken for the signals (see signal(2)); or a string containing shell commands to be evaluated and executed at the first opportunity (that is, when the current command completes, or before printing the next PS1 prompt) after receipt of one of the signals. The signal argument is the name of a signal (for example, PIPE or ALRM) or the number of the signal (see the kill -l command). There are two special signals: EXIT (also known as 0), which is executed when the shell is about to exit, and ERR which is executed after an error occurs (an error is something that would cause the shell to exit if the -e or errexit option were set (see set(1) command). EXIT handlers are executed in the environment of the last executed command. Note that for non-interactive shells, the trap handler cannot be changed for signals that were ignored when the shell started.

With no arguments, trap lists, as a series of trap commands, the current state of the traps that have been set since the shell started.

The original Korn shell's DEBUG trap and the handling of ERR and EXIT traps in functions are not yet implemented.

true
A command that exits with a zero value.
typeset [[+-Ulrtux] [-L[n]] [-R[n]] [-Z[n]] [-i[n]] | -f [-tux]] [name[=value] ...]
Display or set parameter attributes. With no name arguments, parameter attributes are displayed: if no options are used, the current attributes of all parameters are printed as typeset(1) commands; if an option is given (or - with no option letter) all parameters and their values with the specified attributes are printed; if options are introduced with +, parameter values are not printed.

If name arguments are given, the attributes of the named parameters are set (-) or cleared (+). Values for parameters may optionally be specified. If typeset(1) is used inside a function, any newly created parameters are local to the function.

When -f is used, typeset(1) operates on the attributes of functions. As with parameters, if no names are given, functions are listed with their values (that is, definitions) unless options are introduced with +, in which case only the function names are reported.

-Ln Left-justify attribute. n specifies the field width. If n is not specified, the current width of a parameter (or the width of its first assigned value) is used. Leading white space (and zeros, if used with the -Z option) is stripped. If necessary, values are either truncated or space padded to fit the field width.
-Rn Right-justify attribute. n specifies the field width. If n is not specified, the current width of a parameter (or the width of its first assigned value) is used. Trailing white space is stripped. If necessary, values are either stripped of leading characters or space padded to make them fit the field width.
-Zn Zero fill attribute. If not combined with -L, this is the same as -R, except zero padding is used instead of space padding.
-in Integer attribute. n specifies the base to use when displaying the integer (if not specified, the base given in the first assignment is used). Parameters with this attribute can be assigned values containing arithmetic expressions.
-U Unsigned integer attribute. Integers are printed as unsigned values (only useful when combined with the -i option). This option is not in the original Korn shell.
-f Function mode. Display or set functions and their attributes instead of parameters.
-l Lowercase attribute. All uppercase characters in values are converted to lowercase. (In the original Korn shell, this parameter meant 'long integer' when used with the -i option).
-r Read-only attribute. Parameters with the this attribute cannot be assigned to or unset. Once this attribute is set, it cannot be turned off.
-t Tag attribute. Has no meaning to the shell; provided for application use. For functions, -t is the trace attribute. When functions with the trace attribute are executed, the xtrace (-x) shell option is temporarily turned on.
-u Uppercase attribute. All lowercase characters in values are converted to uppercase. (In the original Korn shell, this parameter meant 'unsigned integer' when used with the -i option, which meant uppercase letters would never be used for bases greater than 10. See the -U option).

For functions, -u is the undefined attribute. See the section on functions for the implications of this.

-x Export attribute. Parameters (or functions) are placed in the environment of any executed commands. Exported functions are not yet implemented.
ulimit [-acdfHlmnpsStvw] [value]
Has no effect.
umask [-S] [mask]
Display or set the file-permission creation mask, or umask (see umask(3)). If the -S option is used, the mask displayed or set is symbolic; otherwise, it is an octal number.

Symbolic masks are like those used by chmod(1): [ugoa]{{=+-}{rwx}*}+[,...], in which the first group of characters is the who part, the second group is the op part, and the last group is the perm part. The who part specifies which part of the umask is to be modified. The letters have the following meanings:

u
The user permissions
g
The group permissions
o
The other permissions (non-user, non-group)
a
All permissions (user, group and other)

The op part indicates how the who permissions are to be modified:

=
Set
+
Added to
-
Removed from

The perm part specifies which permissions are to be set, added, or removed:

r
Read permission
w
Write permission
x
Execute permission

When symbolic masks are used, they describe which permissions can be made available (as opposed to octal masks, in which a set bit means the corresponding bit is to be cleared). For example: 'ug=rwx,o=' sets the mask so files will not be readable, writable, or executable by 'others', and is equivalent (on most systems) to the octal mask '07'.

unalias [-adt] [name1 ...]
The aliases for the given names are removed. If the -a option is used, all aliases are removed. If the -t or -d options are used, the indicated operations are carried out on tracked or directory aliases, respectively.
unset [-fv] parameter ...
Unset the named parameters (-v, the default) or functions (-f). The exit status is non-zero if any of the parameters were already unset; otherwise, it is zero.
wait [job]
Wait for one or more specified jobs to finish. The exit status of wait is that of the last specified job. If the last job is killed by a signal, the exit status is 128 + the number of the signal (see kill -l exit-status); if the last specified job cannot be found (because it never existed, or had already finished), the exit status of wait is 127. See the section on job control for the format of job. wait will return if a signal for which a trap has been set is received, or if a HUP, INT or QUIT signal is received.

If no jobs are specified, wait waits for all currently running jobs (if there are any) to finish and exits with a zero status. If job monitoring is enabled, the completion status of jobs is printed (this is not the case when jobs are explicitly specified).

whence [-pv] [name ...]
For each name, the type of command is listed (reserved word, built-in, alias, function, tracked alias or executable). If the -p option is used, a path search is done even if name is a reserved word or alias. Without the -v option, whence is similar to command -v, except that whence will find reserved words and will not print aliases as alias commands; with the -v option, whence is the same as command -V. Note that for whence, the -p option does not affect the search path used, as it does for command. If the type of one or more of the names could not be determined, the exit status is non-zero.

JOB CONTROL

Job control refers to the shell's ability to monitor and control jobs, which are processes or groups of processes created for commands or pipelines. At a minimum, the shell keeps track of the status of the background (that is, asynchronous) jobs that currently exist. This information can be displayed using the jobs command. If job control is fully enabled (using set -m or set -o monitor), as it is for interactive shells, the processes of a job are placed in their own process group, foreground jobs can be stopped by typing the suspend character from the terminal (normally ^Z), jobs can be restarted in either the foreground or background, using the fg and bg commands, respectively, and the state of the terminal is saved or restored when a foreground job is stopped or restarted, respectively.

Only commands that create processes (such as asynchronous commands, subshell commands, and non-built-in, non-function commands) can be stopped; commands like read cannot be stopped.

When a job is created, it is assigned a job number. For interactive shells, this number is printed inside [..], followed by the process identifiers (PID) of the processes in the job when an asynchronous command is run. A job can be referred to in bg, fg, jobs, kill and wait commands either by the PID of the last process in the command pipeline (as stored in the $! parameter) or by prefixing the job number with a percent sign (%). Other percent sequences can also be used to refer to jobs:

%+ The most recently stopped job, or, if there are no stopped jobs, the oldest running job.
%%, % Same as %+.
%- The job that would be the %+ job, if the later did not exist.
%n The job with job number n.
%?string The job containing the string string (an error occurs if multiple jobs are matched).
%string The job starting with string string (an error occurs if multiple jobs are matched).

When a job changes state (for example, a background job finishes or foreground job is stopped), the shell prints the following status information: [number] flag status command where:

number
The number of the job.
flag
This is + or - if the job is the %+ or %- job, respectively; or space if it is neither.
status
Indicates the current state of the job and can be any of the following:
Running
The job has neither stopped nor exited (note that running does not necessarily mean consuming CPU time — the process could be blocked, waiting for some event).
Done [(number)]
The job exited. number is the exit status of the job, which is omitted if the status is zero.
Stopped [(signal)]
The job was stopped by the indicated signal (if no signal is given, the job was stopped by SIGTSTP).
signal-description [(core dumped)]
The job was killed by a signal (such as memory fault or hangup — use kill -l for a list of signal descriptions). The (core dumped) message indicates the process created a core file.
command
The command that created the process. If there are multiple processes in the job, each process will have a line showing its command and possibly its status, if it is different from the status of the previous process.

When an attempt is made to exit the shell while there are jobs in the stopped state, the shell warns the user that there are stopped jobs and does not exit. If another attempt is immediately made to exit the shell, the stopped jobs are sent a HUP signal and the shell exits. Similarly, if the nohup option is not set, and there are running jobs when an attempt is made to exit a login shell, the shell warns the user and does not exit. If another attempt is immediately made to exit the shell, the running jobs are sent a HUP signal and the shell exits.

EMACS 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 the original Korn shell, and the eighth bit is stripped in emacs mode. In this mode, various editing commands (typically bound to one or more control characters) cause immediate actions without waiting for a newline. Several editing commands are bound to particular 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 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. Although only two prefix characters (usually ESC and ^X) are supported, some multi-character sequences can be supported. The following binds the arrow keys on an ANSI terminal, or xterm (these are in the default bindings). Some escape sequences, however, will not work quite this well:

 

bind '^[['=prefix-2
bind '^XA'=up-history
bind '^XB'=down-history
bind '^XC'=forward-char
bind '^XD'=backward-char


bind -l
Lists the names of the functions to which keys may be bound.
bind -m string=[substitute]
The specified input string will afterwards be immediately replaced by the given substitute string, which may contain editing commands.

The following is a list of available editing commands. Each description starts with the name of the command, an n if the command can be prefixed with a count, and any keys the command is bound to by default (written using caret notation; for example, ASCII ESC character is written as ^[). A count prefix for a command is entered using the sequence ^[n, where n is a sequence of 1 or more digits; unless otherwise specified, if a count is omitted, it defaults to 1. 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 (such as ERASE) are bound to reasonable substitutes and override the default bindings.

abort ^G
Useful as a response to a request for a search-history pattern in order to abort the search.
auto-insert n
Simply causes the character to appear as literal input. Most ordinary characters are bound to this.
backward-char n ^B
Moves the cursor backward n characters.
backward-word n ^[B
Moves the cursor backward to the beginning of a word; words consist of alphanumerics, underscore (_) and dollar sign ($).
beginning-of-history ^[<
Moves to the beginning of the history.
beginning-of-line ^A
Moves the cursor to the beginning of the edited input line.
capitalize-word n ^[c, ^[C
Capitalize the first character in the next n words, leaving the cursor past the end of the last word.
comment ^[#
If the current line does not begin with a comment character, one is added at the beginning of the line, and the line is entered (as if return had been pressed); otherwise, the existing comment characters are removed, and the cursor is placed at the beginning of the line.
complete ^[^[
Automatically completes as much as is unique of the 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 this case / is appended. If there is no command or file name with the current partial word as its prefix, a bell character is output (usually causing a audio beep).
complete-command ^X^[
Automatically completes as much as is unique of the command name having the partial word up to the cursor as its prefix, as in the complete command.
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.
complete-list ^[=
List the possible completions for the current word.
delete-char-backward n ERASE, ^?, ^H
Deletes n characters before the cursor.
delete-char-forward n
Deletes n characters after the cursor.
delete-word-backward n ^[ERASE, ^[^?, ^[^H, ^[h
Deletes n words before the cursor.
delete-word-forward n ^[d
Deletes characters after the cursor up to the end of n words.
down-history n ^N
Scrolls the history buffer forward n lines (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.
downcase-word n ^[L, ^[l
Lowercases the next n words.
end-of-history ^[>
Moves to the end of the history.
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 n ^D
Acts as eot if alone on a line; otherwise, acts as delete-char-forward.
error
Error (ring the bell).
exchange-point-and-mark ^X^X
Places the cursor where the mark is, and sets the mark to where the cursor was.
expand-file ^[*
Appends an asterisk (*) to the current word and replaces the word with the result of performing file globbing on the word. If no files match the pattern, the bell is rung.
forward-char n ^F
Moves the cursor forward n characters.
forward-word n ^[f
Moves the cursor forward to the end of the word n.
goto-history n ^[g
Goes to history number n.
kill-line KILL
Deletes the entire input line.
kill-region ^W
Deletes the input between the cursor and the mark.
kill-to-eol n ^K
Deletes the input from the cursor to the end of the line if n is not specified; otherwise, deletes characters between the cursor and column n.
list ^[?
Prints a sorted, columnated list of command names or file names (if any) that can complete the partial word containing the cursor. Directory names have / appended to them.
list-command ^X?
Prints a sorted, columnated list of command names (if any) that can complete the partial word containing the cursor.
list-file ^X^Y
Prints a sorted, columnated list of file names (if any) that can complete the partial word containing the cursor. File type indicators are appended as described under list.
newline ^J, ^M
Causes the current input line to be processed by the shell. The current cursor position can 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
This does nothing.
prefix-1 ^[
Introduces a two-character command sequence.
prefix-2 ^X
prefix-2 ^[[
Introduces a two-character command sequence.
prev-hist-word n ^[., ^[_
The last word (specified by n) of the previous command is inserted at the cursor.
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-backward n ^[^]
Search backward in the current line for occurrence n of the next character typed.
search-character-forward n ^]
Search forward in the current line for occurrence n of the next character typed.
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 abort key will leave search mode. Other commands will be executed after leaving search mode. 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>
Set the mark at the cursor position.
stuff
On systems supporting it, pushes the bound character back onto the terminal input where it can receive special processing by the terminal handler. This is useful for the BRL ^T mini-systat feature, for example.
stuff-reset
Acts like stuff, then aborts input the same as an interrupt.
transpose-chars ^T
If at the end-of-line, or if the gmacs option is set, this exchanges the two previous characters; otherwise, it exchanges the previous and current characters and moves the cursor one character to the right.
up-history n ^P
Scrolls the history buffer backward n lines (earlier).
upcase-word n ^[U, ^[u
Capitalizes the next n words.
version ^V
Display the version of ksh. The current edit buffer is restored as soon as any key is pressed (the key is then processed, unless it is a space).
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.

VI INTERACTIVE INPUT LINE EDITING

The vi command-line editor in ksh has basically the same commands as the vi editor (see vi(1)), with the following exceptions:

Note that the ^X stands for control-X; also <esc>, <space> and <tab> are used for escape, space and tab, respectively.

As in vi, there are two modes: insert mode and command mode. In insert mode, most characters are simply put in the buffer at the current cursor position as they are typed. Some characters are treated specially, however. In particular, the following characters are taken from current tty settings (see stty(1)) and have their usual meaning (normal values are in parentheses): kill (^U), erase (^?), werase (^W), eof (^D), intr (^C) and quit (^\).

In addition, the following characters are also treated specially in insert mode:

^H Erases previous character.
^V Literal next: the next character typed is not treated specially (can be used to insert the characters being described here).
^J ^M End of line: the current line is read, parsed, and executed by the shell.
<esc> Puts the editor in command mode.
^E Command and file-name enumeration.
^F Command and file-name completion. If used twice in a row, the list of possible completions is displayed; if used a third time, the completion is undone.
^X Command and file-name expansion.
<tab> Optional file-name and command completion (see ^F), enabled with set -o vi-tabcomplete.

If a line is longer that the screen width (see COLUMNS parameter), a >, + or < character is displayed in the last column indicating that there are more characters after, before and after, or before the current position, respectively. The line is scrolled horizontally as necessary.

In command mode, each character is interpreted as a command. Characters that either do not correspond to commands, are illegal combinations of commands, or are commands that cannot be carried out, all cause beeps. In the following command descriptions, a n indicates that the command can be prefixed by a number (for example, 10l moves right 10 characters); if no number prefix is used, n is assumed to be 1 unless otherwise specified. The term 'current position' refers to the position between the cursor and the character preceding the cursor. A 'word' is a sequence of letters, digits, and underscore characters, or a sequence of non-letter, non-digit, non-underscore, non-white-space characters (for example, ab2*&^ contains two words), and a 'big word' is a sequence of non-white-space characters.

SPECIAL KSH VI COMMANDS

The following commands are not in, or are different from, the normal vi file editor:

n_
Insert a space followed by a big word from the last command in the history at the current position and enter insert mode. If n is specified, that word from the last command is inserted; if n is not specified, the last word is inserted.
#
Insert the comment character (#) at the start of the current line and return the line to the shell (equivalent to I#^J).
ng
Like G, except if n is not specified, it goes to the most recent remembered line.
nv
Edit line n using the vi editor; if n is not specified, the current line is edited. The actual command executed is 'fc -e ${VISUAL:-${EDITOR:-vi}} n'.
* and ^X
Command or file-name expansion is applied to the current big word (with an appended * if the word contains no file-globbing characters); the big word is replaced with the resulting words. If the current big word is the first on the line (or follows one of the following characters: ;, |, &, (, or )) and does not contain a forward slash (/), command expansion is done; otherwise, file-name expansion is done. Command expansion will match the big word against all aliases, functions, and built-in commands, as well as any executable files found by searching the directories in the PATH parameter. File-name expansion matches the big word against the files in the current directory. After expansion, the cursor is placed just past the last word and the editor is in insert mode.
n\, n^F, n<tab>, and n<exc>
Command/file-name completion. Replace the current big word with the longest unique match obtained after performing command/file-name expansion. <tab> is only recognized if the vi-tabcomplete option is set, while <esc> is only recognized if the vi-esccomplete option is set (see set -o). If n is specified, the possible completion specified by n is selected(as reported by the command/file-name enumeration command).
= and ^E
Command/file-name enumeration. List all the commands or files that match the current big word.
^V
Display the version of ksh(1); it is displayed until another key is pressed (this key is ignored).
@c
Macro expansion. Execute the commands found in the alias _c.

INTRA-LINE MOVEMENT COMMANDS

The following commands control movement within the line in vi edit mode.

nh and n^H
Move left n characters.
nl and n<space>
Move right n characters.
0
Move to column 0.
^
Move to the first non-white-space character.
n|
Move to column n.
$
Move to the last character.
nb
Move back n words.
nB
Move back n big words.
ne
Move forward to the end of the word, n times.
nE
Move forward to the end the big word, n times.
nw
Move forward n words.
nW
Move forward n big words.
%
Find match. The editor looks forward for the nearest parenthesis, bracket, or brace, and then moves the to the matching parenthesis, bracket, or brace.
nfc
Move forward to the occurrence of the character c specified by n.
nFc
Move backward to the occurrence of the character c specified by n.
ntc
Move forward to just before the occurrence of the character c specified by n.
nTc
Move backward to just before the occurrence of the character c specified by n.
n;
Repeats the last f, F, t, or T command.
n,
Repeats the last f, F, t, or T command, but moves in the opposite direction.

INTER-LINE MOVEMENT COMMANDS

The following commands control movement between command lines in vi edit mode.

nj and n+ and n^N
Move to next line specified by n in the history
nk and n- and n^P
Move to the previous line specified by n in the history.
nG
Move to line n in the history; if n is not specified, the number of the first remembered line is used.
ng
Like G, except that if n is not specified, it goes to the most recent remembered line.
n/string
Search backward through the history for the occurrence of the line specified by n that contains string; if string starts with ^, the remainder of the string must appear at the start of the history line for it to match.
n?string
Same as /, except it searches forward through the history.
nn
Search for the occurrence specified by n of the last search string; the direction of the search is the same as the last search.
nN
Search for the occurrence specified by n of the last search string; the direction of the search is the opposite of the last search.

EDIT COMMANDS

The following commands edit the command line.

na
Append text n times: goes into insert mode just after the current position. The append is only replicated if command mode is re-entered (that is, <esc> is used).
nA
Same as a, except it appends at the end of the line.
ni
Insert text n times: goes into insert mode at the current position. The insertion is only replicated if command mode is re-entered (that is, <esc> is used).
nI
Same as i, except the insertion is done just before the first non-blank character.
ns
Substitute the next n characters (that is, delete the characters and go into insert mode).
S
Substitute whole line: all characters from the first non-blank character to the end of the line are deleted and insert mode is entered.
ncmove-cmd
Change from the current position to the position resulting from n occurrences of move-cmd (that is, delete the indicated region and go into insert mode); if move-cmd is c, the line starting from the first non-blank character is changed.
C
Change from the current position to the end of the line (that is, delete to the end of the line and go into insert mode).
nx
Delete the next n characters.
nX
Delete the previous n characters.
D
Delete to the end of the line.
ndmove-cmd
Delete from the current position to the position resulting from n occurrences of move-cmd; move-cmd is either a movement command or d, in which case the current line is deleted.
nrc
Replace the next n characters with the character c.
nR
Replace: enter insert mode, but overwrite existing characters instead of inserting before existing characters. The replacement is repeated n times.
n~
Change the case of the next n characters.
nymove-cmd
Yank from the current position to the position resulting from n move-cmds into the yank buffer; if move-cmd is y, the whole line is yanked.
Y
Yank from the current position to the end of the line.
np
Paste the contents of the yank buffer just after the current position, n times.
nP
Same as p, except the buffer is pasted at the current position.

MISCELLANEOUS VI COMMANDS

^J and ^M
The current line is read, parsed, and executed by the shell.
^L and ^R
Redraw the current line.
n.
Redo the last edit command n times.
u
Undo the last edit command.
U
Undo all changes that have been made to the current line.
intr and quit
The interrupt and quit terminal characters cause the current line to be deleted and a new prompt to be printed.

FILES

~/.profile
Personal startup file.
/etc/profile
System-wide startup file; the etc directory might have a different root, depending upon where the Interix distribution is installed.

AUTHORS

This shell is based on the public domain 7th edition Bourne shell clone by Charles Forsyth and parts of the BRL shell by Doug A. Gwyn, Doug Kingston, Ron Natalie, Arnold Robbins, Lou Salkind and others. The first release was created by Eric Gisin, and it was subsequently maintained by John R. MacMillan (chance!john@sq.sq.com), and Simon J. Gerraty (sjg@zen.void.oz.au). The current maintainer is Michael Rendell (michael@cs.mun.ca). The CONTRIBUTORS file in the source distribution contains a more complete list of people and their part in the shell's development.

NOTES

By default, Interix does not execute files with the set-user-ID (setuid) or set-group-ID (setgid) mode bit set for security reasons. If an attempt is made to execute such a file, the ENOSETUID error is returned. For more information and and instructions for enabling execution of files with these mode bits set, see The superuser account and appropriate privileges in Windows Services for UNIX Help.

SEE ALSO

awk(1)

sh(1)

csh(1)

ed(1)

getconf(1)

sed(1)

stty(1)

vi(1)

dup(2)

exec(2)

getgid(2)

getuid(2)

open(2)

pipe(2)

wait(2)

getopt(3)

rand(3)

signal(2)

system(3)

The KornShell Command and Programming Language Morris Bolsky and David Korn, 1989, ISBN 0-13-516972-0.

UNIX Shell Programming Stephen G. Kochan, Patrick H. Wood, Hayden.

IEEE Standard for information Technology Portable Operating System Interface (POSIX) Part 2: Shell and Utilities" , IEEE Inc, 1993, ISBN 1-55937-255-9.