OKSH(1)

๐Ÿ“ฆ
version 7.9 ยท 2 versions
  • 7.9 ยท alpine 3.24, fedora 43, fedora 44, nixos 26.05, nixpkgs unstable (latest)
  • 7.6 ยท fedora 43
, in alpine 3.24, fedora 43, fedora 44, nixos 26.05, nixpkgs unstable

๐ŸŽ€ NAME ๐ŸŽ€

oksh, rksh โ€” the public domain Korn shell. Yeah bestie, a whole shell, public domain, no cap. ๐Ÿซถ


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

oksh [-+abCefhiklmnpruvXx] [-+o option]
     [-c string | -s | file [argument ...]]

โœจ DESCRIPTION โœจ

Okay so oksh is a command interpreter โ€” like, you type stuff, it makes the computer do the stuff โ€” and it's built for both interactive vibes and shell script life. Its command language is a superset of the sh(1) shell language. Superset!! She ate and left no crumbs. ๐Ÿ’…

The options are as follows:

  • -c string โ€” oksh will execute the command(s) contained in string. Just hand her a string, she runs it, iconic.
  • -i โ€” Interactive shell. A shell is "interactive" if this option is used or if both standard input and standard error are attached to a tty(4). An interactive shell has job control enabled, ignores the SIGINT, SIGQUIT, and SIGTERM signals, and prints prompts before reading input (see the PS1 and PS2 parameters). For non-interactive shells, the trackall option is on by default (see the set command below). ๐Ÿงš
  • -l โ€” Login shell. If the basename the shell is called with (i.e. argv[0]) starts with - or if this option is used, the shell is assumed to be a login shell and the shell reads and executes the contents of /etc/profile and $HOME/.profile if they exist and are readable. ๐Ÿ’–
  • -p โ€” Privileged shell. A shell is "privileged" if this option is used or if the real user ID or group ID does not match the effective user ID or group ID (see getuid(2) and getgid(2)). A privileged shell does not process $HOME/.profile nor the ENV parameter (see below). Instead, the file /etc/suid_profile is processed. Clearing the privileged option causes the shell to set its effective user ID (group ID) to its real user ID (group ID). ๐Ÿซก
  • -r โ€” Restricted shell. A shell is "restricted" if this option is used; if the basename the shell was invoked with was rksh; or if the SHELL parameter is set to rksh. The following restrictions come into effect after the shell processes any profile and ENV files:
    • The cd command is disabled. ๐Ÿšซ
    • The SHELL, ENV, and PATH parameters cannot be changed.
    • Command names can't be specified with absolute or relative paths.
    • The -p option of the built-in command command can't be used.
    • Redirections that create files can't be used (i.e. >, >|, >>, <>).
  • -s โ€” The shell reads commands from standard input; all non-option arguments are positional parameters.

In addition to the above, the options described in the set built-in command can also be used on the command line: both [-+abCefhkmnuvXx] and [-+o option] can be used for single letter or long options, respectively. Bestie you have so many options and honestly? Obsessed. ๐ŸŒˆ

If neither the -c nor the -s option is specified, the first non-option argument specifies the name of a file the shell reads commands from. If there are no non-option arguments, the shell reads commands from the standard input. The name of the shell (i.e. the contents of $0) 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 basename the shell was called with (i.e. argv[0]) is used. ๐Ÿ”

If the ENV parameter is set when an interactive 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 and the resulting file (if any) is read and executed. In order to have an interactive (as opposed to login) shell process a startup file, ENV may be set and exported (see below) in $HOME/.profile โ€” future interactive shell invocations will process any file pointed to by $ENV:

export ENV=$HOME/.kshrc

$HOME/.kshrc is then free to specify instructions for interactive shells. For example, the global configuration file may be sourced:

. /etc/ksh.kshrc

The above strategy may be employed to keep setup procedures for login shells in $HOME/.profile and setup procedures for interactive shells in $HOME/.kshrc. Of course, since login shells are also interactive, any commands placed in $HOME/.kshrc will be executed by login shells too. โœจ

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 whitespace characters (space, tab, and newline) or meta-characters (<, >, |, ;, (, ), and &). Aside from delimiting words, spaces and tabs are ignored, while newlines usually delimit commands. The meta-characters are used in building the following tokens: <, <&, <<, >, >&, >>, etc. are used to specify redirections (see "Input/output redirection" below); | is used to create pipelines; |& is used to create co-processes (see "Co-processes" below); ; is used to separate commands; & is used to create asynchronous pipelines; && and || are used to specify conditional execution; ;; is used in case statements; (( .. )) is used in arithmetic expressions; and lastly, ( .. ) is used to create subshells. ๐Ÿ˜ค

Whitespace 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 "Quoting" below); #, if used at the beginning of a word, introduces a comment โ€” everything after the # up to the nearest newline is ignored; $ is used to introduce parameter, command, and arithmetic substitutions (see "Substitution" below); ` introduces an old-style command substitution (see "Substitution" below); ~ begins a directory expansion (see "Tilde expansion" below); { and } delimit csh(1)-style alternations (see "Brace expansion" below); and finally, *, ?, and [ are used in file name generation (see "File name patterns" below). ๐ŸŒธ

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 "Parameters" below), input/output redirections (see "Input/output redirections" below), and command words; the only restriction is that parameter assignments come before any command words. The command words, if any, define the command that is to be executed and its arguments. The command may be a shell built-in command, a function, or an external command (i.e. a separate executable file that is located using the PATH parameter; see "Command execution" below).

All command constructs have an exit status. For external commands, this is related to the status returned by wait(2) (if the command could not be found, the exit status is 127; if it could not be executed, the exit status is 126). The exit status of other command constructs (built-in commands, functions, compound-commands, pipelines, lists, etc.) 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 0 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, unless the pipefail option is set. A pipeline may 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; if the original status was not 0, the complemented status will be 0. ๐Ÿ’ซ

Lists of commands can be created by separating pipelines by 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 && and || operators are "left-associative". For example, both of these commands will print only "bar":

$ false && echo foo || echo bar
$ true || echo foo && echo bar

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; see "Job control" below). When an asynchronous command is started when job control is disabled (i.e. in most scripts), the command is started with signals SIGINT and SIGQUIT 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 a special kind of asynchronous process (see "Co-processes" below). A command must follow the && and || operators, while it need not follow &, |&, or ;. The exit status of a list is that of the last command executed, with the exception of asynchronous lists, for which the exit status is 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 (i.e. they can't be preceded by parameter assignments or redirections):

case   esac       in       until   ((   }
do     fi         name     while   ))
done   for        select   !       [[
elif   function   then     (       ]]
else   if         time     )       {
โญ Real talk bestie: those words only count as reserved when they're unquoted and first word of a command. Don't come for me when echo done doesn't do the thing. ๐Ÿ˜ญ
Note: 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 may 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; } }

This 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 tries to match word against a specified pattern; 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 within a pattern must be quoted. Both the word and the patterns are subject to parameter, command, and arithmetic substitution, as well as tilde substitution. The initial ( is optional, as is the terminating ;; for the final list. For historical reasons, open and close braces may be used instead of in and esac e.g. 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 ...]]; do list; done โ€” 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, the positional parameters ($1, $2, etc.) are used instead. For historical reasons, open and close braces may be used instead of do and done e.g. for i; { echo $i; }. The exit status of a for statement is the last exit status of list. If there are no items, list is not executed and 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 elifs fail (i.e. exit with non-zero status), the list following the else is executed. The exit status of an if statement is that of non-conditional list that is executed; if no non-conditional list is executed, the exit status is zero. ๐Ÿ’–
  • select name [in word ...]; do list; done โ€” The select statement provides an automatic method of presenting the user with a menu and selecting from it. An enumerated list of the specified word(s) 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 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 (i.e. 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 continues 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 (i.e. $1, $2, etc.). For historical reasons, open and close braces may be used instead of do and done e.g. select i; { echo $i; }. The exit status of a select statement is zero if a break statement is used to exit the loop, non-zero otherwise. ๐ŸŒธ

  • 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 pre-checked 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โ€ below). 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โ€ below). โœจ
  • time [-p] [pipeline] โ€” The time reserved word is described in the โ€œCommand executionโ€ section. ๐Ÿ•ฐ๏ธ
  • (( expression )) โ€” The arithmetic expression expression is evaluated; equivalent to let expression (see โ€œArithmetic expressionsโ€ and the let command, below). ๐Ÿงฎ
  • [[ expression ]] โ€” Similar to the test and [ ... ] commands (described later), with the following exceptions: ๐Ÿ’…
    • Field splitting and file name generation are not performed on arguments.
    • The -a (AND) and -o (OR) operators are replaced with && and ||, respectively.
    • Operators (e.g. -f, =, !) must be unquoted.
    • The second operand of the =, == and != expressions are patterns (e.g. the comparison [[ foobar = f*r ]] succeeds).
    • The < and > binary operators do not need to be quoted with the \ character.
    • The single argument form of test, which tests if the argument has a non-zero length, is not valid; explicit operators must always be used e.g. instead of [ str ] use [[ -n str ]].
    • Parameter, command, and arithmetic substitutions are performed as expressions are evaluated and lazy expression evaluation is used for the && and || operators. This means that in the following statement, $(< foo) is evaluated if and only if the file foo exists and is readable:
$ [[ -r foo && $(< foo) = b*r ]]

โœจ Quoting โœจ

