info > ksh(1)

📖 NAME

ksh, rksh — KornShell, a standard/restricted command and programming language.

📋 SYNOPSIS

ksh [ +-abcefhiklmnprstuvxBCDEGH ] [ +-o option ] ... [ - ] [ arg ... ]
rksh [ +-abcefhiklmnpstuvxBCDEGH ] [ +-o option ] ... [ - ] [ arg ... ]

📖 DESCRIPTION

🐚 Ksh is a command and programming language that executes commands read from a terminal or a file. Rksh is a restricted version of the command interpreter ksh; it is used to set up login names and execution environments whose capabilities are more controlled than those of the standard shell. See Invocation below for the meaning of arguments to the shell.

🔤 Definitions

A metacharacter is one of the following characters:

A blank is a tab or a space. An identifier is a sequence of letters, digits, or underscores starting with a letter or underscore. Identifiers are used as components of variable names. A vname is a sequence of one or more identifiers separated by a . and optionally preceded by a .. Vnames are used as function and variable names. A word is a sequence of characters from the character set defined by the current locale, excluding non-quoted metacharacters.

A command is a sequence of characters in the syntax of the shell language. The shell reads each command and carries out the desired action either directly or by invoking separate utilities. A built-in command is a command that is carried out by the shell itself without creating a separate process. Some commands are built-in purely for convenience and are not documented here. Built-ins that cause side effects in the shell environment and built-ins that are found before performing a path search (see Execution below) are documented here. For historical reasons, some of these built-ins behave differently than other built-ins and are called special built-ins.

📜 Commands

A simple-command is a list of variable assignments (see Variable Assignments below) or a sequence of blank separated words which may be preceded by a list of variable assignments (see Environment below). The first word specifies the name of the command to be executed. Except as specified below, the remaining words are passed as arguments to the invoked command. The command name is passed as argument 0 (see exec(2)). The value of a simple-command is its exit status; 0-255 if it terminates normally; 256+signum if it terminates abnormally (the name of the signal corresponding to the exit status can be obtained via the -l option of the kill built-in utility).

A pipeline is a sequence of one or more commands separated by |. The standard output of each command but the last is connected by a pipe(2) to the standard input of the next command. Each command, except possibly the last, is run as a separate process; the shell waits for the last command to terminate. The exit status of a pipeline is the exit status of the last command unless the pipefail option is enabled. Each pipeline can be preceded by the reserved word ! which causes the exit status of the pipeline to become 0 if the exit status of the last command is non-zero, and 1 if the exit status of the last command is 0.

A list is a sequence of one or more pipelines separated by ;, &, |&, &&, or ||, and optionally terminated by ;, &, or |&. Of these five symbols, ;, &, and |& have equal precedence, which is lower than that of && and ||. The symbols && and || also have equal precedence. A semicolon (;) causes sequential execution of the preceding pipeline; an ampersand (&) causes asynchronous execution of the preceding pipeline (i.e., the shell does not wait for that pipeline to finish). The symbol |& causes asynchronous execution of the preceding pipeline with a two-way pipe established to the parent shell; the standard input and output of the spawned pipeline can be written to and read from by the parent shell by applying the redirection operators <& and >& with arg p to commands and by using -p option of the built-in commands read and print described later. The symbol && (||) causes the list following it to be executed only if the preceding pipeline returns a zero (non-zero) value. One or more new-lines may appear in a list instead of a semicolon, to delimit a command. The first item of the first pipeline of a list that is a simple command not beginning with a redirection, and not occurring within a while, until, or if list, can be preceded by a semicolon. This semicolon is ignored unless the showme option is enabled as described with the set built-in below.

A command is either a simple-command or one of the following. Unless otherwise stated, the value returned by a command is that of the last simple-command executed in the command.

The following reserved words are recognized as reserved only when they are the first word of a command and are not quoted:

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

📝 Variable Assignments

One or more variable assignments can start a simple command or can be arguments to the typeset, enum, export, or readonly special built-in commands as well as to other declaration commands created as types. The syntax for an assignment is of the form:

varname=word
varname[word]=word

No space is permitted between varname and the = or between = and word.

varname=(assign_list)

No space is permitted between varname and the =. The variable varname is unset before the assignment. An assign_list can be one of the following:

In addition, a += can be used in place of the = to signify adding to or appending to the previous value. When += is applied to an arithmetic type, word is evaluated as an arithmetic expression and added to the current value. When applied to a string variable, the value defined by word is appended to the value. For compound assignments, the previous value is not unset and the new values are appended to the current ones provided that the types are compatible.

The right hand side of a variable assignment undergoes all the expansion listed below except word splitting, brace expansion, and pathname expansion. When the left hand side is an assignment is a compound variable and the right hand is the name of a compound variable, the compound variable on the right will be copied or appended to the compound variable on the left.

💬 Comments

A word beginning with # causes that word and all the following characters up to a new-line to be ignored.

🔗 Aliasing

The first word of each command is replaced by the text of an alias if an alias for this word has been defined. An alias name consists of any number of characters excluding metacharacters, quoting characters, file expansion characters, parameter expansion and command substitution characters, the characters / and =. The replacement string can contain any valid shell script including the metacharacters listed above. The first word of each command in the replaced text, other than any that are in the process of being replaced, will be tested for aliases. If the last character of the alias value is a blank then the word following the alias will also be checked for alias substitution. Aliases can be used to redefine built-in commands but cannot be used to redefine the reserved words listed above. Aliases can be created and listed with the alias command and can be removed with the unalias command.

Aliasing is performed when scripts are read, not while they are executed. Therefore, for an alias to take effect, the alias definition command has to be executed before the command which references the alias is read.

The following aliases are automatically preset when the shell is invoked as an interactive shell, unless invoked in POSIX compliance mode (see Invocation below). Preset aliases can be unset or redefined.

history='hist -l'
r='hist -s'

🔄 Tilde Expansion