Quoting is used to prevent the shell from treating characters or words specially. There are three methods of quoting. First, \ 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 may span lines). Third, a double quote (") quotes all characters, except $, ` and \, up to the next unquoted double quote. $ and ` inside double quotes have their usual meaning (i.e. parameter, command, or arithmetic substitution) except 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. ๐ŸŽ€

โœจ Aliases โœจ

There are two types of aliases: normal command aliases and tracked aliases. Command aliases are normally used as a short hand for a long or often used command. The shell expands command aliases (i.e. substitutes the alias name for its value) when it reads the first word of a command. An expanded alias is re-processed 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'
login='exec login'
nohup='nohup '
r='fc -s'
stop='kill -STOP'

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 see 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 (i.e. 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, grep(1), ls(1), mail(1), make(1), mv(1), pr(1), rm(1), sed(1), sh(1), vi(1), and who(1). ๐Ÿ‘‘

โœจ 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`; and arithmetic substitutions take the form $((expression)). ๐Ÿ’–

If a substitution shows up outside of double quotes, bestie, the results are generally subject to word or field splitting according to whatever the IFS parameter currently is. The IFS parameter is literally just a list of characters used to break a string into several words; any characters from the set space, tab, and newline that appear in the IFS characters are called โ€œIFS whitespaceโ€. Sequences of one or more IFS whitespace characters, in combination with zero or one non-IFS whitespace characters, delimit a field. And as a special case โœจ leading and trailing IFS whitespace is stripped (i.e. no leading or trailing empty field gets created by it); leading non-IFS whitespace does create an empty field.

Example time, because this one is a vibe: if IFS is set to <space>:, and VAR is set to <space>A<space>:<space><space>B::D, the substitution for $VAR results in four fields: โ€˜Aโ€™, โ€˜Bโ€™, โ€˜โ€™ (an empty field), and โ€˜Dโ€™. ๐Ÿ‘‘ Note that if the IFS parameter is set to the NULL string, no field splitting is done at all; if the parameter is unset, the default value of space, tab, and newline is used.

Also, note that the field splitting applies only to the immediate result of the substitution. Using the previous example, the substitution for $VAR:E results in the fields: โ€˜Aโ€™, โ€˜Bโ€™, โ€˜โ€™, and โ€˜D:Eโ€™ โ€” not โ€˜Aโ€™, โ€˜Bโ€™, โ€˜โ€™, โ€˜Dโ€™, and โ€˜Eโ€™. This behavior is POSIX compliant, but incompatible with some other shell implementations which do field splitting on the word which contained the substitution or use IFS as a general whitespace delimiter.

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

A command substitution gets 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. Note that $(< foo) has the same effect as $(cat foo), but it is carried out more efficiently because no process is started. ๐Ÿฆ‹

Arithmetic substitutions get 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 below, or a letter followed by zero or more letters or digits (โ€˜_โ€™ counts as a letter). The latter form can be treated as arrays by appending an array index of the form [expr] where expr is an arithmetic expression. Parameter substitutions take the form $name, ${name}, or ${name[expr]} where name is a parameter name. If expr is a literal โ€˜@โ€™ then the named array is expanded using the same quoting rules as โ€˜$@โ€™, while if expr is a literal โ€˜*โ€™ then the named array is expanded using the same quoting rules as โ€˜$โ€™. If substitution is performed on a parameter (or an array parameter element) 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 number of ways, so let's go through them like a lil checklist:

  1. The shell implicitly sets some parameters like โ€˜#โ€™, โ€˜PWDโ€™, and โ€˜$โ€™; this is the only way the special single character parameters are set.
  2. Parameters are imported from the shell's environment at startup.
  3. Parameters can be assigned values on the command line: for example, FOO=bar sets the parameter โ€œFOOโ€ to โ€œbarโ€; 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; see below for the implications of this). Note that both the parameter name and the โ€˜=โ€™ must be unquoted for the shell to recognize a parameter assignment.
  4. The fourth way of setting a parameter is with the export, readonly, and typeset commands; see their descriptions in the โ€œCommand executionโ€ section.
  5. for and select loops set parameters, as well as the getopts, read, and set -A commands.
  6. Lastly, parameters can be assigned values using assignment operators inside arithmetic expressions (see โ€œArithmetic expressionsโ€ below) or using the ${name=value} form of the parameter substitution (see below).

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(7)) 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 (normally causing termination of a shell script, function, or script sourced using the โ€˜.โ€™ built-in command). 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 not specified; otherwise 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, and two of them 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 ID of the last background process started. If no background processes have been started, the parameter is not set.
  • # โ€” The number of positional parameters ($1, $2, etc.).
  • $ โ€” The PID of the shell, or the PID of the original shell if it is a subshell. Do NOT use this mechanism for generating temporary file names; see mktemp(1) instead. ๐Ÿšจ
  • - โ€” The concatenation of the current single letter options (see the set command below 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 of the shell, determined as follows: the first argument to oksh if it was invoked with the -c option and arguments were given; otherwise the file argument, if it was supplied; or else the basename the shell was invoked with (i.e. argv[0]). $0 is also set to the name of the current script or the name of the current function, if it was defined with the function keyword (i.e. a Korn shell style function).
  • 1 ... 9 โ€” The first nine positional parameters that were supplied to the shell, function, or script sourced using the โ€˜.โ€™ built-in command. Further positional parameters may be accessed using ${number}.
  • * โ€” All positional parameters (except parameter 0) i.e. $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 losing NULL arguments or splitting arguments with spaces. ๐Ÿ‘‘

The following parameters are set and/or used by the shell:

  • _ (underscore) โ€” When an external command is executed by the shell, this parameter is set in the environment of the new process to the path of the executed command. In interactive use, this parameter is also set in the parent shell to the last word of the previous command. When MAILPATH messages are evaluated, this parameter contains the name of the file that changed (see the MAILPATH parameter, below).
  • CDPATH โ€” Search path for the cd built-in command. It works the same way as PATH for those directories not beginning with โ€˜/โ€™ or โ€˜.โ€™ in cd commands. Note that if CDPATH is set and does not contain โ€˜.โ€™ or an empty path, the current directory is not searched. Also, the cd built-in command will display the resulting directory when a match is found in any search path other than the empty path.
  • 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 the select, set -o, and kill -l commands to format information columns.

EDITOR โ€” bestie if VISUAL isn't set, THIS is the parameter that decides your command-line editing mode for interactive shells. Wanna know how that whole thing works? Peep the VISUAL parameter right below, it explains the mechanics. ๐Ÿ’…

Note: back in the day, EDITOR was for your old-school line editor vibe (think ed(1)), and VISUAL was for the fancy screen editor vibe (think vi(1)). So yeah โ€” if VISUAL is set, it overrides EDITOR. The hierarchy is real. ๐Ÿ‘‘

ENV โ€” if this one is set after any profile files have run, its expanded value gets used as a shell startup file. It's usually where you stash your function and alias definitions, no cap. โœจ

EXECSHELL โ€” set this and it's assumed to hold the shell that gets used to execute commands when execve(2) fails to execute them AND they don't start with a #!shell sequence. Niche but iconic. ๐Ÿฆ‹

FCEDIT โ€” the editor that the fc command uses (details below, keep reading bestie).

FPATH โ€” it's giving PATH's cooler cousin ๐Ÿ’–. Used when an undefined function gets executed, to go locate the file that defines the function. It's ALSO searched when a command can't be found using PATH. See "Functions" below for the full tea.

HISTCONTROL โ€” a colon separated list of history settings. If ignoredups is present, lines identical to the previous history line won't be saved. If ignorespace is present, lines starting with a space won't be saved. Unknown settings? Ignored, we don't know her. ๐Ÿ™ˆ

HISTFILE โ€” the name of the file where command history lives. When you assign to it, history gets loaded from the file you named. Also lowkey iconic: several invocations of the shell running on the same machine will share history if their HISTFILE parameters all point to the same file. Group chat energy fr fr. ๐Ÿ’ฌ

Note: if HISTFILE isn't set, no history file is used at all. This is different from the original Korn shell, which uses $HOME/.sh_history.

HISTSIZE โ€” how many commands normally get stored for history. Default is 500.

HOME โ€” the default directory for the cd command, and the value that gets substituted for an unqualified ~ (see "Tilde expansion" below). Home sweet home ๐Ÿ 

IFS โ€” Internal field separator! Used during substitution and by the read command to split values into distinct arguments. Normally set to space, tab, and newline. See "Substitution" above for the details. ๐ŸŒธ

Note: this parameter is not imported from the environment when the shell is started. She's built different.

KSH_VERSION โ€” the version of the shell and the date the version was created. Read-only, so don't even try it. ๐Ÿ’€

LINENO โ€” the line number of the function or shell script that's currently being executed. Your little GPS for scripts. ๐Ÿ“

LINES โ€” set to the number of lines on the terminal or window.

MAIL โ€” if set, you'll be informed of the arrival of mail in the named file. This parameter is ignored if the MAILPATH parameter is set. (MAILPATH is the main character here, sorry.) ๐Ÿ“ฌ

MAILCHECK โ€” how often, in seconds, the shell checks for mail in the file(s) specified by MAIL or MAILPATH. If set to 0, the shell checks before each prompt. Default is 600 (that's 10 minutes bestie).

MAILPATH โ€” a list of files to be checked for mail. Colon separated, and each file may be followed by a ? and a message to print if new mail has arrived. Command, parameter, and arithmetic substitution all happen on that message, and 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 hasn't successfully changed directories since the shell started, or if the shell just doesn't know where it is. Lost girl behaviour. ๐Ÿ˜ญ

OPTARG โ€” when using getopts, this holds the argument for a parsed option, if it requires one.

OPTIND โ€” the index of the next argument to be processed when using getopts. Assigning 1 to this parameter causes getopts to process arguments from the beginning the next time it's invoked. Rewind button ๐Ÿ”„

PATH โ€” a colon separated list of directories that get searched when looking for commands and files sourced using the . command (see below). An empty string resulting from a leading or trailing colon, or two adjacent colons, is treated as a . (the current directory). ๐Ÿ‘‘

POSIXLY_CORRECT โ€” if set, this parameter causes the posix option to be enabled. See "POSIX mode" below.

PPID โ€” the process ID of the shell's parent. Read-only! ๐Ÿซถ

PS1 โ€” THE primary prompt for interactive shells ๐Ÿ’–. Parameter, command, and arithmetic substitutions are performed, and the prompt string can be customised using backslash-escaped special characters.

Note: since the command-line editors try to figure out how long the prompt is (so they know how far it is to the edge of the screen), escape codes in the prompt tend to mess things up. You can tell the shell not to count certain sequences (such as escape codes) by using the \[...\] substitution (see below) or by prefixing your prompt with a non-printing character (such as control-A) followed by a carriage return, and then delimiting the escape codes with this non-printing character. By the way, don't blame me for this hack โ€” it's in the original oksh. ๐Ÿ’€

The default prompt is the first part of the hostname, followed by $ for non-root users, and # for root.

The following backslash-escaped special characters can be used to customise the prompt:

  • \a โ€” insert an ASCII bell character. ๐Ÿ””
  • \d โ€” the current date, in the format "Day Month Date", for example "Wed Nov 03".
  • \D{format} โ€” the current date, with format converted by strftime(3). The braces must be specified.
  • \e โ€” insert an ASCII escape character.
  • \h โ€” the hostname, minus domain name.
  • \H โ€” the full hostname, including domain name.
  • \j โ€” current number of jobs running (see "Job control" below).
  • \l โ€” the controlling terminal.
  • \n โ€” insert a newline character.
  • \r โ€” insert a carriage return character.
  • \s โ€” the name of the shell.
  • \t โ€” the current time, in 24-hour HH:MM:SS format.
  • \T โ€” the current time, in 12-hour HH:MM:SS format.
  • \@ โ€” the current time, in 12-hour HH:MM:SS AM/PM format.
  • \A โ€” the current time, in 24-hour HH:MM format.
  • \u โ€” the current user's username.
  • \v โ€” the current version of oksh.
  • \V โ€” like \v, but more verbose.
  • \w โ€” the current working directory. $HOME is abbreviated as ~.
  • \W โ€” the basename of the current working directory. $HOME is abbreviated as ~.
  • \! โ€” the current history number. An unescaped ! will produce the current history number too, as per the POSIX specification. A literal ! can be put in the prompt by placing !! in PS1.
  • \# โ€” the current command number. This could be different to the current history number, if HISTFILE contains a history list from a previous session.
  • \$ โ€” the default prompt character, i.e. # if the effective UID is 0, otherwise $. Since the shell interprets $ as a special character within double quotes, it's safer in this case to escape the backslash than to try quoting it.
  • \nnn โ€” the octal character nnn.
  • \\ โ€” insert a single backslash character.
  • \[ โ€” normally the shell keeps track of the number of characters in the prompt. Use of this sequence turns off that count.
  • \] โ€” use of this sequence turns the count back on.
Note: the backslash itself may be interpreted by the shell. So to set PS1, either escape the backslash itself, or use double quotes. The latter is more practical:
PS1="\u "

Here's a more complex example, which doesn't rely on the above backslash-escaped sequences. It embeds the current working directory, in reverse video, in the prompt string:

x=$(print \\001)
PS1="$x$(print \\r)$x$(tput so)$x\$PWD$x$(tput se)$x> "

PS2 โ€” secondary prompt string, by default > , used when more input is needed to complete a command.

PS3 โ€” the prompt used by the select statement when reading a menu selection. Default is #? .

PS4 โ€” used to prefix commands that get printed during execution tracing (see the set -x command below). Parameter, command, and arithmetic substitutions are performed before it's printed. Default is + .

PWD โ€” the current working directory. May be unset or NULL if the shell doesn't know where it is. ๐Ÿซ 

RANDOM โ€” a random number generator โœจ. Every time RANDOM is referenced, it's assigned the next random number in the range 0-32767. By default, arc4random(3) is used to produce values. If the variable RANDOM is assigned a value, that value is used as the seed to srand_deterministic(3) and subsequent references of RANDOM produce a predictable sequence. So like, choose your fighter: chaos or deterministic fate. ๐Ÿ”ฎ

REPLY โ€” the default parameter for the read command if no names are given. Also used in select loops to store the value that's 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. Math girlie. โฑ๏ธ

TERM The user's terminal type. If set, it will be used to determine the escape sequence used to clear the screen.

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 temporary shell files are created in. If this parameter is not set, or does not contain the absolute path of a writable directory, temporary files are created in /tmp.

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(1), emacs, or gmacs (Gosling emacs) editing mode is enabled, respectively. See also the EDITOR parameter, above.

Tilde expansion Tilde expansion, which is done in parallel with parameter substitution, is done on words starting with an unquoted โ€˜~โ€™. 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 (such as those preceding a simple-command or those occurring in the arguments of alias, export, readonly, and typeset), tilde expansion is done after any assignment (i.e. after the equals sign) or after an unquoted colon (โ€˜:โ€™); login names are also delimited by colons.

The home directory of previously expanded login names are cached and re- used. The alias -d command may be used to list, change, and add to this cache (e.g. alias -d fac=/usr/local/facilities; cd ~fac/bin).

Brace expansion (alternation) Brace expressions take the following form:

prefix{str1,...,strN}suffix

The expressions are expanded to N words, each of which is the concatenation of prefix, stri, and suffix (e.g. โ€œa{c,b{X,Y},d}eโ€ expands to four words: โ€œ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 (e.g. {} 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 meaning:

? 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 โ€˜-โ€™ (e.g. โ€œ[a0-9]โ€ matches the letter โ€˜aโ€™ or any digit). In order to represent itself, a โ€˜-โ€™ must either be quoted or 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 (see below), so to represent itself it must be quoted or appear later in the list.

Within a bracket expression, the name of a character class enclosed in โ€˜[:โ€™ and โ€˜:]โ€™ stands for the list of all characters belonging to that class. Supported character classes:

alnum cntrl lower space alpha digit print upper blank graph punct xdigit

These match characters using the macros specified in isalnum(3), isalpha(3), and so on. A character class may not be used as an endpoint of a range.

[!..] 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โ€, โ€œfoobarfooโ€, etc.

+(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โ€, โ€œfoobarโ€, etc.

?(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 (think about it).

Unlike most shells, ksh never matches โ€˜.โ€™ and โ€˜..โ€™.

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 โ€˜/โ€™.

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 and/or standard output 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. Note that this means the command cmd < foo > foo will open foo for reading and then truncate it when it opens it for writing, 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 if file exists it is appended to instead of being truncated. Also, the file is opened in append mode, so writes always go to the end of the file (see open(2)).

< 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 (i.e. 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 (if the shell is interactive) 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 expanded file name generation characters is used. Note that in restricted shells, redirections which can create files cannot be used.

For simple-commands, redirections may appear anywhere in the command; for compound-commands (if statements, etc.), any redirections must appear at the end. Redirections are processed after pipelines are created and in the order they are given, so the following will print an error with a line number prepended to it:

$ cat /foo/bar 2>&1 > /dev/null | cat -n

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

Expressions may contain alpha-numeric parameter identifiers, array references, and integer constants and may be combined with the following C operators (listed and grouped in increasing order of precedence):

Unary operators:

  • - ! ~ ++ --

Binary operators:

             ,
             = *= /= %= += -= <<= >>= &= ^= |=
             ||
             &&
             |
             ^
             &
             == !=
             < <= >= >
             << >>
             + -
             * / %

Ternary operators:

?: (precedence is immediately higher than assignment)

Grouping operators:

( )

So here's the tea, bestie: a parameter that's NULL or unset evaluates to 0 โ€” it doesn't throw a fit, it just quietly becomes zero. ๐Ÿ’…

Integer constants can be written in literally any base you want using the notation base#number, where base is a decimal integer telling you the base, and number is a number written in that base. Also โ€” and this is the cute part โ€” integers can be prefixed with 0X or 0x (that's base 16, hex girlies rise) or 0 (base 8) in all forms of arithmetic expressions, except when they're numeric arguments to the test command. Noted. ๐Ÿซถ


โœจ The operators, evaluated โœจ

  • unary + โ€” the result is the argument itself. It's included for completeness, okay?? It's giving "I'm here for moral support." ๐ŸŽ€
  • unary - โ€” negation. Flips the sign, that's it.
  • ! โ€” logical NOT; the result is 1 if the argument is zero, and 0 if it's not.
  • ~ โ€” arithmetic (bit-wise) NOT.
  • ++ โ€” increment. Must be applied to a parameter (not a literal, not some other expression, bestie, I'm serious). The parameter gets incremented by 1. When you use it as a prefix operator, the result is the incremented value of the parameter; when you use it as a postfix operator, the result is the original value of the parameter. Yes, the order matters. Iykyk.
  • -- โ€” same energy as ++, except the parameter gets decremented by 1.
  • , โ€” separates two arithmetic expressions; the left-hand side gets evaluated first, then the right. The result is the value of the expression on the right-hand side.
  • = โ€” assignment; the variable on the left gets set to the value on the right.
  • *= /= += -= <<= >>= &= ^= |= โ€” the assignment operators. โŸจvarโŸฉโŸจopโŸฉ=โŸจexprโŸฉ is the same as โŸจvarโŸฉ=โŸจvarโŸฉโŸจopโŸฉโŸจexprโŸฉ, with any operator precedence in โŸจexprโŸฉ preserved. Example, because examples slay: var1 *= 5 + 3 is the same as specifying var1 = var1 * (5 + 3).
  • || โ€” logical OR; the result is 1 if either argument is non-zero, 0 if not. The right argument only gets evaluated if the left argument is zero โ€” short-circuit queen. ๐Ÿ‘‘
  • && โ€” logical AND; the result is 1 if both arguments are non-zero, 0 if not. The right argument only gets evaluated if the left argument is non-zero.
  • | โ€” arithmetic (bit-wise) OR.
  • ^ โ€” arithmetic (bit-wise) XOR (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 < above, bestie. Same vibe, different comparison. ๐Ÿฆ‹
  • << >> โ€” 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. The classics.
  • % โ€” remainder; the result is the remainder of the division of the left argument by the right. Heads up: the sign of the result is unspecified if either argument is negative. So don't come crying to me about it. ๐Ÿ’€
  • โŸจarg1โŸฉ?โŸจarg2โŸฉ:โŸจarg3โŸฉ โ€” if โŸจarg1โŸฉ is non-zero, the result is โŸจarg2โŸฉ; otherwise the result is โŸจarg3โŸฉ. The ternary ate and left no crumbs. โœจ

๐ŸŒธ Co-processes ๐ŸŒธ

A co-process is a pipeline created with the |& operator, and it's 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. Obsessed with the symmetry tbh. ๐Ÿ’–

Once a co-process has been started, another can't be started until the co-process exits, or until the co-process's input has been redirected using an exec n>&p redirection. If a co-process's input is redirected 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. It's giving communal living. ๐Ÿซถ

Some notes concerning co-processes, because bestie you need these:

  • The only way to close the co-process's input (so the co-process reads an end-of-file) is to redirect the input to a numbered file descriptor and then close that file descriptor โ€” e.g. exec 3>&p; exec 3>&-.
  • In order for co-processes to share a common output, the shell must keep the write portion of the output pipe open. This means that end-of-file will not be detected until all co-processes sharing the co-process's output have exited (when they all exit, the shell closes its copy of the pipe). You can avoid this by redirecting the output to a numbered file descriptor (since that also causes the shell to close its copy). Note that this behaviour is slightly different from the original Korn shell, which closes its copy of the write portion of the co-process output when the most recently started co-process exits (instead of when all sharing co-processes exit). The original Korn shell could never. ๐Ÿ˜ญ
  • print -p will ignore SIGPIPE signals during writes if the signal isn't being trapped or ignored; the same is true if the co-process input has been duplicated to another file descriptor and print -un is used.

๐ŸŽ€ Functions ๐ŸŽ€

Functions are defined using either the Korn shell function function-name syntax or the Bourne/POSIX function-name() syntax (see below for the difference between the two forms โ€” yes, there is a difference, stay tuned).

Functions are like .-scripts (i.e. scripts sourced using the . built-in command) in that they're executed in the current environment. However, unlike .-scripts, shell arguments (i.e. positional parameters $1, $2, etc.) are never visible inside them. When the shell is determining the location of a command, functions are searched after special built-in commands, before regular and non-regular built-ins, and before the PATH is searched. The order is the moment, fr fr.

An existing function may 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. The autoload command (which is an alias for typeset -fu) may 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 continues (i.e. the shell searches the regular built-in command table and PATH). Note that if a command isn't found using PATH, an attempt is made to autoload a function using FPATH โ€” and that right there is an undocumented feature of the original Korn shell. We love a secret. ๐Ÿ™ˆ

Functions can have two attributes, "trace" and "export", which 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 function's 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 that's not the effect you want, bestie, the typeset command can be used inside a function to create a local parameter. Note that special parameters (e.g. $$, $!) can't be scoped in this way. Sorry. ๐Ÿ’€

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

  • The $0 parameter is set to the name of the function (Bourne-style functions leave $0 untouched).
  • Parameter assignments preceding function calls are not kept in the shell environment (executing Bourne-style functions will keep assignments).
  • OPTIND is saved/reset and restored on entry and exit from the function so getopts can be used properly both inside and outside the function (Bourne-style functions leave OPTIND untouched, so using getopts inside a function interferes with using getopts outside the function). A mess, honestly. ๐Ÿ˜ญ

๐Ÿ‘‘ POSIX mode ๐Ÿ‘‘

The shell is intended to be POSIX compliant; however, in some cases, POSIX behaviour is contrary either to the original Korn shell behaviour 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's on, the POSIX behaviour 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 shell can also be compiled so that it's in POSIX mode by default โ€” however, this is usually not desirable. ๐Ÿ’…

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

  • kill -l output. In POSIX mode, only signal names are listed (in a single line); in non-POSIX mode, signal numbers, names, and descriptions are printed (in columns). Columns are lowkey iconic, sorry to the single line girlies. โœจ
  • echo options. In POSIX mode, -e and -E are not treated as options, but printed like other arguments; in non-POSIX mode, these options control the interpretation of backslash sequences.
  • 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.
  • eval exit status. If eval gets to see an empty command (i.e. eval `false` ), its exit status in POSIX mode will be 0. In non-POSIX mode, it will be the exit status of the last command substitution that was done in the processing of the arguments to eval (or 0 if there were no command substitutions).
  • getopts. In POSIX mode, options must start with a -; in non-POSIX mode, options can start with either - or +.
  • Brace expansion (aka alternation, the glow-up of {a,b,c}). In POSIX mode it's off; in non-POSIX mode it's on. Heads up bestie: set -o posix (or setting the POSIXLY_CORRECT parameter) automatically flips the braceexpand option off โ€” but you can totally explicitly turn it back 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 $?prints0in POSIX mode and1in non-POSIX mode. This construct is used in most shell scripts that use the oldgetopt(1)` command. ๐Ÿ˜Œ
  • Argument expansion of the 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, while assignment tilde expansion is turned on. wild tbh
  • Signal specification. In POSIX mode, signals can be specified as digits only if signal numbers match POSIX values (i.e. HUP=1, INT=2, QUIT=3, ABRT=6, KILL=9, ALRM=14, and TERM=15). In non-POSIX mode, signals can always be 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 and j in non-POSIX mode:
alias a='for ' i='j'
a i in 1 2; do echo i=$i j=$j; done

Strict Bourne shell mode ๐Ÿง“โœจ

When the sh option is enabled (see the set command), oksh will behave like sh(1) in the following ways:

  • The parameter $_ is not set to:
    • the expanded alias' full program path after entering commands that are tracked aliases
    • the last argument on the command line after entering external commands
    • the file that changed when MAILPATH is set to monitor a mailbox
  • File descriptors are left untouched when executing exec with no arguments. ๐Ÿšช
  • Backslash-escaped special characters are not substituted in PS1.
  • Sequences of ((...)) are not interpreted as arithmetic expressions. ๐Ÿ˜ญ

Command execution ๐Ÿ‘‘

After evaluation of command-line arguments, redirections, and parameter assignments, the type of command is determined: a special built-in, a function, a regular built-in, 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 ๐Ÿ’€
  • parameter assignments that are specified before the command are kept after the command completes

Just to confuse things: if the posix option is turned off (see the set command below), some special commands are very special in that no field splitting, file globbing, brace expansion, nor tilde expansion is performed 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:

POSIX special commands ๐ŸŒŸ

., :, break, continue, eval, exec, exit, export, readonly, return, set, shift, times, trap, unset

Additional oksh special commands โœจ

builtin, typeset

Very special commands (when POSIX mode is off) ๐Ÿ’…

alias, readonly, set, typeset

POSIX regular commands ๐ŸŒธ

alias, bg, cd, command, false, fc, fg, getopts, jobs, kill, pwd, read, true, umask, unalias, wait

Additional oksh regular commands ๐Ÿฆ‹

[, echo, let, print, suspend, test, ulimit, whence

Once the type of 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 [arg ...]

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 may be used to access them while file is being executed. If no arguments are given, the positional parameters are those of the environment the command is used in. ๐Ÿซถ

: [...]

The null command. Exit status is set to zero. It literally does nothing and it slays at it. ๐Ÿ’…

alias [-d | -t [-r] | +-x] [-p] [+] [name[=value] ...]

Without arguments, alias lists all aliases. For any name without a value, the existing alias is listed. Any name with a value defines an alias (see โ€œAliasesโ€ above). ๐Ÿ‘ฏ

When listing aliases, one of two formats is used. Normally, aliases are listed as name=value, where value is quoted. If options were preceded with โ€˜+โ€™, or a lone โ€˜+โ€™ is given on the command line, only name is printed.

The -d option causes directory aliases, which are used in tilde expansion, to be listed or set (see โ€œTilde expansionโ€ above).

If the -p option is used, each alias is prefixed with the string alias .

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 -x option sets (+x clears) the export attribute of an alias or, if no names are given, lists the aliases with the export attribute (exporting an alias has no effect).

bg [job ...]

Resume the specified stopped job(s) in the background. If no jobs are specified, %+ is assumed. See โ€œJob controlโ€ below for more information. ๐Ÿƒโ€โ™€๏ธ

bind [-l]

The current bindings are listed. If the -l flag is given, bind instead lists the names of the functions to which keys may be bound. See โ€œEmacs editing modeโ€ for more information. โŒจ๏ธ

bind [-m] string=[substitute] ...
bind string=[editing-command] ...

In โ€œEmacs editing modeโ€, the specified editing command is bound to the given string. Future input of the string will cause the editing command to be immediately invoked. Bindings have no effect in โ€œVi editing modeโ€. ๐Ÿ™ˆ

If the -m flag is given, the specified input string will afterwards be immediately replaced by the given substitute string, which may contain editing commands. Control characters may be written using caret notation. For example, ^X represents Control-X.

If a certain character occurs as the first character of any bound multi-character string sequence, that character becomes a command prefix character. Any character sequence that starts with a command prefix character but that is not bound to a command or substitute is implicitly considered as bound to the error command. By default, two command prefix characters exist: Escape (^[) and Control-X (^X).

The following default bindings show how the arrow keys on an ANSI terminal or xterm are bound (of course some escape sequences won't work out quite this nicely):

bind '^[[A'=up-history
bind '^[[B'=down-history
bind '^[[C'=forward-char
bind '^[[D'=backward-char
break [level]

Exit the levelth inner-most for, select, until, or while loop. level defaults to 1. ๐Ÿšช

builtin command [arg ...]

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 or โ€˜.โ€™ means the current directory. If dir is found in any component of the CDPATH search path other than the NULL path, the name of the new working directory will be written to standard output. 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 isn't set (see the set command below), references to โ€˜..โ€™ in dir are relative to the path used to get to the directory. If the -P option (physical path) is used or if the physical option is set, โ€˜..โ€™ is relative to the filesystem directory tree. The PWD and OLDPWD parameters are updated to reflect the current and old working 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 [arg ...]

If neither the -v nor -V option is given, cmd is executed exactly as if command had not been specified, with two exceptions:

  1. cmd cannot be an alias or a shell function ๐Ÿšซ
  2. special built-in commands lose their specialness (i.e. 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-ish systems, it is the value returned by getconf PATH). Nevertheless, reserved words, aliases, shell functions, and builtin commands are still found before external commands. ๐Ÿ›ฃ๏ธ

If the -v option is given, instead of executing cmd, information about what would be executed is given (and the same is done for arg ...). For special and regular built-in commands and functions, their names are simply printed; for aliases, a command that defines them is printed; and for commands found by searching the PATH parameter, the full path of the command is printed. If no command is found (i.e. 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 [level]

Jumps to the beginning of the levelth inner-most for, select, until, or while loop. level defaults to 1. โญ๏ธ

๐ŸŒธ echo ๐ŸŒธ

echo [-Een] [arg ...]

okay so echo prints its arguments (separated by spaces, duh) followed by a newline, straight to standard output. The newline gets suppressed if any of the arguments contain the backslash sequence \c. Wanna know about the other backslash sequences it recognizes? Peep the print command below, bestie ๐Ÿ‘‡

The options are there purely for compatibility with BSD shell scripts, so:

  • -n โ€” suppresses that trailing newline
  • -e โ€” enables backslash interpretation (which is literally a no-op, since that's normally done anyway ๐Ÿ’€)
  • -E โ€” suppresses backslash interpretation
If the posix option is set, only the first argument is treated as an option, and only if it's exactly -n. periodt.

โœจ eval โœจ

eval command ...

The arguments get concatenated (with spaces between them, obviously) to form one single string, and then the shell parses and executes that string in the current environment. it's giving "strings all the way down" ๐Ÿ’…


๐Ÿ‘‘ exec ๐Ÿ‘‘

exec [command [arg ...]]

The command is executed without forking โ€” it replaces the shell process. main character energy, no understudy, we love to see it.

If no command is given except for I/O redirection, that I/O redirection is permanent and the shell is not replaced. But heads up: any file descriptors greater than 2 which are opened or dup(2)'d this way are not made available to other executed commands (i.e. commands that are not built-in to the shell). And ngl, the Bourne shell differs here โ€” it does pass these file descriptors on. ๐Ÿ’€


exit

exit [status]

The shell dips out with the specified exit status. If status isn't specified, the exit status is the current value of the $? parameter. slay, we're leaving ๐Ÿšชโœจ


๐Ÿ’– export ๐Ÿ’–

export [-p] [parameter[=value]]

Sets the export attribute of the named parameters. Exported parameters are passed in the environment to executed commands. And if values are specified, the named parameters are also assigned. two birds, one stone ๐Ÿฆ

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 instead.


false

false

A command that exits with a non-zero status. that's it. that's the whole vibe. it's giving "no" ๐Ÿ™…โ€โ™€๏ธ


๐ŸŒˆ fc ๐ŸŒˆ

fc [-e editor | -l [-n]] [-r] [first [last]]

Fix command. first and last select commands from the history. You can select them by history number, or by a string that specifies the most recent command starting with that string.

  • -l โ€” lists the command on standard output
  • -n โ€” inhibits the default command numbers
  • -r โ€” reverses the order of the list

Without -l, the selected commands get edited by the editor specified with the -e option โ€” or, if no -e is specified, the editor specified by the FCEDIT parameter (and if that parameter isn't set, /bin/ed is used) โ€” and then executed by the shell. iconic behavior, honestly.

fc -s [-g] [old=new] [prefix]

Re-executes the most recent command beginning with prefix, or the previous command if no prefix is specified, performing the optional substitution of old with new. If -g is specified, all occurrences of old are replaced with new. The editor is not invoked when the -s flag is used. The obsolescent equivalent -e - is also accepted. This command is usually accessed with the predefined alias r='fc -s'.


fg

fg [job ...]

Resumes the specified job(s) in the foreground. If no jobs are specified, %+ is assumed. See "Job control" below for more info ๐Ÿ’…


๐ŸŽ€ getopts ๐ŸŽ€

getopts optstring name [arg ...]

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 colon, that option is expected to have an argument. Options that don't take arguments may be grouped in a single argument. If an option takes an argument and the option character is not the last character of the argument it's found in, the remainder of the argument is taken to be the option's argument; otherwise, the next argument is the option's argument. iykyk ๐Ÿง 

Each time getopts is invoked, it places the next option in the shell parameter name and the index of the argument to be processed by the next call to getopts 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. Furthermore, if optstring does not begin with a colon, a question mark is placed in name, OPTARG is unset, and an error message is printed to standard error.

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).

โš ๏ธ Warning: Changing the value of the shell parameter OPTIND to a value other than 1, or parsing different sets of arguments without resetting OPTIND, may lead to unexpected results. ๐Ÿ™ˆ do not do this to yourself bestie

The following code fragment shows how one might process the arguments for a command that can take the option -a and the option -o, which requires an argument.

while getopts ao: name
do
    case $name in
    a)    flag=1 ;;
    o)    oarg=$OPTARG ;;
    ?)    echo "Usage: ..."; exit 2 ;;
    esac
done
shift $(($OPTIND - 1))
echo "Non-option arguments: " "$@"

๐Ÿ” hash ๐Ÿ”

hash [-r] [name ...]

Without arguments, any hashed executable command pathnames are listed. The -r option causes all hashed commands to be removed from the hash table. Each name is searched as if it were a command name and added to the hash table if it's an executable command. caching queen โœจ


jobs

jobs [-lnp] [job ...]

Displays information about the specified job(s); if no jobs are specified, all jobs are displayed.

  • -n โ€” information is displayed only for jobs that have changed state since the last notification
  • -l โ€” the process ID of each process in a job is also listed
  • -p โ€” only the process group of each job is printed

See "Job control" below for the format of job and the displayed job.


๐Ÿ’€ kill ๐Ÿ’€

kill [-s signame | -signum | -signame] { job | pid | pgrp } ...

Sends the specified signal to the specified jobs, process IDs, or process groups. If no signal is specified, the TERM signal is sent. If a job is specified, the signal is sent to the job's process group. See "Job control" below for the format of job.

kill -l [exit-status ...]

Prints the signal name corresponding to exit-status. If no arguments are specified, a list of all the signals, their numbers, and a short description of them is printed.


๐Ÿงฎ let ๐Ÿงฎ

let [expression ...]

Each expression is evaluated (see "Arithmetic expressions" above). 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 may need to be quoted, (( expr )) is syntactic sugar for let "expr". math girlie hours, no cap โœจ


print

print [-nprsu[n] | -R [-en]] [argument ...]

print prints its arguments on 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### (# is an octal digit, of which there may be 0 to 3). \c is equivalent to using the -n option. \ expansion may 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 "Co-processes" above).

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


๐Ÿ“ pwd ๐Ÿ“

pwd [-LP]

Prints the present working directory. If the -L option is used, or if the physical option isn't set (see the set command below), the logical path is printed (i.e. the path used to cd to the current directory). If the -P option (physical path) is used, or if the physical option is set, the path determined from the filesystem (by following .. directories to the root directory) is printed. where are we?? ๐Ÿ—บ๏ธโœจ


๐Ÿซถ read ๐Ÿซถ

read [-prsu[n]] [parameter ...]

Reads a line of input from the standard input, separates the line into fields using the IFS parameter (see "Substitution" above), and assigns each field to the specified parameters. If there are more parameters than fields, the extra parameters are set to NULL โ€” or 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 the newline are stripped and more input is read. If no input is read, read exits with a non-zero status.

The first parameter can have a question mark plus a string tacked onto the end of it, and if it does, that string becomes a prompt (printed to standard error before any input gets read) whenever the input is a tty(4). Like, for real: read nfoo?'number of foos: '.

  • -un โ€” input gets read from file descriptor n (n defaults to 0 if you justโ€ฆ don't say it).
  • -p โ€” input gets read from the current co-process instead (go peek at "Co-processes" above for the whole tea on that).
  • -s โ€” input gets saved to the history file. โœจ

๐Ÿซถ readonly

readonly [-p] [parameter[=value] ...]

Sets the read-only attribute on the parameters you name. If you hand it values too, the parameters get set to those values before the attribute goes on. And once a parameter is read-only? Yeah, that's it โ€” you can't unset it and you can't change its value. It's giving permanent. ๐Ÿ’…

If you name no parameters at all, it prints the names of every parameter that has the read-only attribute, one per line โ€” unless you use the -p option, in which case it prints readonly commands that define all the read-only parameters, values included.


๐ŸŒธ return

return [status]

Bails out of a function or a . script, with exit status status. No status given? Then it uses the exit status of the last command that ran. If you use it somewhere that isn't a function or a . script, it does the exact same thing as exit.

Heads up bestie: ksh treats both profile and ENV files as . scripts, whereas the original Korn shell only treats profiles as . scripts. ๐Ÿ‘‘

๐ŸŽ€ set

set [+-abCefhkmnpsuvXx] [+-o option] [+-A name] [--] [arg ...]

set is the multitasker of the shell: it sets (-) or clears (+) shell options, sets the positional parameters, or sets an array parameter. You can flip options with the +-o option syntax, where option is the long name of the option, or with the +-letter syntax, where letter is the option's single letter name (and no, not every option has a single letter name, we can't all be blessed ๐Ÿ’…).

Here's the full roster of option letters (where they exist) and long names, plus what each one actually does:

  • -A name โ€” Sets the elements of the array parameter name to arg .... If -A is used, the array is reset (i.e. emptied) first; if +A is used, the first N elements are set (where N is the number of arguments); 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 โ€” Stops > redirection from overwriting existing files. Instead, >| 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 (i.e. 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. For && or ||, only the status of the last command is tested.
  • -f | noglob โ€” Do not expand file name patterns.
  • -h | trackall โ€” Create tracked aliases for all executed commands (see "Aliases" above). Enabled by default for non-interactive shells.
  • -k | keyword โ€” Parameter assignments are recognized anywhere in a command.
  • -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 โ€” The shell is a privileged shell. It is set automatically if, when the shell starts, the real UID or GID does not match the effective UID (EUID) or GID (EGID), respectively. See above 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 with 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 | markdirs โ€” Mark directories with a trailing / during file name generation.
  • -x | xtrace โ€” Print commands and parameter assignments when they are executed, preceded by the value of PS4.
  • bgnice โ€” Background jobs are run with lower priority.
  • braceexpand โ€” Enable brace expansion (a.k.a. alternation).
  • csh-history โ€” Enables a subset of csh(1)-style history editing using the ! character.
  • emacs โ€” Enable BRL emacs-like command-line editing (interactive shells only); see "Emacs editing mode".
  • gmacs โ€” Enable gmacs-like command-line editing (interactive shells only). Currently identical to emacs editing except that transpose (^T) acts slightly differently.
  • ignoreeof โ€” The shell will not (easily) exit when end-of-file is read; exit must be used. To avoid infinite loops, the shell will exit if EOF is read 13 times in a row.
  • interactive โ€” The shell is an interactive shell. This option can only be used when the shell is invoked. See above for a description of what this means.
  • login โ€” The shell is a login shell. This option can only be used when the shell is invoked. See above for a description of what this means.
  • nohup โ€” Do not kill running jobs with a SIGHUP signal when a login shell exits. Currently set by default; this is different from the original Korn shell (which doesn't have this option, but does send the SIGHUP 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" (i.e. the filesystem's) .. directories instead of "logical" directories (i.e. the shell handles .., which allows the user to be oblivious of symbolic links to directories). Clear by default. Note that setting this option does not affect the current value of the PWD parameter; only the cd command changes PWD. See the cd and pwd commands above for more details.
  • pipefail โ€” The exit status of a pipeline is the exit status of the rightmost command in the pipeline that doesn't return 0, or 0 if all commands returned a 0 exit status.
  • posix โ€” Enable POSIX mode. See "POSIX mode" above.
  • restricted โ€” The shell is a restricted shell. This option can only be used when the shell is invoked. See above for a description of what this means.
  • sh โ€” Enable strict Bourne shell mode (see "Strict Bourne shell mode" above).
  • vi โ€” Enable vi(1)-like command-line editing (interactive shells only).
  • vi-esccomplete โ€” In vi command-line editing, do command and 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 may cause problems.
  • vi-tabcomplete โ€” In vi command-line editing, do command and file name completion when tab (^I) is entered in insert mode. This is the default.
  • viraw โ€” No effect. In the original Korn shell, unless viraw was set, the vi command-line mode would let the tty(4) driver do the work until ESC (^[) was entered. ksh is always in viraw mode.

All of these options can also be used when you invoke the shell, btw. The current set of options (the ones with single letter names, anyway) lives in the parameter $-. Run set -o with no option name and it'll list every option and whether it's on or off; run set +o and it prints the current shell options in a form you can feed right back into the shell to land on the exact same option settings. ๐Ÿ”ฅ

Any remaining arguments are positional parameters, assigned in order to the positional parameters (i.e. $1, $2, etc.). If the options end with -- and there are no remaining arguments, all positional parameters get cleared. If you give no options or arguments at all, the values of all names are printed. And for unknown historical reasons, a lone - option is treated specially โ€” it clears both the -x and -v options. ๐Ÿ’€

shift [number]

Okay bestie, shift is the โœจslidingโœจ command. It renames your positional parameters โ€” the ones that were number+1, number+2, etc. all get renamed to 1, 2, etc. And number defaults to 1. ๐Ÿ’…


suspend

suspend stops the shell, like, as if it had just received the suspend character from the terminal. ๐Ÿ›‘ But heads up: you can't suspend a login shell unless the parent process is a member of the same terminal session but is a member of a different process group. As a general rule, if the shell was started by another shell or via su(1), it can be suspended. โœจ


test expression, [ expression ]

test evaluates the expression and returns zero status if it's true, 1 if it's false, or greater than 1 if there was an error. ๐Ÿ˜ญ It's normally used as the condition command of if and while statements. And important: symbolic links are followed for all file expressions except -h and -L. ๐Ÿ‘€

The following basic expressions are available:

  • -a file โ€” file exists. โœจ
  • -b file โ€” file is a block special device. ๐Ÿงฑ
  • -c file โ€” file is a character special device. ๐Ÿ”ค
  • -d file โ€” file is a directory. ๐Ÿ“
  • -e file โ€” file exists.
  • -f file โ€” file is a regular file. ๐Ÿ“„
  • -G file โ€” file's group is the shell's effective group ID.
  • -g file โ€” file's mode has the setgid bit set. ๐Ÿ”
  • -h file โ€” file is a symbolic link. ๐Ÿ”—
  • -k file โ€” file's mode has the sticky(8) bit set.
  • -L file โ€” file is a symbolic link. ๐Ÿ”—
  • -O file โ€” file's owner is the shell's effective user ID.
  • -o option โ€” Shell option is set (see the set command above for a list of options). As a non-standard extension, if the option starts with a !, the test is negated; the test always fails if option doesn't exist (so [ -o foo -o -o !foo ] returns true if and only if option foo exists). ๐Ÿ’…
  • -p file โ€” file is a named pipe.
  • -r file โ€” file exists and is readable.
  • -S file โ€” file is a unix(4)-domain socket. ๐Ÿ”Œ
  • -s file โ€” file is not empty.
  • -t fd โ€” File descriptor fd is a tty(4) device.
  • -u file โ€” file's mode has the setuid bit set.
  • -w file โ€” file exists and is writable. โœ๏ธ
  • -x file โ€” file exists and is executable. โšก
  • file1 -nt file2 โ€” file1 is newer than file2 or file1 exists and file2 does not. โฐ
  • file1 -ot file2 โ€” file1 is older than file2 or file2 exists and file1 does not. โณ
  • file1 -ef file2 โ€” file1 is the same file as file2. ๐Ÿ‘ฏ
  • string โ€” string has non-zero length.
  • -n string โ€” string is not empty.
  • -z string โ€” string is empty.
  • string = string โ€” Strings are equal.
  • string == string โ€” Strings are equal.
  • string != string โ€” Strings are not equal.
  • string > string โ€” Strings compare greater than based on the ASCII value of their characters.
  • string < string โ€” Strings compare less than based on the ASCII value of their characters.
  • 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, may be combined with the following operators (listed in increasing order of precedence):

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). For example, [ -w /dev/fd/2 ] tests if 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 such that only one argument remains then a string length test is performed (again, even if the argument is a unary operator); if leading ! arguments can be stripped such that three arguments remain and the second argument is a binary operator, then the binary operation is performed (even if the first argument is a unary operator, including an unstripped !). ๐Ÿซ 

Note: A common mistake is to use if [ $foo = bar ] which fails if parameter foo is NULL or unset, if it has embedded spaces (i.e. IFS characters), or if it is a unary operator like ! or -n. Use tests like if [ "X$foo" = Xbar ] instead. ๐Ÿšจ

time [-p] [pipeline]

If a pipeline is given, the times used to execute the pipeline are reported. If no pipeline is given, then the user and system time used by the shell itself, and all the commands it has run since it was started, are reported. โฑ๏ธ

The times reported are:

  • the real time (elapsed time from start to finish),
  • the user CPU time (time spent running in user mode), and
  • the system CPU time (time spent running in kernel mode).

Times are reported to standard error; the format of the output is:

0m0.00s real     0m0.00s user     0m0.00s system

If the -p option is given, the output is slightly longer:

real     0.00
user     0.00
sys      0.00

It is an error to specify the -p option unless pipeline is a simple command. ๐Ÿ˜ฑ

Simple redirections of standard error do not affect the output of the time command:

$ time sleep 1 2> afile
$ { time sleep 1; } 2> afile

Times for the first command do not go to afile, but those of the second command do. ๐Ÿ‘€


times

Print the accumulated user and system times used both by the shell and by processes that the shell started which have exited. ๐Ÿ“Š The format of the output is:

0m0.00s 0m0.00s
0m0.00s 0m0.00s

trap [handler signal ...]

Sets a trap handler that is to be executed when any of the specified *signal*s are received. ๐Ÿ’…

handler is either:

  • a NULL string, indicating the signals are to be ignored,
  • a minus sign (-), indicating that the default action is to be taken for the signals (see signal(3)), or
  • a string containing shell commands to be evaluated and executed at the first opportunity (i.e. when the current command completes, or before printing the next PS1 prompt) after receipt of one of the signals.

signal is the name of a signal (e.g. PIPE or ALRM) or the number of the signal (see the kill -l command above). ๐Ÿ“ก

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 the set command above). 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. Note that the output of trap cannot be usefully piped to another process (an artifact of the fact that traps are cleared when subprocesses are created). ๐Ÿ™ˆ

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. โœ…


type

Short form of command -V (see above). ๐Ÿ”


typeset

typeset [[+-lprtUux] [-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 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 is used inside a function, any newly created parameters are local to the function. ๐Ÿ‘‘

When -f is used, typeset operates on the attributes of functions. As with parameters, if no name arguments are given, functions are listed with their values (i.e. definitions) unless options are introduced with +, in which case only the function names are reported. ๐Ÿ› ๏ธ

  • -f โ€” Function mode. Display or set functions and their attributes, instead of parameters.
  • -i[n] โ€” 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 may be assigned values containing arithmetic expressions.
  • -L[n] โ€” 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 whitespace (and zeros, if used with the -Z option) is stripped. If necessary, values are either truncated or space padded to fit the field width.
  • -l โ€” lower case attribute, bestie. Every upper case character in a value gets yeeted down to lower case. ๐Ÿ’… (Fun lore drop: in the original Korn shell this parameter meant โ€œlong integerโ€ when you paired it with the -i option.)
  • -p โ€” prints complete typeset commands that can be used to re-create the attributes (but not the values) of parameters. This is the default action (the option exists for ksh93 compatibility). ๐Ÿซถ
  • -R[n] โ€” right justify attribute. n says what the field width is. If you don't give n, it uses the current width of a parameter (or the width of its first assigned value). Trailing whitespace gets stripped. If it has to, it'll strip leading characters off values or space-pad them so they fit the field width. โœจ
  • -r โ€” read-only attribute. Parameters with this attribute may not be assigned to or unset. And once you set it? It cannot be turned off. Ever. No takebacks, no cap. ๐Ÿšซ
  • -t โ€” tag attribute. Has no meaning to the shell; it's 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 โ€” unsigned integer attribute. Integers are printed as unsigned values (only useful when combined with the -i option). Heads up: this option is not in the original Korn shell. ๐ŸŒˆ
  • -u โ€” upper case attribute. All lower case characters in values are converted to upper case. (In the original Korn shell, this parameter meant โ€œunsigned integerโ€ when used with the -i option, which meant upper case letters would never be used for bases greater than 10. See the -U option.)

For functions, -u is the undefined attribute. See โ€œFunctionsโ€ above 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. ๐Ÿ’€
  • -Z[n] โ€” zero fill attribute. If it's not combined with -L, this is the same as -R, except zero padding is used instead of space padding. ๐ŸŽ€

๐ŸŒธ ulimit ๐ŸŒธ

ulimit [-acdfHlmnpSst [value]] ...

Display or set process limits. If no options are used, the file size limit (-f) is assumed. value, if specified, may be either an arithmetic expression starting with a number or the word โ€œunlimitedโ€. The limits affect the shell and any processes created by the shell after a limit is imposed; limits may not be increased once they are set. ๐Ÿ˜ญ

  • -a โ€” display all limits; unless -H is used, soft limits are displayed.
  • -c n โ€” impose a size limit of n blocks on the size of core dumps.
  • -d n โ€” impose a size limit of n kilobytes on the size of the data area.
  • -f n โ€” impose a size limit of n blocks on files written by the shell and its child processes (files of any size may be read).
  • -H โ€” set the hard limit only (the default is to set both hard and soft limits).
  • -l n โ€” impose a limit of n kilobytes on the amount of locked (wired) physical memory.
  • -m n โ€” impose a limit of n kilobytes on the amount of physical memory used. This limit is not enforced. ๐Ÿ™ˆ
  • -n n โ€” impose a limit of n file descriptors that can be open at once.
  • -p n โ€” impose a limit of n processes that can be run by the user at any one time.
  • -S โ€” set the soft limit only (the default is to set both hard and soft limits).
  • -s n โ€” impose a size limit of n kilobytes on the size of the stack area.
  • -t n โ€” impose a time limit of n CPU seconds spent in user mode to be used by each process.

As far as ulimit is concerned, a block is 512 bytes. ๐Ÿ“


๐Ÿ’– umask ๐Ÿ’–

umask [-S] [mask]

Display or set the file permission creation mask, or umask (see umask(2)). If the -S option is used, the mask displayed or set is symbolic; otherwise, it's an octal number. ๐Ÿ”ข

Symbolic masks are like those used by chmod(1). When used, they describe what permissions may 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 โ€œ007โ€. ๐Ÿฆ‹


โœจ unalias โœจ

unalias [-adt] [name ...]

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 ๐ŸŽ€

unset [-fv] parameter ...

Unset the named parameters (-v, the default) or functions (-f). The exit status is non-zero if any of the parameters have the read-only attribute set, zero otherwise. ๐Ÿซถ


๐Ÿ‘‘ wait ๐Ÿ‘‘

wait [job ...]

Wait for the specified job(s) 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 above); if the last specified job can't be found (because it never existed, or had already finished), the exit status of wait is 127. See โ€œJob controlโ€ below for the format of job. wait will return if a signal for which a trap has been set is received, or if a SIGHUP, SIGINT, or SIGQUIT signal is received. โณ

If no jobs are specified, wait waits for all currently running jobs (if 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 ๐ŸŒˆ

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 performed even if name is a reserved word, alias, etc. Without the -v option, whence is similar to command -v except that whence won't 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 (i.e. asynchronous) jobs that currently exist; this information can be displayed using the jobs commands. 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, and the state of the terminal is saved or restored when a foreground job is stopped or restarted, respectively. ๐ŸŽฎ

Note that only commands that create processes (e.g. asynchronous commands, subshell commands, and non-built-in, non-function commands) can be stopped; commands like read cannot be. ๐Ÿšซ

When a job is created, it is assigned a job number. For interactive shells, this number is printed inside โ€œ[..]โ€, followed by the process IDs of the processes in the job when an asynchronous command is run. A job may be referred to in the bg, fg, jobs, kill, and wait commands either by the process ID 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.
  • %- โ€” the job that would be the %+ job if the latter did not exist.
  • %n โ€” the job with job number n.
  • %?string โ€” the job with its command containing the string string (an error occurs if multiple jobs are matched).
  • %string โ€” the job with its command starting with the string string (an error occurs if multiple jobs are matched).

When a job changes state (e.g. a background job finishes or foreground job is stopped), the shell prints the following status information: ๐Ÿ“ข

      [number] flag status command

where...

  • number โ€” is the job number of the job;
  • flag โ€” is the โ€˜+โ€™ or โ€˜-โ€™ character 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:
    • Done [number] โ€” the job exited. number is the exit status of the job, which is omitted if the status is zero.
    • 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).
    • 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 (e.g. memory fault, hangup); use kill -l for a list of signal descriptions. The โ€œcore dumpedโ€ message indicates the process created a core file.
  • command โ€” is 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 you try to bail out of the shell while there are jobs sitting in the stopped state, the shell will warn you that, bestie, there are stopped jobs and it will not let you leave. Rude? A little. Protective? Very. If you immediately try to exit again, those stopped jobs get sent a SIGHUP signal and the shell dips out for real. ๐Ÿ’€

Same energy with running jobs: if the nohup option is not set and there are running jobs when you try to exit a login shell, the shell warns you and doesn't exit. Try again right away and the running jobs get a SIGHUP signal, and then the shell exits. Bye bestie ๐Ÿซถ


๐ŸŽ€ Interactive input line editing ๐ŸŽ€

When you're in an interactive session, the shell reads command lines from a tty(4) in one of three modes, and which one is controlled by the emacs, gmacs, and vi options โ€” and listen, at most one of these can be set at a time, no greedy behaviour. The default is emacs. ๐Ÿ‘‘

You can set an editing mode explicitly with the set built-in, or implicitly through the EDITOR and VISUAL environment variables. If none of these options are enabled, the shell just reads lines using the normal tty(4) driver, plain and simple. If the emacs or gmacs option is set, the shell lets you do emacs-like editing of the command; same deal, if vi is set, you get vi-like editing. All these modes are described in detail in the sections below. ๐Ÿ’…

In these editing modes, if a line is longer than the screen width (check the COLUMNS parameter, iykyk), a <yellow>></yellow>, <yellow>+</yellow>, or <yellow><</yellow> character shows up in the last column to tell you there are more characters after, before and after, or before the current position, respectively. The line just scrolls horizontally as needed. โœจ


โœจ Emacs editing mode โœจ

When the emacs option is set, interactive input line editing is enabled. Warning: this mode is slightly different from the emacs mode in the original Korn shell โ€” not me being dramatic, that's literally in the docs. 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, and these bindings can be changed using the bind command. ๐ŸŒˆ

The following is a list of available editing commands. Each description starts with the name of the command, suffixed with a colon; 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 โ€” e.g. the ASCII ESC character is written as ^[. ^[A-Z] sequences are not case sensitive. 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. Also, many editing commands are useful only on terminals with a visible cursor. The default bindings were chosen to resemble corresponding Emacs key bindings. The user's tty(4) characters (e.g. ERASE) are bound to reasonable substitutes and override the default bindings. ๐Ÿงš
  • abort: โ€” ^C, ^G. Useful as a response to a request for a search-history pattern in order to abort the search. Escape hatch, slay. ๐Ÿƒโ€โ™€๏ธ
  • auto-insert: โ€” [n]. Simply causes the character to appear as literal input. Most ordinary characters are bound to this. ๐ŸŒธ
  • backward-char: โ€” [n] ^B, ^X^D. Moves the cursor backward n characters. โฌ…๏ธ
  • backward-word: โ€” [n] ^[b. Moves the cursor backward to the beginning of the word; words consist of alphanumerics, underscore (_), and dollar sign ($) characters. ๐Ÿ”™
  • 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. Uppercase the first character in the next n words, leaving the cursor past the end of the last word. โœจ
  • clear-screen: โ€” ^L. Clears the screen if the TERM parameter is set and the terminal supports clearing the screen, then reprints the prompt string and the current input line. ๐Ÿงผ
  • 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 which 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 beep to be sounded). ๐Ÿ””

Custom completions may be configured by creating an array named complete_command, optionally suffixed with an argument number to complete only for a single argument. So defining an array named complete_kill provides possible completions for any argument to the kill(1) command, but complete_kill_1 only completes the first argument. For example, the following command makes oksh offer a selection of signal names for the first argument to kill(1):

set -A complete_kill_1 -- -9 -HUP -INFO -KILL -TERM
  • 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 above. ๐Ÿ‘‘
  • complete-file: โ€” ^[^X. Automatically completes as much as is unique of the file name having the partial word up to the cursor as its prefix, as in the complete command described above. ๐Ÿ“
  • complete-list: โ€” ^I, ^[=. Complete as much as is possible of the current word, and list the possible completions for it. If only one completion is possible, match as in the complete command above. ๐Ÿ“
  • delete-char-backward: โ€” [n] ERASE, ^?, ^H. Deletes n characters before the cursor. ๐Ÿ—‘๏ธ
  • delete-char-forward: โ€” [n] Delete. Deletes n characters after the cursor. โœ‚๏ธ
  • delete-word-backward: โ€” [n] WERASE, ^[ERASE, ^W, ^[^?, ^[^H, ^[h. Deletes n words before the cursor. ๐Ÿ’จ
  • delete-word-forward: โ€” [n] ^[d. Deletes n words after the cursor. ๐Ÿงน
  • down-history: โ€” [n] ^N, ^XB. 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 a * 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, ^XC. Moves the cursor forward n characters. โžก๏ธ
  • forward-word: โ€” [n] ^[f. Moves the cursor forward to the end of the *n*th word. ๐Ÿš€
  • goto-history: โ€” [n] ^[g. Goes to history number n. ๐ŸŽฏ
  • kill-line: โ€” KILL. Deletes the entire input line. ๐Ÿ’€
  • 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 above. ๐Ÿ“‚
  • newline: โ€” ^J, ^M. Causes the current input line to be processed by the shell. The current cursor position may be anywhere on the line. โ†ฉ๏ธ
  • newline-and-next: โ€” ^O. Causes the current input line to be processed by the shell, and the next line from history becomes the current line. This is only useful after an up-history or search-history. ๐Ÿ”
  • no-op: โ€” QUIT. This does nothing. ๐Ÿ˜ถ
  • prev-hist-word: โ€” [n] ^[., ^[_. The last (*n*th) word of the previous command is inserted at the cursor. ๐Ÿ•ฐ๏ธ
  • quote: โ€” ^^. The following character is taken literally rather than as an editing command. ๐Ÿ›ก๏ธ
  • redraw: โ€” Reprints the prompt string and the current input line. ๐Ÿ–Œ๏ธ
  • search-character-backward: โ€” [n] ^[^]. Search backward in the current line for the *n*th occurrence of the next character typed. ๐Ÿ”
  • search-character-forward: โ€” [n] ^]. Search forward in the current line for the *n*th occurrence 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. ๐Ÿ“
  • 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, ^XA. Scrolls the history buffer backward n lines (earlier). โช
  • upcase-word: โ€” [n] ^[U, ^[u. Uppercase the next n words. ๐Ÿ” 
  • quote: ^V โ€” bestie this is just a synonym for ^^. Same energy, different key.
  • yank: ^Y โ€” pastes the most recently killed text string right at the current cursor position. ๐Ÿ’–
  • yank-pop: ^[y โ€” right after a yank, this swaps the text you just pasted out for the next previously killed text string. Cycling through your kills like it's a lil carousel ๐ŸŽ 

The following editing commands lack default bindings but can be used with the bind command:

  • kill-region โ€” deletes the input between the cursor and the mark. Bye bye โœ‚๏ธ

๐ŸŒˆ Vi editing mode ๐ŸŒˆ

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

  • You start out in insert mode. No hunting for a key first, you're already in โœจ
  • There are file name and command completion commands: =, \, *, ^X, ^E, ^F, and, optionally, โŸจtabโŸฉ and โŸจescโŸฉ.
  • The _ command is different โ€” in oksh it's the last argument command; in vi(1) it goes to the start of the current line.
  • The / and G commands move in the opposite direction to the j command. Yes really, they're built different ๐Ÿ’…
  • Commands which don't make sense in a single line editor are not available (e.g. screen movement commands and ex(1)-style colon (:) commands). It's one line, bestie, there's no screen to scroll ๐Ÿ™ˆ

Note that the ^X stands for control-X; also โŸจescโŸฉ, โŸจspaceโŸฉ, and โŸจtabโŸฉ are used for escape, space, and tab, respectively (no kidding). ๐Ÿซถ

Like vi(1), 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; however, some characters are treated specially. In particular, the following characters are taken from current tty(4) 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 to the above, the following characters are also treated specially in insert mode:

  • ^E โ€” Command and file name enumeration (see below).
  • ^F โ€” Command and file name completion (see below). If used twice in a row, the list of possible completions is displayed; if used a third time, the completion is undone. Three taps and we're back where we started, iconic ๐ŸŽ€
  • ^H โ€” Erases previous character.
  • ^J | ^M โ€” End of line. The current line is read, parsed, and executed by the shell. โœจ
  • ^L โ€” Clear the screen (if possible) and redraw the current line. See the clear-screen command in โ€œEmacs editing modeโ€ for more information.
  • ^R โ€” Redraw the current line.
  • ^V โ€” Literal next. The next character typed is not treated specially (can be used to insert the characters being described here). It's giving "ignore the vibes, just take the key" ๐Ÿ’€
  • ^X โ€” Command and file name expansion (see below).
  • โŸจescโŸฉ โ€” Puts the editor in command mode (see below).
  • โŸจtabโŸฉ โ€” Optional file name and command completion (see ^F above), enabled with set -o vi-tabcomplete.

In command mode, each character is interpreted as a command. Characters that don't correspond to commands, are illegal combinations of commands, or are commands that can't be carried out, all cause beeps. ๐Ÿ˜ญ In the following command descriptions, an [n] indicates the command may be prefixed by a number (e.g. 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, and non-whitespace characters (e.g. โ€œab2*&^โ€ contains two words) and a โ€œbig-wordโ€ is a sequence of non-whitespace characters. Slay, vocab lesson done ๐Ÿ’œ

โœจ Special oksh vi commands โœจ

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

  • [n]_ โ€” Insert a space followed by the nth big-word from the last command in the history at the current position and enter insert mode; 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).
  • [n]g โ€” Like G, except if n is not specified, it goes to the most recent remembered line.
  • [n]v โ€” Edit line n using the vi(1) 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 characters โ€˜;โ€™, โ€˜|โ€™, โ€˜&โ€™, โ€˜(โ€™, or โ€˜)โ€™, and does not contain a slash (โ€˜/โ€™), then 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]โŸจescโŸฉ โ€” Command/file name completion. Replace the current big-word with the longest unique match obtained after performing command and 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 nth possible completion 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.
  • @c โ€” Macro expansion. Execute the commands found in the alias _c.

๐Ÿฆ‹ Intra-line movement commands ๐Ÿฆ‹

  • [n]h and [n]^H โ€” Move left n characters.
  • [n]l and [n]โŸจspaceโŸฉ โ€” Move right n characters.
  • 0 โ€” Move to column 0.
  • ^ โ€” Move to the first non-whitespace character.
  • [n]| โ€” Move to column n.
  • $ โ€” Move to the last character.
  • [n]b โ€” Move back n words.
  • [n]B โ€” Move back n big-words.
  • [n]e โ€” Move forward to the end of the word, n times.
  • [n]E โ€” Move forward to the end of the big-word, n times.
  • [n]w โ€” Move forward n words.
  • [n]W โ€” Move forward n big-words.
  • % โ€” Find match. The editor looks forward for the nearest parenthesis, bracket, or brace and then moves the cursor to the matching parenthesis, bracket, or brace.
  • [n]fc โ€” Move forward to the nth occurrence of the character c.
  • [n]Fc โ€” Move backward to the nth occurrence of the character c.
  • [n]tc โ€” Move forward to just before the nth occurrence of the character c.
  • [n]Tc โ€” Move backward to just before the nth occurrence of the character c.
  • [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 ๐ŸŒธ

  • [n]j, [n]+, and [n]^N โ€” Move to the nth next line in the history.
  • [n]k, [n]-, and [n]^P โ€” Move to the nth previous line in the history.
  • [n]G โ€” Move to line n in the history; if n is not specified, the number of the first remembered line is used.
  • [n]g โ€” Like G, except if n is not specified, it goes to the most recent remembered line.
  • [n]/string โ€” Search backward through the history for the nth line containing 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.
  • [n]n โ€” Search for the nth occurrence of the last search string; the direction of the search is the same as the last search.
  • [n]N โ€” Search for the nth occurrence of the last search string; the direction of the search is the opposite of the last search.

๐Ÿ’– Edit commands ๐Ÿ’–

  • [n]a โ€” Append text n times; goes into insert mode just after the current position. The append is only replicated if command mode is re-entered i.e. โŸจescโŸฉ is used.
  • [n]A โ€” Same as a, except it appends at the end of the line.
  • [n]i โ€” Insert text n times; goes into insert mode at the current position. The insertion is only replicated if command mode is re-entered i.e. โŸจescโŸฉ is used.
  • [n]I โ€” Same as i, except the insertion is done just before the first non-blank character.
  • [n]s โ€” Substitute the next n characters (i.e. 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.
  • [n]cmove-cmd โ€” Change from the current position to the position resulting from n move-cmds (i.e. 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 (i.e. delete to the end of the line and go into insert mode).
  • [n]x โ€” Delete the next n characters.
  • [n]X โ€” Delete the previous n characters.
  • D โ€” Delete to the end of the line.
  • [n]dmove-cmd โ€” Delete from the current position to the position resulting from n move-cmds; move-cmd is a movement command (see above) or d, in which case the current line is deleted.
  • [n]rc โ€” Replace the next n characters with the character c.
  • [n]R โ€” 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.
  • [n]ymove-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.
  • [n]p โ€” Paste the contents of the yank buffer just after the current position, n times.
  • [n]P โ€” Same as p, except the buffer is pasted at the current position.

โญ Miscellaneous vi commands โญ

  • ^J and ^M โ€” bestie, the current line is read, parsed, and then executed by the shell. like, it actually runs. no takebacks ๐Ÿ’…
  • ^L โ€” clears the screen (if that's even possible on your terminal) and redraws the current line. fresh page energy โœจ
  • ^R โ€” just redraws the current line. no clearing, just a lil glow-up ๐ŸŽ€
  • [n]. โ€” redo the last edit command n times. yes, n times. go off ๐Ÿ”
  • u โ€” undo the last edit command. the classic. the icon ๐Ÿ‘‘
  • U โ€” undo all changes that have been made to the current line. nuke it back to how it started ๐Ÿ’€
  • intr and quit โ€” the interrupt and quit terminal characters cause the current line to be deleted and a brand new prompt to be printed. so like, your line is gone gone. rip ๐Ÿซถ

๐ŸŒธ FILES ๐ŸŒธ

  • ~/.profile โ€” User's login profile.
  • /etc/ksh.kshrc โ€” Global configuration file. Not sourced by default. (yes bestie, you gotta source it yourself, it's not gonna do it for you ๐Ÿ™ˆ)
  • /etc/profile โ€” System login profile.
  • /etc/shells โ€” Shell database.
  • /etc/suid_profile โ€” Privileged shell profile. main character security vibes ๐Ÿ”ฅ

โœจ SEE ALSO โœจ

csh(1), ed(1), mg(1), sh(1), stty(1), vi(1), shells(5), environ(7), script(7)

S. R. Bourne, โ€œThe UNIX Shellโ€, Bell System Technical Journal, 57:6, pp. 1971-1990, 1978.

S. R. Bourne, An Introduction to the UNIX Shell, AT&T Bell Laboratories, Computing Science Technical Report, 70, 1978.

Morris Bolsky and David Korn, The KornShell Command and Programming Language, Prentice Hall, First Edition 1989, ISBN 0135169720.

Stephen G. Kochan and Patrick H. Wood, UNIX Shell Programming, 3rd Edition, Sams, 2003, ISBN 0672324903.

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

the reading list is giving โœจacademiaโœจ and honestly? valid. iykyk ๐Ÿ“š

๐Ÿ’œ VERSION ๐Ÿ’œ

This page documents version @(#)PD KSH v5.2.14 99/07/13.2 of the public domain Korn shell.


๐Ÿซถ 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 of pdksh was created by Eric Gisin, and it was subsequently maintained by John R. MacMillan <change!john@sq.sq.com>, Simon J. Gerraty <sjg@zen.void.oz.au>, and 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.

shoutout to the whole founding friend group fr fr, they literally built the thing you're using right now ๐ŸŒˆ๐Ÿ‘‘

๐Ÿ’€ BUGS ๐Ÿ’€

$(command) expressions are currently parsed by finding the closest matching (unquoted) parenthesis. Thus constructs inside $(command) may produce an error. For example, the parenthesis in โ€˜x);;โ€™ is interpreted as the closing parenthesis in โ€˜$(case x in x);; *);; esac)โ€™.

okay so this one's a real one, bestie โ€” not a cute lil quirk. if you're nesting stuff inside $(command) with parentheses floating around in there, the parser can get confused and throw an error at you. be careful, fr fr ๐Ÿ˜ญ

and that's the whole page, bestie!! ๐Ÿ’–โœจ this one comes from the Debian crew, dated April 24, 2025, and it documents version @(#)PD KSH v5.2.14 99/07/13.2 of oksh โ€” so if you ever forget literally any of this, just run man oksh and it's all right there waiting for you. go forth and slay your shell scripts, you've got this ๐Ÿฆ‹๐ŸŽ€๐Ÿ‘‘

๐Ÿ“ฆ where this page comes from