After alias substitution is performed, each word is checked to see if it begins with an unquoted ~. For tilde expansion, word also refers to the word portion of parameter expansion (see Parameter Expansion below). If a word is preceded by a tilde, then it is checked up to a / to see if it matches a user name in the password database (see getpwnam(3)). If a match is found, the ~ and the matched login name are replaced by the login directory of the matched user. If no match is found, the original text is left unchanged. A ~ by itself, or in front of a /, is replaced by $HOME, unless the HOME variable is unset, in which case the current user's home directory as configured in the operating system is used. A ~ followed by a + or - is replaced by $PWD or $OLDPWD respectively.

In addition, when expanding a variable assignment (see Variable Assignments above), tilde expansion is attempted when the value of the assignment begins with a ~, and when a ~ appears after a :. A : also terminates a user name following a ~.

The tilde expansion mechanism may be extended or modified by defining one of the discipline functions .sh.tilde.set or .sh.tilde.get (see Functions and Discipline Functions below). If either exists, then upon encountering a tilde word to expand, that function is called with the tilde word assigned to either .sh.value (for the .sh.tilde.set function) or .sh.tilde (for the .sh.tilde.get function). Performing tilde expansion within a discipline function will not recursively call that function, but default tilde expansion remains active, so literal tildes should still be quoted where required. Either function may assign a replacement string to .sh.value. If this value is non-empty and does not start with a ~, it replaces the default tilde expansion when the function terminates. Otherwise, the tilde expansion is left unchanged.

📦 Command Substitution

The standard output from a command list enclosed in parentheses preceded by a dollar sign ( $(list) ), or in a brace group preceded by a dollar sign ( ${ list;} ), or in a pair of grave accents (``) may be used as part or all of a word; trailing new-lines are removed. In the second case, the { and } are treated as a reserved words so that { must be followed by a blank and } must appear at the beginning of the line or follow a ;. In the third (obsolete) form, the string between the quotes is processed for special quoting characters before the command is executed (see Quoting below). The command substitution $(cat file) can be replaced by the equivalent but faster $(<file). The command substitution $(n<#) will expand to the current byte offset for file descriptor n. Except for the second form, the command list is run in a subshell so that no side effects are possible. For the second form, the final } will be recognized as a reserved word after any token.

➗ Arithmetic Expansion

An arithmetic expression enclosed in double parentheses preceded by a dollar sign ( $(()) ) is replaced by the value of the arithmetic expression within the double parentheses.

🔗 Process Substitution

Each command argument of the form <(list) or >(list) will run process list asynchronously connected to some file in /dev/fd if this directory exists, or else a fifo a temporary directory. The name of this file will become the argument to the command. If the form with > is selected then writing on this file will provide input for list. If < is used, then the file passed as an argument will contain the output of the list process. For example,

paste <(cut -f1 file1) <(cut -f3 file2) | tee >(process1) >(process2)

cuts fields 1 and 3 from the files file1 and file2 respectively, pastes the results together, and sends it to the processes process1 and process2, as well as putting it onto the standard output. Note that the file, which is passed as an argument to the command, is a UNIX pipe(2) so programs that expect to lseek(2) on the file will not work.

Process substitution of the form <(list) can also be used with the < redirection operator which causes the output of list to be standard input or the input for whatever file descriptor is specified.

📐 Parameter Expansion

A parameter is a variable, one or more digits, or any of the characters *, @, #, ?, -, $, and !. A variable is denoted by a vname. To create a variable whose vname contains a ., a variable whose vname consists of everything before the last . must already exist. A variable has a value and zero or more attributes. Variables can be assigned values and attributes by using the typeset special built-in command. The attributes supported by the shell are described later with the typeset special built-in command. Exported variables pass their attributes to the environment so that a newly invoked ksh that is a child or exec'd process of the current shell will automatically import them, unless the posix shell option is on.

The shell supports both indexed and associative arrays. An element of an array variable is referenced by a subscript. A subscript for an indexed array is denoted by an arithmetic expression (see Arithmetic Evaluation below) between a [ and a ]. To assign values to an indexed array, use vname=(value ...) or set -A vname value .... The value of all non-negative subscripts must be in the range of 0 through 4,194,303. A negative subscript is treated as an offset from the maximum current index +1 so that -1 refers to the last element. Indexed arrays can be declared with the -a option to typeset. Indexed arrays need not be declared. Any reference to a variable with a valid subscript is legal and an array will be created if necessary.

An associative array is created with the -A option to typeset. A subscript for an associative array is denoted by a string enclosed between [ and ].

Referencing any array without a subscript is equivalent to referencing the array with subscript 0.

The value of a variable may be assigned by writing:

vname=value [ vname=value ] ...

or

vname[subscript]=value [ vname[subscript]=value ] ...

Note that no space is allowed before or after the =.

Attributes assigned by the typeset special built-in command apply to all elements of the array. An array element can be a simple variable, a compound variable or an array variable. An element of an indexed array can be either an indexed array or an associative array. An element of an associative array can also be either. To refer to an array element that is part of an array element, concatenate the subscript in brackets. For example, to refer to the foobar element of an associative array that is defined as the third element of the indexed array, use ${vname[3][foobar]}.

A nameref is a variable that is a reference to another variable. A nameref is created with the -n attribute of typeset. The value of the variable at the time of the typeset command becomes the variable that will be referenced whenever the nameref variable is used. The name of a nameref cannot contain a .. When a variable or function name contains a ., and the portion of the name up to the first . matches the name of a nameref, the variable referred to is obtained by replacing the nameref portion with the name of the variable referenced by the nameref. If a nameref is used as the index of a for loop, a name reference is established for each item in the list. A nameref provides a convenient way to refer to the variable inside a function whose name is passed as an argument to a function. For example, if the name of a variable is passed as the first argument to a function, the command

typeset -n var=$1

inside the function causes references and assignments to var to be references and assignments to the variable whose name has been passed to the function.

If any of the floating point attributes, -E, -F, or -X, or the integer attribute, -i, is set for vname, then the value is subject to arithmetic evaluation as described below.

Positional parameters, parameters denoted by a number, may be assigned values with the set special built-in command. Parameter $0 is set from argument zero when the shell is invoked.

The character $ is used to introduce substitutable parameters.

In the above, word is not evaluated unless it is to be used as the substituted string, so that, in the following example, pwd is executed only if d is not set or is null:

print ${d:-$(pwd)}

If the colon ( : ) is omitted from the above expressions, then the shell only checks whether parameter is set or not.

⚙️ Shell Variables

The following parameters are automatically set by the shell:

The following variables are used by the shell:

The shell gives default values to PATH, PS1, PS2, PS3, PS4, MAILCHECK, FCEDIT, TMOUT and IFS, while HOME, SHELL, ENV, and MAIL are not set at all by the shell (although HOME is set by login(1)). On some systems MAIL and SHELL are also set by login(1).

✂️ Field Splitting

After parameter expansion and command substitution, the results of substitutions are scanned for the field separator characters (those found in IFS) and split into distinct fields where such characters are found. Explicit null fields ("" or '') are retained. Implicit null fields (those resulting from parameters that have no values or command substitutions with no output) are removed.

🔄 Brace Expansion

If the braceexpand (-B) option is set then each of the fields resulting from IFS are checked to see if they contain one or more of the brace patterns {*,*}, {l1..l2}, {n1..n2}, {n1..n2% fmt}, {n1..n2 ..n3}, or {n1..n2 ..n3%fmt}, where * represents any character, l1,l2 are letters and n1,n2,n3 are signed numbers and fmt is a format specified as used by printf. In each case, fields are created by prepending the characters before the { and appending the characters after the } to each of the strings generated by the characters between the { and }. The resulting fields are checked to see if they have any brace patterns.

In the first form, a field is created for each string between { and ,, between , and ,, and between , and }. The string represented by * can contain embedded matching { and } without quoting. Otherwise, each { and } with * must be quoted.

In the seconds form, l1 and l2 must both be either upper case or both be lower case characters in the C locale. In this case a field is created for each character from l1 thru l2.

In the remaining forms, a field is created for each number starting at n1 and continuing until it reaches n2 incrementing n1 by n3. The cases where n3 is not specified behave as if n3 where 1 if n1<=n2 and -1 otherwise. If forms which specify %fmt any format flags, widths and precisions can be specified and fmt can end in any of the specifiers cdiouxX. For example, {a,z}{1..5..3%02d}{b..c}x expands to the 8 fields, a01bx, a01cx, a04bx, a04cx, z01bx, z01cx, z04bx and z04cx.

📁 Pathname Expansion

This is also known as globbing or sometimes filename generation. Following splitting, each field is scanned for the characters *, ?, (, and [ unless the -f option has been set. If one of these characters appears, then the word is regarded as a pattern. Each file name component that contains any pattern character is replaced with a lexicographically sorted set of names that matches the pattern from that directory. If no file name is found that matches the pattern, then that component of the filename is left unchanged unless the pattern is prefixed with ~(N) in which case it is removed as described below. The special traversal names . and .. are never matched. If FIGNORE is set, then each file name component that matches the pattern defined by the value of FIGNORE is ignored when generating the matching filenames. If FIGNORE is not set, the character . at the start of each file name component will be ignored unless the first character of the pattern corresponding to this component is the character . itself. Note, that for other uses of pattern matching the / and . are not treated specially.

A pattern-list is a list of one or more patterns separated from each other with a & or |. A & signifies that all patterns must be matched whereas | requires that only one pattern be matched. Composite patterns can be formed with one or more of the following subpatterns:

By default, each pattern, or subpattern will match the longest string possible consistent with generating the longest overall match. If more than one match is possible, the one starting closest to the beginning of the string will be chosen. However, for each of the above compound patterns a - can be inserted in front of the ( to cause the shortest match to the specified pattern-list to be used.

When pattern-list is contained within parentheses, the backslash character \ is treated specially even when inside a character class. All ANSI C character escapes are recognized and match the specified character. In addition the following escape sequences are recognized:

A pattern of the form %(pattern-pair(s)) is a subpattern that can be used to match nested character expressions. Each pattern-pair is a two character sequence which cannot contain & or |. The first pattern-pair specifies the starting and ending characters for the match. Each subsequent pattern-pair represents the beginning and ending characters of a nested group that will be skipped over when counting starting and ending character matches. The behavior is unspecified when the first character of a pattern-pair is alphanumeric except for the following:

Thus, %({}Q"E\), matches characters starting at { until the matching } is found not counting any { or } that is inside a double quoted string or preceded by the escape character \. Without the {} this pattern matches any C language string.

Each subpattern in a composite pattern is numbered, starting at 1, by the location of the ( within the pattern. The sequence \n, where n is a single digit and \n comes after the n-th subpattern, matches the same string as the subpattern itself.

Finally a pattern can contain subpatterns of the form ~(options:pattern-list), where either options or :pattern-list can be omitted. Unlike the other compound patterns, these subpatterns are not counted in the numbered subpatterns. :pattern-list must be omitted for options F, G, N, and V below. If options is present, it can consist of one or more of the following:

If both options and :pattern-list are specified, then the options apply only to pattern-list. Otherwise, these options remain in effect until they are disabled by a subsequent ~(...) or at the end of the subpattern containing ~(...).

💬 Quoting

Each of the metacharacters listed earlier (see Definitions above) has a special meaning to the shell and causes termination of a word unless quoted. A character may be quoted (i.e., made to stand for itself) by preceding it with a \. The pair \new-line is removed. All characters enclosed between a pair of single quote marks ('') that is not preceded by a $ are quoted. A single quote cannot appear within the single quotes. A single quoted string preceded by an unquoted $ is processed as an ANSI C string except for the following:

Inside double quote marks (""), parameter and command substitution occur and \ quotes the characters \, `, ", and $. A $ in front of a double quoted string will be ignored in the "C" or "POSIX" locale, and may cause the string to be replaced by a locale specific string otherwise.

The meaning of $* and $@ is identical when not quoted or when used as a variable assignment value or as a file name. However, when used as a command argument, "$*" is equivalent to "$1d$2d...", where d is the first character of the IFS variable, whereas "$@" is equivalent to "$1" "$2" ....

Inside grave quote marks (``), \ quotes the characters \, `, and $. If the grave quotes occur within double quotes, then \ also quotes the character ".

The special meaning of reserved words or aliases can be removed by quoting any character of the reserved word. The recognition of function names or built-in command names listed below cannot be altered by quoting them.

🔢 Arithmetic Evaluation

The shell performs arithmetic evaluation for arithmetic expansion, to evaluate an arithmetic command, to evaluate an indexed array subscript, and to evaluate arguments to the built-in commands shift and let as well as arguments to numeric format specifiers given to print -f and printf. Evaluations are performed using double precision floating point arithmetic or long double precision floating point for systems that provide this data type. Floating point constants follow the ANSI C programming language floating point conventions. The case-insensitive floating point constants NaN and Inf can be used to represent "not a number" and infinity respectively, unless the posix shell option is on. Integer constants follow the ANSI C programming language integer constant conventions although only single byte character constants are recognized and character casts are not recognized. In addition constants can be of the form [base#]n where base is a decimal number between two and sixty-four representing the arithmetic base and n is a number in that base. The digits above 9 are represented by the lower case letters, the upper case letters, @, and _ respectively. For bases less than or equal to 36, upper and lower case characters can be used interchangeably.

An arithmetic expression uses the same syntax, precedence, and associativity of expression as the C language. All the C language operators that apply to floating point quantities can be used. In addition, the operator ** can be used for exponentiation. It has higher precedence than multiplication and is left associative. In addition, when the value of an arithmetic variable or subexpression can be represented as a long integer, all C language integer arithmetic operations can be performed. Variables can be referenced by name within an arithmetic expression without using the parameter expansion syntax. When a variable is referenced, its value is evaluated as an arithmetic expression.

Any of the following math library functions that are in the C math library can be used within an arithmetic expression:

abs  acos  acosh  asin  asinh  atan  atan2  atanh  cbrt  ceil  copysign  cos  cosh
erf  erfc  exp  exp10  exp2  expm1  fabs  fdim  finite  float  floor  fma  fmax
fmin  fmod  fpclass  fpclassify  hypot  ilogb  int  isfinite  isgreater  isgreaterequal
isinf  isinfinite  isless  islessequal  islessgreater  isnan  isnormal  issubnormal
isunordered  iszero  j0  j1  jn  ldexp  lgamma  log  log10  log1p  log2  logb
nearbyint  nextafter  nexttoward  pow  remainder  rint  round  scalb  scalbn  signbit
sin  sinh  sqrt  tan  tanh  tgamma  trunc  y0  y1  yn

In addition, arithmetic functions can be defined as shell functions with a variant of the function name syntax,

function .sh.math.name ident ... { list ;}

where name is the function name used in the arithmetic expression and each identifier, ident is a name reference to the long double precision floating point argument. The value of .sh.value when the function returns is the value of this function. User defined functions can take up to 3 arguments and override C math library functions.

An internal representation of a variable as a double precision floating point can be specified with the -E [n], -F [n], or -X [n] option of the typeset special built-in command. The -E option causes the expansion of the value to be represented using scientific notation when it is expanded. The optional option argument n defines the number of significant figures. The -F option causes the expansion to be represented as a floating decimal number when it is expanded. The -X option causes the expansion to be represented using the %a format defined by ISO C-99. The optional option argument n defines the number of places after the decimal (or radix) point in this case.

An internal integer representation of a variable can be specified with the -i [n] option of the typeset special built-in command. The optional option argument n specifies an arithmetic base to be used when expanding the variable. If you do not specify an arithmetic base, base 10 will be used.

Arithmetic evaluation is performed on the value of each assignment to a variable with the -E, -F, -X, or -i attribute. Assigning a floating point number to a variable whose type is an integer causes the fractional part to be truncated.

💡 Prompting

When used interactively, the shell prompts with the value of PS1 after expanding it for parameter expansion, command substitution, and arithmetic expansion, before reading a command. In addition, each single ! in the prompt is replaced by the command number. A !! is required to place ! in the prompt. If at any time a new-line is typed and further input is needed to complete a command, then the secondary prompt (i.e., the value of PS2) is issued.

❓ Conditional Expressions

A conditional expression is used with the [[ compound command to test attributes of files and to compare strings. Field splitting and pathname expansion are not performed on the words between [[ and ]]. Each expression can be constructed from one or more of the following unary or binary expressions:

The following obsolete arithmetic comparisons are also permitted:

In each of the above expressions, if file is of the form /dev/fd/n, where n is an integer, then the test is applied to the open file whose descriptor number is n.

A compound expression can be constructed from these primitives by using any of the following, listed in decreasing order of precedence.

🔀 Input/Output

Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. The following may appear anywhere in a simple-command or may precede or follow a command and are not passed on to the invoked command. Command substitution, parameter expansion, and arithmetic expansion occur before word or digit is used except as noted below. Pathname expansion occurs only if the shell is interactive and the pattern matches a single file. Field splitting is not performed.

In each of the following redirections, if file is of the form /dev/sctp/host/port, /dev/tcp/host/port, or /dev/udp/host/port, where host is a hostname or host address, and port is a service given by name or an integer port number, then the redirection attempts to make a tcp, sctp or udp connection to the corresponding socket.

No intervening space is allowed between the characters of redirection operators.

If one of the above is preceded by a digit, with no intervening space, then the file descriptor number referred to is that specified by the digit (instead of the default 0 or 1). If one of the above, other than >&- and the ># and <# forms, is preceded by {varname} with no intervening space, then a file descriptor number > 9 will be selected by the shell and stored in the variable varname, so it can be read from or written to with redirections like <& $varname or >& $varname. If >&- or the any of the ># and <# forms is preceded by {varname} the value of varname defines the file descriptor to close or position. For example:

... 2>&1

means file descriptor 2 is to be opened for writing as a duplicate of file descriptor 1 and

exec {n}<file

means open file named file for reading and store the file descriptor number in variable n.

A special shorthand redirection operator &>word is available; it is equivalent to >word 2>&1. It cannot be preceded by any digit or variable name. This shorthand is disabled if the posix shell option is active.

The order in which redirections are specified is significant. The shell evaluates each redirection in terms of the (file descriptor, file) association at the time of evaluation. For example:

... 1>fname 2>&1

first associates file descriptor 1 with file fname. It then associates file descriptor 2 with the file associated with file descriptor 1 (i.e. fname). If the order of redirections were reversed, file descriptor 2 would be associated with the terminal (assuming file descriptor 1 had been) and then file descriptor 1 would be associated with file fname.

If a command is followed by & and job control is not active, then the default standard input for the command is the empty file /dev/null. Otherwise, the environment for the execution of a command contains the file descriptors of the invoking shell as modified by input/output specifications.

🌐 Environment

The environment (see environ(7)) is a list of name-value pairs that is passed to an executed program in the same way as a normal argument list. The names must be identifiers and the values are character strings. The shell interacts with the environment in several ways. On invocation, the shell scans the environment and creates a variable for each name found, giving it the corresponding value and attributes and marking it export. Executed commands inherit the environment. If the user modifies the values of these variables or creates new ones, using the export or typeset -x commands, they become part of the environment.

The environment seen by any executed command is thus composed of any name-value pairs originally inherited by the shell, whose values may be modified by the current shell, plus any additions which must be noted in export or typeset -x commands.

The environment for any simple-command or function may be augmented by prefixing it with one or more variable assignments. A variable assignment argument is a word of the form identifier=value. Thus:

TERM=450 cmd args                  and
(export TERM; TERM=450; cmd args)

are equivalent (as far as the above execution of cmd is concerned except for special built-in commands listed below - those that are marked with <*>).

If the obsolete -k option is set, all variable assignment arguments are placed in the environment, even if they occur after the command name. The following first prints a=b c and then c:

echo a=b c
set -k
echo a=b c

This feature is intended for use with scripts written for early versions of the shell and its use in new scripts is strongly discouraged. It is likely to disappear someday.

🧩 Functions

For historical reasons, there are two ways to define functions, the name() syntax and the function name syntax, described in the Commands section above. Shell functions are read in and stored internally. Alias names are resolved when the function is read. Functions are executed like commands with the arguments passed as positional parameters. (See Execution below.)

Functions defined by the function name syntax and called by name execute in the same process as the caller and share all files and present working directory with the caller. Traps caught by the caller are reset to their default action inside the function. A trap condition that is not caught or ignored by the function causes the function to terminate and the condition to be passed on to the caller. A trap on EXIT set inside a function is executed in the environment of the caller after the function completes. Ordinarily, variables are shared between the calling program and the function. However, the typeset special built-in command used within a function defines local variables whose scope includes the current function. They can be passed to functions that they call in the variable assignment list that precedes the call or as arguments passed as name references. Errors within functions return control to the caller.

Functions defined with the name() syntax and functions defined with the function name syntax that are invoked with the . special built-in are executed in the caller's environment and share all variables and traps with the caller. Errors within these function executions cause the script that contains them to abort.

The special built-in command return is used to return from function calls.

Function names can be listed with the -f or +f option of the typeset special built-in command. The text of functions, when available, will also be listed with -f. Functions can be undefined with the -f option of the unset special built-in command.

Ordinarily, functions are unset when the shell executes a shell script. Functions that need to be defined across separate invocations of the shell should be placed in a directory and the FPATH variable should contain the name of this directory. They may also be specified in the ENV file.

🔧 Discipline Functions

Each variable can have zero or more discipline functions associated with it. The shell initially understands the discipline names get, set, append, and unset but can be added when defining new types. On most systems others can be added at run time via the C programming interface extension provided by the builtin built-in utility. If the get discipline is defined for a variable, it is invoked whenever the given variable is referenced. If the variable .sh.value is assigned a value inside the discipline function, the referenced variable will evaluate to this value instead. If the set discipline is defined for a variable, it is invoked whenever the given variable is assigned a value. If the append discipline is defined for a variable, it is invoked whenever a value is appended to the given variable. The variable .sh.value is given the value of the variable before invoking the discipline, and the variable will be assigned the value of .sh.value after the discipline completes. If .sh.value is unset inside the discipline, then that value is unchanged. If the unset discipline is defined for a variable, it is invoked whenever the given variable is unset. The variable will not be unset unless it is unset explicitly from within this discipline function.

The variable .sh.name contains the name of the variable for which the discipline function is called, .sh.subscript is the subscript of the variable, and .sh.value will contain the value being assigned inside the set discipline function. The variable _ is a reference to the variable including the subscript if any. For the set discipline, changing .sh.value will change the value that gets assigned. Finally, the expansion ${var.name}, when name is the name of a discipline, and there is no variable of this name, is equivalent to the command substitution ${ var.name;}.

📛 Name Spaces

Commands and functions that are executed as part of the list of a namespace command that modify variables or create new ones, create a new variable whose name is the name of the name space as given by identifier preceded by .. When a variable whose name is name is referenced, it is first searched for using .identifier.name. Similarly, a function defined by a command in the namespace list is created using the name space name preceded by a ..

When the list of a namespace command contains a namespace command, the names of variables and functions that are created consist of the variable or function name preceded by the list of identifiers each preceded by ..

Outside of a name space, a variable or function created inside a name space can be referenced by preceding it with the name space name.

By default, variables starting with .sh are in the sh name space.

📦 Type Variables

Typed variables provide a way to create data structure and objects. A type can be defined either by a shared library, by the enum built-in command described below, or by using the new -T option of the typeset built-in command. With the -T option of typeset, the type name, specified as an option argument to -T, is set with a compound variable assignment that defines the type. Function definitions can appear inside the compound variable assignment and these become discipline functions for this type and can be invoked or redefined by each instance of the type. The function name create is treated specially. It is invoked for each instance of the type that is created but is not inherited and cannot be redefined for each instance.

When a type is defined a special built-in command of that name is added. These built-ins are declaration commands and follow the same expansion rules as the built-in commands described below that are marked with a <**> symbol. These commands can subsequently be used inside further type definitions. The man page for these commands can be generated by using the --man option or any of the other -- options described with getopts. The -r, -a, -A, -h, and -S options of typeset are permitted with each of these new built-ins.

An instance of a type is created by invoking the type name followed by one or more instance names. Each instance of the type is initialized with a copy of the subvariables except for subvariables that are defined with the -S option. Variables defined with the -S are shared by all instances of the type. Each instance can change the value of any subvariable and can also define new discipline functions of the same names as those defined by the type definition as well as any standard discipline names. No additional subvariables can be defined for any instance.

When defining a type, if the value of a subvariable is not set and the -r attribute is specified, it causes the subvariable to be a required subvariable. Whenever an instance of a type is created, all required subvariables must be specified. These subvariables become read-only in each instance.

When unset is invoked on a subvariable within a type, and the -r attribute has not been specified for this field, the value is reset to the default value associative with the type. Invoking unset on a type instance not contained within another type deletes all subvariables and the variable itself.

A type definition can be derived from another type definition by defining the first subvariable name as _ and defining its type as the base type. Any remaining definitions will be additions and modifications that apply to the new type. If the new type name is the same as that of the base type, the type will be replaced and the original type will no longer be accessible.

The typeset command with the -T and no option argument or operands will write all the type definitions to standard output in a form that can be read in to create all they types.

🔧 Jobs

If the monitor option of the set command is turned on, an interactive shell associates a job with each pipeline. It keeps a table of current jobs, printed by the jobs command, and assigns them small integer numbers. When a job is started asynchronously with &, the shell prints a line which looks like:

[1] 1234

indicating that the job which was started asynchronously was job number 1 and had one (top-level) process, whose process id was 1234.

This paragraph and the next require features that are not in all versions of UNIX and may not apply. If you are running a job and wish to do something else you may hit the key ^Z (control-Z) which sends a STOP signal to the current job. The shell will then normally indicate that the job has been 'Stopped', and print another prompt. You can then manipulate the state of this job, putting it in the background with the bg command, or run some other commands and then eventually bring the job back into the foreground with the foreground command fg. A ^Z takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed.

A job being run in the background will stop if it tries to read from the terminal. Background jobs are normally allowed to produce output, but this can be disabled by giving the command stty tostop. If you set this tty option, then background jobs will stop when they try to produce output like they do when they try to read input.

A job pool is a collection of jobs started with list & associated with a name.

There are several ways to refer to jobs in the shell. A job can be referred to by the process id of any process of the job or by one of the following:

In addition, unless noted otherwise, wherever a job can be specified, the name of a background job pool can be used to represent all the jobs in that pool.

The shell learns immediately whenever a process changes state. It normally informs you whenever a job becomes blocked so that no further progress is possible, but only just before it prints a prompt. This is done so that it does not otherwise disturb your work. The notify option of the set command causes the shell to print these job change messages as soon as they occur.

When the monitor option is on, each background job that completes triggers any trap set for CHLD.

When you try to leave the shell while jobs are running or stopped, you will be warned that `You have stopped(running) jobs.' You may use the jobs command to see what they are. If you immediately try to exit again, the shell will not warn you a second time, and the stopped jobs will be terminated.

When a login shell receives a HUP signal, it sends a HUP signal to each job that has not been disowned with the disown built-in command described below.

🚦 Signals

The INT and QUIT signals for an invoked command are ignored if the command is followed by & and the monitor option is not active. Otherwise, signals have the values inherited by the shell from its parent (but see also the trap built-in command below).

⚡ Execution

Each time a command is read, the above expansions and substitutions are carried out. If the command name matches one of the Special Built-in Commands listed below, it is executed within the current shell process. Next, the command name is checked to see if it matches a user defined function. If it does, the positional parameters are saved and then reset to the arguments of the function call. A function is also executed in the current shell process. When the function completes or issues a return, the positional parameter list is restored. For functions defined with the function name syntax, any trap set on EXIT within the function is executed. The exit value of a function is the value of the last command executed. If a command name is not a special built-in command or a user defined function, but it is one of the built-in commands listed below, it is executed in the current shell process.

The shell variables PATH followed by the variable FPATH defines the list of directories to search for the command name. Alternative directory names are separated by a colon (:). The default path is the value that was output by getconf PATH at the time ksh was compiled. The current directory can be specified by two or more adjacent colons, or by a colon at the beginning or end of the path list. If the command name contains a /, then the search path is not used. Otherwise, each directory in the list of directories defined by PATH and FPATH is checked in order. If the directory being searched is contained in FPATH and contains a file whose name matches the command being searched, then this file is loaded into the current shell environment as if it were the argument to the . command except that only preset aliases are expanded, and a function of the given name is executed as described above.

If this directory is not in FPATH the shell first determines whether there is a built-in version of a command corresponding to a given pathname and if so it is invoked in the current process. If no built-in is found, the shell checks for a file named .paths in this directory. If found and there is a line of the form FPATH=path where path names an existing directory then that directory is searched immediately after the current directory as if it were found in the FPATH variable. If path does not begin with /, it is checked for relative to the directory being searched. The .paths file is then checked for a line of the form PLUGIN_LIB=libname [ : libname ] .... Each library named by libname will be searched for as if it were an option argument to builtin -f, and if it contains a built-in of the specified name this will be executed instead of a command by this name. Any built-in loaded from a library found this way will be associated with the directory containing the .paths file so it will only execute if not found in an earlier directory.

Finally, the directory will be checked for a file of the given name. If the file has execute permission but is not an a.out file, it is assumed to be a file containing shell commands. A separate shell is spawned to read it. All non-exported variables are removed in this case. If the shell command file doesn't have read permission, or if the setuid and/or setgid bits are set on the file, then the shell executes an agent whose job it is to set up the permissions and execute the shell with the shell command file passed down as an open file. If the .paths contains a line of the form name=value in the first or second line, then the environment variable name is modified by prepending the directory specified by value to the directory list. If value is not an absolute directory, then it specifies a directory relative to the directory that the executable was found. If the environment variable name does not already exist it will be added to the environment list for the specified command.

A parenthesized command is executed in a subshell without removing non-exported variables.

🔄 Command Re-entry

The text of the last HISTSIZE (default 512) commands entered from a terminal device is saved in a history file. The file $HOME/.sh_history is used if the HISTFILE variable is not set or if the file it names is not writable. A shell can access the commands of all interactive shells which use the same named HISTFILE. The built-in command hist is used to list or edit a portion of this file. The portion of the file to be edited or listed can be selected by number or by giving the first character or characters of the command. A single command or range of commands can be specified. If you do not specify an editor program as an argument to hist then the value of the variable HISTEDIT is used. If HISTEDIT is unset, the obsolete variable FCEDIT is used. If FCEDIT is not defined, then /bin/ed is used. The edited command(s) is printed and re-executed upon leaving the editor unless you quit without writing. The -s option (and in obsolete versions, the editor name -) is used to skip the editing phase and to re-execute the command. In this case a substitution parameter of the form old=new can be used to modify the command before execution. For example, with the preset alias r, which is aliased to 'hist -s', typing r bad=good c will re-execute the most recent command which starts with the letter c, replacing the first occurrence of the string bad with the string good.

✏️ In-line Editing Options

Normally, each command line entered from a terminal device is simply typed followed by a new-line (`RETURN' or `LINE FEED'). If either the emacs, gmacs, or vi option is active, the user can edit the command line. To be in either of these edit modes set the corresponding option. An editing option is automatically selected each time the VISUAL or EDITOR variable is assigned a value ending in either of these option names.

The editing features require that the user's terminal accept `RETURN' as carriage return without line feed and that a space (` ') must overwrite the current character on the screen.

Unless the multiline option is on, the editing modes implement a concept where the user is looking through a window at the current line. The window width is the value of COLUMNS if it is defined, otherwise 80. If the window width is too small to display the prompt and leave at least 8 columns to enter input, the prompt is truncated from the left. If the line is longer than the window width minus two, a mark is displayed at the end of the window to notify the user. As the cursor moves and reaches the window boundaries the window will be centered about the cursor. The mark is a > (<, *) if the line extends on the right (left, both) side(s) of the window.

The search commands in each edit mode provide access to the history file. Only strings are matched, not patterns, although a leading ^ in the string restricts the match to begin at the first character in the line.

Each of the edit modes has an operation to list the files or commands that match a partially entered word. When applied to the first word on the line, or the first word after a ;, |, &, or (, and the word does not begin with ~ or contain a /, the list of aliases, functions, and executable commands defined by the PATH variable that could match the partial word is displayed. Otherwise, the list of files that match the given word is displayed. If the partially entered word does not contain any file expansion characters, a * is appended before generating these lists. After displaying the generated list, the input line is redrawn. These operations are called command name listing and file name listing, respectively. There are additional operations, referred to as command name completion and file name completion, which compute the list of matching commands or files, but instead of printing the list, replace the current word with a complete or partial match. For file name completion, if the match is unique, a / is appended if the file is a directory and a space is appended if the file is not a directory. Otherwise, the longest common prefix for all the matching files replaces the word. For command name completion, only the portion of the file names after the last / are used to find the longest command prefix. If only a single name matches this prefix, then the word is replaced with the command name followed by a space. When using a tab for completion that does not yield a unique match, a subsequent tab will provide a numbered list of matching alternatives. A specific selection can be made by entering the selection number followed by a tab.

⌨️ Key Bindings

The KEYBD trap can be used to intercept keys as they are typed and change the characters that are actually seen by the shell. This trap is executed after each character (or sequence of characters when the first character is ESC) is entered while reading from a terminal. The variable .sh.edchar contains the character or character sequence which generated the trap. Changing the value of .sh.edchar in the trap action causes the shell to behave as if the new value were entered from the keyboard rather than the original value.

The variable .sh.edcol is set to the input column number of the cursor at the time of the input. The variable .sh.edmode is set to ESC when in vi insert mode (see below) and is null otherwise. By prepending ${.sh.editmode} to a value assigned to .sh.edchar it will cause the shell to change to control mode if it is not already in this mode.

This trap is not invoked for characters entered as arguments to editing directives, or while reading input for a character search.

📝 Emacs Editing Mode

This mode is entered by enabling either the emacs or gmacs option. The only difference between these two modes is the way they handle ^T. To edit, the user moves the cursor to the point needing correction and then inserts or deletes characters or words as needed. All the editing commands are control characters or escape sequences. The notation for control characters is caret (^) followed by the character. For example, ^F is the notation for control F. This is entered by depressing `f' while holding down the `CTRL' (control) key. The `SHIFT' key is not depressed. (The notation ^? indicates the DEL (delete) key.)

The notation for escape sequences is M- followed by a character. For example, M-f (pronounced Meta f) is entered by depressing ESC (ASCII 033) followed by `f'. (M-F would be the notation for ESC followed by `SHIFT' (capital) `F'.)

All edit commands operate from any place on the line (not just at the beginning). Neither the `RETURN' nor the `LINE FEED' key is entered after edit commands except when noted.

The M-[ multi-character commands below are DEC VT220 escape sequences generated by special keys on standard PC keyboards, such as the arrow keys. You could type them directly but they are meant to recognize the keys in question, which are indicated in parentheses.

📝 Vi Editing Mode

There are two typing modes. Initially, when you enter a command you are in the input mode. To edit, the user enters control mode by typing ESC (033) and moves the cursor to the point needing correction and then inserts or deletes characters or words as needed. Most control commands accept an optional repeat count prior to the command.

The notation for control characters used below is ^ followed by a character. For instance, ^H is entered by holding down the Control key and pressing H. ^[ (Control+[) is equivalent to the ESC key.

The notation for escape sequences is ^[ followed by one or more characters. The ^[[ (ESC [) multi-character commands below are DEC VT220 escape sequences generated by special keys on standard PC keyboards, such as the arrow keys, which are indicated in parentheses. When in input mode, these keys will switch you to control mode before performing the associated action. These sequences can use preceding repeat count parameters, but only when the ^[ and the subsequent [ are entered into the input buffer at the same time, such as when pressing one of those keys.

Input Edit Commands By default the editor is in input mode.

Motion Edit Commands These commands will move the cursor.

Search Edit Commands These commands access your command history.

📖 DESCRIPTION

🔍 N — Search for next match of the last pattern to / or ?, but in reverse direction.

✏️ Text Modification Edit Commands

These commands will modify the line.

🧰 Other Edit Commands

Miscellaneous commands.

🏗️ Built-in Commands

The simple-commands listed below are built in to the shell and are executed in the same process as the shell. The effects of any added Input/Output redirections are local to the command, except for the exec and redirect commands. Unless otherwise indicated, the output is written on standard output (file descriptor 1) and the exit status, when there is no syntax error, is zero. Except for :, true, false, and echo, all built-in commands accept -- to indicate end of options, and are self-documenting.

The self-documenting commands interpret the option --man as a request to display that command's own manual page, --help as a request to display the OPTIONS section from their manual page, and -? as a request to print a brief usage message. All these are processed as error messages, so they are written on standard error (file descriptor 2) and to pipe them into a pager such as more(1) you need to add a 2>&1 redirection before the |. The display of boldface text depends on whether standard error is on a terminal, so is disabled when using a pager. Exporting the ERROR_OPTIONS environment variable with a value containing emphasis will force this on; a value containing noemphasis forces it off.

The test/[ command needs an additional -- argument to recognize self-documentation options, e.g. test --man --. The exec and redirect commands, as they make redirections permanent, should use self-documentation options in a subshell when redirecting, for example: (redirect --man) 2>&1. There are advanced output options as well; see getopts --man for more information.

Commands that are preceded by a symbol below are special built-in commands and are treated specially in the following ways:

  1. Variable assignment lists preceding the command remain in effect when the command completes.
  2. I/O redirections are processed after variable assignments.
  3. Errors cause a script that contains them to abort.
  4. They are not valid function names.

Commands that are preceded by a symbol below are declaration commands. Any following words that are in the format of a variable assignment are expanded with the same rules as a variable assignment. This means that tilde expansion is performed after the = sign, array assignments of the form varname=(assign_list) are supported, and field splitting and pathname expansion are not performed.

🚀 Invocation

If the shell is invoked by exec(2), initialization depends on argument zero ($0) as follows. If the first character of $0 is -, or the -l option is given on the invocation command line, then the shell is assumed to be a login shell. If the basename of the command path in $0 is rsh, rksh, or krsh, then the shell becomes restricted. If the basename is sh or rsh, or the -o posix option is given on the invocation command line, then the shell is initialized in full POSIX compliance mode (see the set builtin command above for more information). After this, if the shell was assumed to be a login shell, commands are read from /etc/profile and then from $HOME/.profile if it exists. Alternatively, the option -l causes the shell to be treated as a login shell. Next, for interactive shells, commands are read from the file named by ENV if the file exists, its name being determined by performing parameter expansion, command substitution, and arithmetic expansion on the value of that environment variable. If the -s option is not present and arg and a file by the name of arg exists, then it reads and executes this script. Otherwise, if the first arg does not contain a /, a path search is performed on the first arg to determine the name of the script to execute. The script arg must have execute permission and any setuid and setgid settings will be ignored. If the script is not found on the path, arg is processed as if it named a built-in command or function. Commands are then read as described below; the following options are interpreted by the shell when it is invoked:

The remaining options and arguments are described under the set command above. An optional - as the first argument is ignored.

🔒 Rksh Only

Rksh is used to set up login names and execution environments whose capabilities are more controlled than those of the standard shell. The actions of rksh are identical to those of ksh, except that the following are disallowed:

The restrictions above are enforced after .profile and the ENV files are interpreted. When a command to be executed is found to be a shell procedure, rksh invokes ksh to execute it. Thus, it is possible to provide to the end-user shell procedures that have access to the full power of the standard shell, while imposing a limited menu of commands; this scheme assumes that the end-user does not have write and execute permissions in the same directory.

The net effect of these rules is that the writer of the .profile has complete control over user actions, by performing guaranteed setup actions and leaving the user in an appropriate directory (probably not the login directory). The system administrator often sets up a directory of commands (e.g., /usr/rbin) that can be safely invoked by rksh.

🚪 EXIT STATUS

⚠️ Errors detected by the shell, such as syntax errors, cause the shell to return a non-zero exit status. 🔄 If the shell is being used non-interactively, then execution of the shell file is abandoned unless the error occurs inside a subshell in which case the subshell is abandoned. Otherwise, the shell returns the exit status of the last command executed (see also the exit command above). 🔍 Run time errors detected by the shell are reported by printing the command or function name and the error condition. If the line number that the error occurred on is greater than one, then the line number is also printed in square brackets ([]) after the command or function name.

📁 FILES

📚 SEE ALSO

🛠️ cat(1), cd(1), chmod(1), cut(1), date(1), egrep(1), echo(1), emacs(1), env(1), fgrep(1), gmacs(1), grep(1), stty(1), test(1), umask(1), vi(1), 🔧 dup(2), exec(2), fork(2), 📖 getpwnam(3), ioctl(2), lseek(2), 🛠️ paste(1), 🔧 pathconf(2), pipe(2), 📖 sysconf(3), 🔧 umask(2), ulimit(2), wait(2), 📖 strftime(3), wctrans(3), rand(3), 📄 profile(5), 🌐 environ(7).

📚 Morris I. Bolsky and David G. Korn, The New KornShell Command and Programming Language, Prentice Hall, 1995.

📜 POSIX - Part 2: Shell and Utilities, IEEE Std 1003.2-1992, ISO/IEC 9945-2, IEEE, 1993.

⚠️ CAVEATS

KSH(1)

ksh(1)
📖 NAME 📋 SYNOPSIS 📖 DESCRIPTION
🔤 Definitions 📜 Commands 📝 Variable Assignments 💬 Comments 🔗 Aliasing 🔄 Tilde Expansion 📦 Command Substitution ➗ Arithmetic Expansion 🔗 Process Substitution 📐 Parameter Expansion ⚙️ Shell Variables ✂️ Field Splitting 🔄 Brace Expansion 📁 Pathname Expansion 💬 Quoting 🔢 Arithmetic Evaluation 💡 Prompting ❓ Conditional Expressions 🔀 Input/Output 🌐 Environment 🧩 Functions 🔧 Discipline Functions 📛 Name Spaces 📦 Type Variables 🔧 Jobs 🚦 Signals ⚡ Execution 🔄 Command Re-entry ✏️ In-line Editing Options ⌨️ Key Bindings 📝 Emacs Editing Mode 📝 Vi Editing Mode
📖 DESCRIPTION
✏️ Text Modification Edit Commands 🧰 Other Edit Commands 🏗️ Built-in Commands 🚀 Invocation 🔒 Rksh Only
🚪 EXIT STATUS 📁 FILES 📚 SEE ALSO ⚠️ CAVEATS

Generated by phpman v4.9.26-1-g511901d · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-08-04 22:09 @216.73.216.89
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format

^_top_^