MKSH(1)
๐ MKSH โ MirBSD Korn shell ๐
okay so bestie, welcome to the manual page for <strong>mksh</strong> โ also known as <strong>sh</strong> โ from the General Commands Manual. This is the MirBSD Korn shell. Buckle up, she's iconic. ๐
โจ NAME โจ
<strong>mksh</strong>, <strong>sh</strong> โ MirBSD Korn shell. That's it, that's the name, she's serving ๐ฆ
๐ธ SYNOPSIS ๐ธ
mksh [-+abCefhiklmnprUuvXx] [-T [!]tty | -] [-+o option] [-c string | -s
| file [argument ...]]
builtin-name [argument ...]
๐ DESCRIPTION ๐
mksh is a command interpreter, and she's built for both interactive use and shell script use. Her command language is a superset of the <strong>sh(C)</strong> shell language and is largely compatible with the original Korn shell. ๐
ngl, quick heads-up: sometimes this manual page will hand out scripting advice, and while it does sometimes take portable shell scripting or various standards into account, <strong>all information is first and foremost presented with mksh in mind</strong> and should be taken as such. Periodt. ๐
๐ซถ I use Android, OS/2, etc. so what...? ๐ซถ
Please refer to: http://www.mirbsd.org/mksh-faq.htm#sowhatismksh โจ
๐ Invocation ๐
Most builtins can be called directly, for example if a link points from its name to the shell; not all make sense, have been tested or work at all though. ๐ญ
The options are as follows:
-c stringโmkshwill execute the command(s) contained instring. ๐-iโ Interactive shell. A shell that reads commands from standard input is "interactive" if this option is used <strong>or</strong> if both standard input and standard error are attached to atty(4). An interactive shell has job control enabled, ignores theSIGINT,SIGQUITandSIGTERMsignals, and prints prompts before reading input (see thePS1andPS2parameters). It also processes theENVparameter or themkshrcfile (see below). For non-interactive shells, thetrackalloption is on by default (see thesetcommand below). ๐-lโ Login shell. If the name or basename the shell is called with (i.e.argv[0]) starts with '-' <strong>or</strong> if this option is used, the shell is assumed to be a login shell; see "Startup files" below. ๐-pโ Privileged shell. A shell is "privileged" if the real user ID or group ID does <strong>not</strong> match the effective user ID or group ID (seegetuid(2)andgetgid(2)). Clearing the privileged option causes the shell to set its effective user ID (group ID) to its initial real user ID (group ID). For further implications, see "Startup files". If the shell is privileged and this flag is not explicitly set, the "privileged" option is cleared automatically after processing the startup files. ๐ฅ-rโ Restricted shell. A shell is "restricted" if the basename the shell is called with, after '-' processing, starts with 'r' <strong>or</strong> if this option is used. The following restrictions come into effect <strong>after the shell processes any profile andENVfiles</strong>:- The
cd(andchdir) command is disabled. ๐ - The
SHELL,ENVandPATHparameters cannot be changed. - Command names can't be specified with absolute or relative paths.
- The
-poption of the built-in commandcommandcan't be used. - Redirections that create files can't be used (i.e. "
>", ">|", ">>", "<>"). ๐
- The
-sโ The shell reads commands from standard input; all non-option arguments are positional parameters.-T nameโ Spawnmkshon thetty(4)device given. The pathsname,/dev/ttyCnameand/dev/ttynameare attempted in order. Unlessnamebegins with an exclamation mark ('!'), this is done in a subshell and returns immediately. Ifnameis a dash ('-'), detach from controlling terminal (daemonise) instead. ๐ธ
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. โจ
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 name the shell was called with (i.e. argv[0]) is used. ๐ฆ
The exit status of the shell is <strong>127</strong> 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 <strong>zero</strong> if no command is executed. ๐
๐ Startup files ๐
For the actual location of these files, see "FILES". A login shell processes the system profile first. A privileged shell then processes the suid profile. A non-privileged login shell processes the user profile next. A non-privileged interactive shell checks the value of the ENV parameter after subjecting it to parameter, command, arithmetic and tilde ('~') substitution; if unset or empty, the user mkshrc profile is processed; otherwise, if a file whose name is the substitution result exists, it is processed; non-existence is silently ignored. A privileged shell then drops privileges if neither was the -p option given on the command line nor set during execution of the startup files. ๐
๐ Command syntax ๐
The shell begins parsing its input by removing any backslash-newline combinations, then 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; ";;", ";&" and ";|" are 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. Note that the following characters are also treated specially by the shell and <strong>must be quoted</strong> 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 programmes 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 redirection" below) and command words; the only restriction is that <strong>parameter assignments come before any command words</strong>. 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). Note that 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 <strong>127</strong>; if it could not be executed, the exit status is <strong>126</strong>); 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 <strong>0</strong> 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 (see there). All commands of a pipeline are executed in separate subshells; this is allowed by POSIX but <strong>differs from both variants of AT&T UNIX ksh</strong>, where all but the last command were executed in subshells; see the read builtin's description for implications and workarounds. ๐ญ 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. Note that 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
๐
okay so the & token? she makes the command in front of her run asynchronously ๐
like, the shell starts it and does not sit around waiting for it to finish. (she's not ghosting it tho โ the shell does keep track of the status of asynchronous commands; see โJob controlโ below ๐)
when an asynchronous command gets started while job control is disabled (i.e. in most scripts, bestie), the command starts with signals SIGINT and SIGQUIT ignored and with input redirected from /dev/null โ however, redirections specified in the asynchronous command have precedence, so you can absolutely override that.
the |& operator starts a co-process, which is a special kind of asynchronous process (see โCo-processesโ below ๐ซถ).
not me reminding you again but: a command must follow the&&and||operators, while it need not follow&,|∨. that's the rule. periodt.
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 recognised if they're unquoted and if they're used as the first word of a command (i.e. they can't be preceded by parameter assignments or redirections โ no sneaking up on them):
case else function then ! (
do esac if time [[ ((
done fi in until {
elif for select while }
in the compound command descriptions below, 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, all of these are valid ๐:
$ { echo foo; echo bar; }
$ { echo foo; echo bar<newline>}
$ { { echo foo; echo bar; } }
and this one is not valid, bestie, do not do this:
$ { echo foo; echo bar }
case โ the pattern matchmaker ๐
case word in [[(] pattern [| pattern] ...) list <terminator>] ... esac
The case statement attempts 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, iconic. 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 ๐ธ
for historical reasons, open and close braces may be used instead of in and esac, for example: case $foo { (ba[rz]|blah) date ;; }
the list <terminator>s are:
;;โ terminate after the list.;&โ fall through into the next list.;|โ evaluate the remaining pattern-list tuples.
the exit status of a case statement is that of the executed list; if no list is executed, the exit status is zero.
for โ the lil loop that could ๐
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. the exit status of a for statement is the last exit status of list; if list is never executed, the exit status is zero. if in is not used to specify a word list, the positional parameters ($1, $2, etc.) are used instead; in this case, use a newline instead of the semicolon (;) for portability ๐ซถ
for historical reasons, open and close braces may be used instead of do and done, as in for i; { echo $i; } (not portable).
function name { list; } โ making a whole function ๐
defines the function name (see โFunctionsโ below). all redirections specified after a function definition are performed whenever the function is executed, not when the function definition is executed. big difference, lowkey important.
name() command โ the other way to make a function
mostly the same as function (see above and โFunctionsโ below). most amounts of space and tab after name will be ignored, she's chill like that.
function name() { list; } โ the bashism
bashism for name() { list; } (the function keyword is ignored).
if โ the decision maker ๐
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 whatever non-conditional (not the first) list that is executed; if no non-conditional list is executed, the exit status is zero.
select โ the menu maker, so cute ๐
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 words is printed on standard error, followed by a prompt (PS3: normally โ#? โ). a number corresponding to one of the enumerated words is then read from standard input, name is set to the selected word (or unset if the selection is not valid), REPLY is set to what was read (leading and trailing space is stripped), and list is executed. if a blank line (i.e. zero or more IFS octets) is entered, the menu is reprinted without executing list ๐
when list completes, the enumerated list is printed if REPLY is empty, 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. the exit status of a select statement is zero if a break statement is used to exit the loop, non-zero otherwise. if in word ... is omitted, the positional parameters are used. for historical reasons, open and close braces may be used instead of do and done, as in: select i; { echo $i; }
time [-p] [pipeline]
the โCommand executionโ section describes the time reserved word. go read it, bestie ๐
until โ the backwards while ๐
until list; do list; done
this works like while (see below), except that the body list is executed only while the exit status of the first list is non-zero. yes it's giving opposite day, that's the whole point โจ
while โ the pre-checked loop ๐
while list; do list; done
a while is a pre-checked loop. its body list 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.
[[ expression ]] โ test but make it fierce ๐
similar to the test and [ ... ] commands (described later), with the following exceptions:
- field splitting and globbing are not performed on arguments.
- the
-a(AND) and-o(OR) operators are replaced, respectively, with&&and||. - operators (e.g.
-f,=,!) must be unquoted. - 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 filefooexists and is readable:
$ [[ -r foo && $(<foo) = b*r ]]
- the second operand of the
=and!=expressions is a pattern (e.g. the comparison[[ foobar = f*r ]]succeeds). this even works indirectly, while quoting forces literal interpretation:
$ bar=foobar; baz='f*r' # or: baz='f+(o)b?r'
$ [[ $bar = $baz ]]; echo $? # 0
$ [[ $bar = "$baz" ]]; echo $? # 1
{ list; } โ grouping, no fork ๐
compound construct; list is executed, but not in a subshell. note that { and } are reserved words, not meta-characters. iykyk.
(list) โ grouping, but make it a subshell ๐ฆ
execute list in a subshell, forking. there is no implicit way to pass environment changes from a subshell back to its parent. sorry bestie, that's just how she is ๐ญ
(( expression )) โ math time โญ
the arithmetic expression expression is evaluated; equivalent to let "expression" in a compound construct. see the let command and โArithmetic expressionsโ below.
โจ Quoting โจ
quoting is used to prevent the shell from treating characters or words specially. there are three methods of quoting:
\quotes the following character, unless it is at the end of a line, in which case both the\and the newline are stripped.- a single quote (
') quotes everything up to the next single quote (this may span lines). - a double quote (
") quotes all characters, except$,\and`, up to the next unescaped double quote.
$ and ` inside double quotes have their usual meaning (i.e. parameter, arithmetic or command substitution) โ except no field splitting is carried out on the results of double-quoted substitutions, and the old-style form of command substitution has backslash-quoting for double quotes enabled ๐
if a \ inside a double-quoted string is followed by ", $, \ or `, only the \ is removed, i.e. the combination 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.
if a single-quoted string is preceded by an unquoted $, C style backslash expansion (see below) is applied (even single quote characters inside can be escaped and do not terminate the string then); the expanded result is treated as any other single-quoted string. if a double-quoted string is preceded by an unquoted $, the $ is simply ignored. iconic behaviour tbh ๐ธ
โจ Backslash expansion โจ
in places where backslashes are expanded, certain C and AT&T UNIX ksh or GNU bash style escapes are translated. these include \a, \b, \f, \n, \r, \t, \U########, \u#### and \v. for \U######## and \u####, # means a hexadecimal digit (up to 4 or 8); these translate a Universal Coded Character Set codepoint to UTF-8 (see โCAVEATSโ on UCS limitations ๐). furthermore, \E and \e expand to the escape character.
in the print builtin mode, octal sequences must have the optional up to three octal digits # prefixed with the digit zero (\0###); hexadecimal sequences \x## are limited to up to two hexadecimal digits #; both octal and hexadecimal sequences convert to raw octets; \%, where % is none of the above, translates to \% (backslashes are retained). don't @ me, that's the spec ๐
okay so, picking right back up where we were bestie ๐ โ in C style mode, raw octet-yielding octal sequences \### are not allowed to have that one up to three octal digits prefixed with the digit zero, like, the zero is simply not invited ๐ซ. Hexadecimal sequences \x## are greedy little gremlins: they eat up as many hexadecimal digits โ#โ as they possibly can and only stop when they hit the first non-xdigit. Below \x100 these hand you raw octets; above that, they're equivalent to \U#. And then the sequence \c%, where โ%โ is any octet, translates to Ctrl-%, which literally means \c? becomes DEL and everything else gets bitwise ANDed with 0x9F. Finally \%, where โ%โ is none of the above, just translates to % โ the backslashes get trimmed even before newlines. periodt. ๐
๐ธ Aliases ๐ธ
There are two types of aliases, bestie: 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. And 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,
- a quoted word is found, or
- an alias word that is currently being expanded is found.
Aliases are specifically an interactive feature: while they do happen to work in scripts and on the command line in some cases, aliases are expanded during lexing, so their use must be in a separate command tree from their definition โ otherwise, the alias will not be found ๐ญ. Noticeably, command lists (separated by semicolon, in command substitutions also by newline) may be one same parse tree.
The following command aliases are defined automatically by the shell:
autoload='\\builtin typeset -fu'
functions='\\builtin typeset -f'
hash='\\builtin alias -t'
history='\\builtin fc -l'
integer='\\builtin typeset -i'
local='\\builtin typeset'
login='\\builtin exec login'
nameref='\\builtin typeset -n'
nohup='nohup '
r='\\builtin fc -e -'
type='\\builtin whence -v'
Tracked aliases allow the shell to remember where it found a particular command ๐. The first time the shell does a path search for a command that is marked as a tracked alias, it saves the full path of the command. The next time the command is executed, the shell checks the saved path to see that it is still valid, and if so, avoids repeating the path search โ efficiency queen ๐
. 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(1), grep(1), ls(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. So:
- Parameter substitutions, which are described in detail in the next section, take the form
$nameor${...}; - command substitutions take the form
$(command)or (deprecated)`command`or (executed in the current environment)${ command;}and strip trailing newlines; and - arithmetic substitutions take the form
$((expression)).
Parsing the current-environment command substitution requires a space, tab or newline after the opening brace and that the closing brace be recognised as a keyword (i.e. is preceded by a newline or semicolon). They are also called funsubs (function substitutions) and behave like functions in that local and return work, and in that exit terminates the parent shell; shell options are shared. ๐
Another variant of substitution are the valsubs (value substitutions) ${|command;} which are also executed in the current environment, like funsubs, but share their I/O with the parent; instead, they evaluate to whatever the, initially empty, expression-local variable REPLY is set to within the commands.
If a substitution appears outside of double quotes, the results of the substitution are generally subject to word or field splitting according to the current value of the IFS parameter. The IFS parameter specifies a list of octets which are used to break a string up into several words; any octets from the set space, tab and newline that appear in the IFS octets are called โIFS whitespaceโ. Sequences of one or more IFS whitespace octets, in combination with zero or one non-IFS whitespace octets, delimit a field. As a special case, leading and trailing IFS whitespace is stripped (i.e. no leading or trailing empty field is created by it); leading or trailing non-IFS whitespace does create an empty field.
Example, bestie: 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 empty string, no field splitting is done; if it 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.
heads up bestie: 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 is replaced by the output generated by the specified command which is run in a subshell. For $(command) and ${|command;} and ${ command;} substitutions, normal quoting rules are used when command is parsed; however, for the deprecated `command` form, a โ\โ followed by any of โ$โ, โโ or โ\โ is stripped (as is โ"โ when the substitution is part of a double-quoted string); a backslash โ\โ followed by any other character is unchanged. As a special case in command substitutions, a command of the form <fileis interpreted to mean substitute the contents of *file*. Note that$(<foo)has the same effect as$(cat foo)`. ๐ฑ
Note that some shells do not use a recursive parser for command substitutions, leading to failure for certain constructs; to be portable, use as workaround x=$(cat) <<\EOF (or the newline-keeping x=<<\EOF extension) instead to merely slurp the string. IEEE Std 1003.1 (โPOSIX.1โ) recommends using case statements of the form x=$(case $foo in (bar) echo $bar ;; (*) echo $baz ;; esac) instead, which would work but not serve as example for this portability issue.
x=$(case $foo in bar) echo $bar ;; *) echo $baz ;; esac)
# above fails to parse on old shells; below is the workaround
x=$(eval $(cat)) <<\EOF
case $foo in bar) echo $bar ;; *) echo $baz ;; esac
EOF
Arithmetic substitutions are replaced by the value of the specified expression. For example, the command print $((2+3*4)) displays 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. Array indices in mksh are limited to the range 0 through 4294967295, inclusive. That is, they are a 32-bit unsigned integer.
Parameter substitutions take the form $name, ${name} or ${name[expr]} where name is a parameter name. Substitutions of an array in scalar context, i.e. without an expr in the latter form mentioned above, expand the element with the key โ0โ. Substitution of all array elements with ${name[*]} and ${name[@]} works equivalent to $* and $@ for positional parameters. If substitution is performed on a parameter (or an array parameter element) that is not set, an empty string is substituted unless the nounset option (set -u) is set, in which case an error occurs. ๐ค
Parameters can be assigned values in a number of ways. First, the shell implicitly sets some parameters like โ#โ, โPWDโ and โ$โ; this is the only way the special single character parameters are set. Second, parameters are imported from the shell's environment at startup. Third, parameters can be assigned values on the command line: for example, 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 recognise a parameter assignment. The construct FOO+=baz is also recognised; the old and new values are string-concatenated with no separator. The fourth way of setting a parameter is with the export, readonly and typeset commands; see their descriptions in the โCommand executionโ section. Fifth, for and select loops set parameters as well as the getopts, read and set -A commands. 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 empty, it is substituted; otherwise, word is substituted.
Okay bestie, this is the rest of the parameter substitution menu and it's lowkey a whole โจpersonalityโจ โ every ${...} trick you can pull. Let's go one by one, no skips, I'm not gatekeeping.
${name:+word}โ ifnameis set and not empty,wordgets substituted; otherwise, literally nothing gets substituted. It's giving "use this alt or get nothing" ๐${name:=word}โ ifnameis set and not empty, it's substituted as-is; otherwisewordgets assigned to it and then the resulting value ofnameis what you get back. Sneaky little assignment moment, we love her.${name:?word}โ ifnameis set and not empty, she's substituted; otherwisewordgets printed on standard error (preceded byname:) and an error happens (which normally terminates a shell script, a function, or a script sourced using the.built-in). Ifwordis omitted, the stringparameter null or not setis used instead. Dramatic but valid ๐ญ
Heads up: for all of the above,wordis actually considered quoted, and special parsing rules apply. Those parsing rules also differ depending on whether the whole expression is double-quoted:wordthen uses double-quoting rules, except for the double quote itself (") and the closing brace, which โ if backslash escaped โ gets quote removal applied.
And in all of those modifiers above, the : can be omitted โ when you do that, the conditions only depend on name being set (as opposed to set and not empty). If word is needed, parameter, command, arithmetic and tilde substitution are performed on it; if word isn't needed, it is not evaluated at all. Efficient queen. โจ
The following forms of parameter substitution can also be used, bestie, and they're iconic:
${#name}โ the number of positional parameters ifnameis*,@or not specified; otherwise it's the length (in characters) of the string value of parametername.${#name[*]}${#name[@]}โ the number of elements in the arrayname. Count 'em ๐งฎ${%name}โ the width (in screen columns) of the string value of parametername, or-1if${name}contains a control character.${!name}โ the name of the variable referred to byname. This will benameexcept whennameis a name reference (bound variable), created by thenamerefcommand (which is an alias fortypeset -n). Oh andnamecannot be one of most special parameters (see below).${!name[*]}${!name[@]}โ the names of indices (keys) in the arrayname. Yes, the keys. Like a lil peek inside ๐${name#pattern}${name##pattern}โ ifpatternmatches the beginning of the value of parametername, the matched text is deleted from the result of substitution. A single#gives you the shortest match, and two of them (##) give you the longest match.${name%pattern}${name%%pattern}โ like${...#...}but it deletes from the end of the value instead. Mirror image, equally slay.${name/pattern/string}${name/#pattern/string}${name/%pattern/string}${name//pattern/string}โ the longest match ofpatternin the value of parameternameis replaced withstring(deleted ifstringis empty; and the trailing slash/may be omitted in that case). A leading slash followed by#or%causes the pattern to be anchored at the beginning or end of the value, respectively; empty unanchored patterns cause no replacement; a single leading slash, or use of a pattern that matches the empty string, causes the replacement to happen only once; two leading slashes cause all occurrences of matches in the value to be replaced. May be slow on long strings, so don't come crying to me when your 4MB string takes a sec ๐ญ${name@/pattern/string}โ the same as${name//pattern/string}, except that bothpatternandstringare expanded anew for each iteration. Use withKSH_MATCH. Fancy.${name:pos:len}โ the firstlencharacters ofname, starting at positionpos, are substituted. Bothposand:lenare optional. Ifposis negative, counting starts at the end of the string; if it's omitted, it defaults to0. Iflenis omitted or greater than the length of the remaining string, all of it is substituted. Bothposandlenare evaluated as arithmetic expressions. Math girlies rise ๐ง${name@#}โ the hash (using theBAFHalgorithm) of the expansion ofname. This is also used internally for the shell's hashtables. So yes, you're peeking at the shell's own machinery. Main character energy fr fr.${name@Q}โ a quoted expression safe for re-entry, whose value is the value of thenameparameter, is substituted. Perfect for when you need something to survive a round trip ๐
Also: note thatpatternmay need extended globbing pattern (@(...)), single ('...') or double ("...") quote escaping unless-o shis set. Don't say I didn't warn you.
The special parameters ๐
These ones are implicitly set by the shell and cannot be set directly using assignments. They're not like other parameters, they're special. Periodt.
!โ process ID of the last background process started. If no background processes have been started, the parameter is not set. (No job, no!, sad.)#โ the number of positional parameters ($1,$2, etc.).$โ the PID of the shell or, if it is a subshell, the PID of the original shell. Do NOT use this mechanism for generating temporary file names; seemktemp(1)instead. I'm serious, bestie, don't do it ๐ซถ-โ the concatenation of the current single letter options (see thesetcommand 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 to128plus the signal number, but at most255.0โ the name of the shell, determined as follows: the first argument tomkshif it was invoked with the-coption and arguments were given; otherwise the file argument, if it was supplied; or else the name the shell was invoked with (i.e.argv[0]).$0is also set to the name of the current script, or to the name of the current function if it was defined with thefunctionkeyword (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. Further positional parameters may be accessed using${number}.*โ all positional parameters (except0), 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 theIFSparameter (or the empty string ifIFSis unset.@โ 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 empty arguments or splitting arguments with spaces (IFS, actually). The way"$@"is the correct answer every single time, I'm obsessed ๐
The following parameters are set and/or used by the shell. Long list incoming, stay with me, they're all useful:
_(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. Handy lil gremlin.BASHPIDโ the PID of the shell or subshell.CDPATHโ likePATH, but used to resolve the argument to thecdbuilt-in command. Note that ifCDPATHis set and does not contain.or an empty string element, the current directory is not searched. Also, thecdbuilt-in command will display the resulting directory when a match is found in any search path other than the empty path. Big "where am I going" energy.COLUMNSโ set to the number of columns on the terminal or window. If never unset and not imported, always set dynamically; unless the value as reported bystty(1)is non-zero and sane enough (minimum is12x3), defaults to80; similar forLINES. This parameter is used by the interactive line editing modes and by theselect,set -oandkill -lcommands to format information columns. Importing from the environment or unsetting this parameter removes the binding to the actual terminal size in favour of the provided value.ENVโ if this parameter is found to be set after any profile files are executed, the expanded value is used as a shell startup file. It typically contains function and alias definitions. โจEPOCHREALTIMEโ time since the epoch, as returned bygettimeofday(2), formatted as decimaltv_secfollowed by a dot (.) andtv_usecpadded to exactly six decimal digits.EXECSHELLโ if set, this parameter is assumed to contain the shell that is to be used to execute commands thatexecve(2)fails to execute and which do not start with a#!shellsequence.FCEDITโ the editor used by thefccommand (see below).FPATHโ likePATH, but used when an undefined function is executed to locate the file defining the function. It is also searched when a command can't be found usingPATH. See "Functions" below for more information.HISTFILEโ the name of the file used to store command history. When assigned to or unset, the file is opened, history is truncated then loaded from the file; subsequent new commands (possibly consisting of several lines) are appended once they successfully compiled. Also, several invocations of the shell will share history if theirHISTFILEparameters all point to the same file. Sharing is caring, and also chaos ๐
Note: ifHISTFILEis unset or empty, no history file is used. This is different from AT&T UNIXksh. Not a typo, not a bug, just how it is.
HISTSIZEโ the number of commands normally stored for history. The default is2047. The maximum is65535. So like, plenty, but not infinite, okay? ๐HOMEโ the default directory for thecdcommand and the value substituted for an unqualified~(see "Tilde expansion" below).IFSโ internal field separator, used during substitution and by thereadcommand, to split values into distinct arguments; normally set to space, tab and newline. See "Substitution" above for details.
Note: this parameter is not imported from the environment when the shell is started. It's a homegrown thing, she doesn't take visitors.
KSHEGIDโ the effective group id of the shell at startup.KSHGIDโ the real group id of the shell at startup.KSHUIDโ the real user id of the shell at startup.KSH_MATCHโ the last string that matched โจ. Okay so heads up: in a future version this is gonna be an indexed array, with indexes1and up capturing matching groups (we're not there yet bestie). For now it gets set by string comparisons (=and!=) inside double-bracket test expressions when a match is found (which is when!=returns false), bycasewhen a match is encountered, and by all of these substitution operations:${x#pat},${x##pat},${x%pat},${x%%pat},${x/pat/rpl},${x/#pat/rpl},${x/%pat/rpl},${x//pat/rpl}, and${x@/pat/rpl}. There's a whole example at the end of the Emacs editing mode docs if you want the visual ๐KSH_VERSIONโ the name (self-identification) and version of the shell, and it's read-only so don't even try it ๐. Also peep the version commands in the "Emacs editing mode" and "Vi editing mode" sections further down ๐LINENOโ the line number of the function or shell script that's currently being executed. Your little "where am I" tracker ๐LINESโ set to the number of lines on the terminal or window. Defaults to24, and it's always set, unless it was imported or unset. See alsoCOLUMNS๐OLDPWDโ the previous working directory. It's unset ifcdhasn't successfully changed directories since the shell started, or if the shell simply doesn't know where it is (mood, honestly ๐ญ)OPTARGโ when you're usinggetopts, this holds the argument for a parsed option, if that option requires one.OPTINDโ the index of the next argument to be processed when usinggetopts. Pro tip: assigning1to this parameter makesgetoptsprocess arguments from the beginning the next time it's invoked ๐PATHโ a colon-separated list of directories (semicolon on OS/2) that get searched when looking for commands and for files sourced with the.command (see below). And here's the fun part: an empty string that comes from a leading or trailing (semi)colon, or from two adjacent ones, is treated as a.โ i.e. the current directory ๐ซฃPATHSEPโ a colon (semicolon on OS/2), just sitting there for the user's convenience ๐PGRPโ the process ID of the shell's process group leader.PIPESTATUSโ an array holding the errorlevel (exit status) codes, one by one, of the last pipeline that ran in the foreground ๐ฐPPIDโ the process ID of the shell's parent.PS1โ the primary prompt for interactive shells, aka the face of your terminal ๐. Parameter, command and arithmetic substitutions all get performed, and!gets replaced with the current command number (see thefccommand below). If you want a literal!in your prompt, just put!!inPS1.
The default prompt is "$ " for non-root users and "# " for root. And here's a sneaky one: if mksh is invoked by root and PS1 does not contain a # character, the default value will be used even if PS1 already exists in the environment ๐ค
The mksh distribution ships with a sample dot.mkshrc containing a sophisticated example, but you might like this one instead โ note that ${HOSTNAME:=$(hostname)} and the whole root-vs-user distinguishing clause are (in this example) executed at PS1 assignment time, while the $USER and $PWD are escaped and will therefore be evaluated every single time a prompt is displayed:
PS1='${USER:=$(id -un)}'"@${HOSTNAME:=$(hostname)}:\$PWD $(
if (( USER_ID )); then print \$; else print \#; fi) "
Now, a lil warning bestie: 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 your prompt tend to mess things up ๐. You can tell the shell not to count certain sequences (like escape codes) by prefixing your prompt with a character (such as Ctrl-A) followed by a carriage return, and then delimiting the escape codes with that same character. Any occurrences of that character in the prompt are not printed. And by the way โ don't blame me for this hack, it's derived from the original ksh88(1), which actually did print the delimiter character, so you were flat out of luck if you didn't have any non-printing characters ๐
Since backslashes and other special characters may be interpreted by the shell, to set PS1 you either escape the backslash itself or use double quotes. The latter is way more practical ngl. Here's a more complex example that avoids directly entering special characters (like with ^V in the emacs editing mode), and embeds the current working directory in reverse video (colour would work too) inside the prompt string:
x=$(print \\001) # otherwise unused char
PS1="$x$(print \\r)$x$(tput so)$x\$PWD$x$(tput se)$x> "
And due to a strong suggestion from David G. Korn, mksh now also supports the following form โจ:
PS1=$'\1\r\1\e[7m\1$PWD\1\e[0m\1> '
PS2โ the secondary prompt string, by default"> ", used when more input is needed to complete a command.PS3โ the prompt used by theselectstatement when reading a menu selection. Default is"#? ".PS4โ used to prefix commands that get printed during execution tracing (see theset -xcommand below). Parameter, command and arithmetic substitutions are performed before it's printed. Default is"+ ". You might wanna set it to"[$EPOCHREALTIME] "instead, so you get timestamps in there โฐPWDโ the current working directory. May be unset or empty if the shell doesn't know where it is (we've all been there ๐ซ ).RANDOMโ every single timeRANDOMis referenced, it first gets assigned a number between0and32767from a Linear Congruential PRNG ๐ฒREPLYโ the default parameter for thereadcommand when no names are given. Also used inselectloops 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 that assignment plus the value that was assigned โณTMOUTโ if it's 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 that time gets exceeded, the shell exits ๐TMPDIRโ the directory where temporary shell files get created. If this parameter isn't set, or doesn't contain the absolute path of a writable directory, temporary files get created in/tmp.USER_IDโ the effective user id of the shell at startup ๐ชช
๐ธ Tilde expansion ๐ธ
Tilde expansion runs in parallel with parameter substitution, and it's applied to words starting with an unquoted ~ โจ. In parameter assignments (like the ones preceding a simple-command, or the ones occurring in the arguments of a declaration utility), 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 Korn shell, except in POSIX mode, always expands tildes after unquoted equals signs โ not just in assignment context (see below) โ and enables tab completion for tildes after all unquoted colons during command line editing ๐
The characters following the tilde, up to the first / if there is one, are assumed to be a login name. If that login name is empty, +, or -, then the simplified value of the HOME, PWD, or OLDPWD parameter gets substituted, respectively. Otherwise the password file gets searched for the login name, and the tilde expression is substituted with that user's home directory. If the login name isn't found in the password file, or if any quoting or parameter substitution occurs in the login name, then no substitution is performed โ sorry bestie ๐
The home directory of previously expanded login names gets 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 this exact form:
prefix{str1,...,strN}suffix
The expressions expand to N words, each of which is the concatenation of prefix, stri and suffix โ so for example a{c,b{X,Y},d}e expands to four words: ace, abXe, abYe and ade ๐. As noted in that example, brace expressions can be nested, and the resulting words are not sorted. Brace expressions must contain an unquoted comma (,) for expansion to even occur (so {} and {foo} are not expanded, don't even try it). 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 โ and if no files match, the word is left unchanged. The pattern elements mean the following:
?โ matches any single character.*โ matches any sequence of octets.[...]โ matches any of the octets inside the brackets. Ranges of octets can be specified by separating two octets with a-(e.g.[a0-9]matches the letteraor any digit). In order to represent itself, a-must either be quoted or be the first or last octet in the octet list. Similarly, a]must be quoted or be the first octet in the list if it's gonna 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 ๐[!...]โ just like[...], except it matches any octet that is not inside the brackets.*(pattern|...|pattern)โ matches any string of octets 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 octets 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 any string that matches one of the patterns you listed. So?(foo|bar)only ever matches"","foo"and"bar". Nothing else, bestie. ๐@(pattern|...|pattern)โ matches a string that matches exactly one of the patterns you listed. So@(foo|bar)only matches"foo"and"bar". That's it, that's the whole vibe.!(pattern|...|pattern)โ matches literally any string that does not match one of the listed patterns. Examples, because this one's feral:!(foo|bar)matches everything except"foo"and"bar";!(*)matches no strings at all ๐ญ; and!(?)*matches all strings (think about it, bestie, I'll wait ๐ง).
Heads up: complicated globbing โ especially with alternatives โ is slow. Using separate comparisons may (or may not) be faster. No promises either way, that's just how it is.
Another thing: mksh (and pdksh) never matches"."and"..", but AT&T UNIX ksh, Bourne sh and GNU bash do. So don't come for me when your script behaves differently over there. ๐
And fr fr: none of the pattern elements above match either a period ('.') at the start of a file name or a slash ('/'), even if you explicitly write them inside a[...]sequence. Also, the names"."and".."are never matched, even by the pattern".*". Periodt. โ
If the markdirs option is set, any directories that come out of file name generation get marked with a trailing '/'. Cute little bow on top. ๐
๐ธ Input/output redirection ๐ธ
When a command runs, its standard input, standard output and standard error (file descriptors 0, 1 and 2, respectively) are normally inherited straight from the shell. Three exceptions to that, and they are:
- commands in pipelines, where standard input and/or standard output are whatever the pipeline set up;
- asynchronous commands created when job control is disabled, where standard input is initially set to
/dev/null; - and commands where you've specified any of the redirections below, obviously. ๐
Here's the full menu, no cap:
>fileโ standard output gets redirected to file. If file doesn't exist, it gets created; if it does exist, is a regular file, and thenoclobberoption is set, you get an error; otherwise, the file is truncated. Note that this meanscmd <foo >foowill openfoofor reading and then truncate it when it opens it for writing โ all beforecmdgets a chance to actually readfoo. Yeah. That one bites everybody once. ๐ญ>|fileโ same as>, except the file gets truncated even if thenoclobberoption is set. It's the "I said what I said" version.>>fileโ same as>, except if file exists it's appended to instead of truncated. Also, the file is opened in append mode, so writes always go to the end of the file (seeopen(2)).<fileโ standard input gets redirected from file, which is opened for reading.<>fileโ same as<, except the file is opened for reading and writing. Both. At once. Main character energy. ๐<<markerโ okay so this is the here document one. 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 that 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", but not for'"'. If multiple here documents are used on the same command line, they're saved in order.
If no marker is given, the here document ends at the next << and substitution will be performed. If marker is only a set of either single '' or double "" quotes with nothing in between, the here document ends at the next empty line and substitution will not be performed.
<<-markerโ same as<<, except leading tabs are stripped from the lines in the here document. Great for keeping your script looking pretty. โจ<<<wordโ same as<<, except that word is the here document. This is called a here string. Obsessed.<&fdโ standard input is duplicated from file descriptor fd. And 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. Three flavours, all valid, pick your fighter. ๐ฆ>&fdโ same as<&, except the operation is done on standard output.&>fileโ same as>file 2>&1. This is a deprecated (legacy) GNU bash extension supported by mksh, which also supports the preceding explicit fd digit โ for example,3&>fileis the same as3>file 2>&3in mksh, but a syntax error in GNU bash. So like, use with intention, bestie.&>|file,&>>file,&>&fdโ same as>|file,>>fileor>&fd, followed by2>&1, as above. These are mksh extensions. Homegrown. ๐
In any of the redirections above, the file descriptor being 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. And 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 | pr -n -t
File descriptors created by I/O redirections are private to the shell. ๐คซ
โจ 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.
Warning: this also affects implicit conversion to integer, for example as done by the let command. Never use unchecked user input โ e.g. from the environment โ in an arithmetic context! I'm so serious. ๐
Expressions are calculated using signed arithmetic and the mksh_ari_t type (a 32-bit signed integer), unless they begin with a sole '#' character, in which case they use mksh_uari_t (a 32-bit unsigned integer).
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:
( )
Integer constants and expressions are calculated using an exactly 32-bit wide, signed or unsigned, type with silent wraparound on integer overflow. Integer constants may be specified with arbitrary bases using the notation base#number, where base is a decimal integer specifying the base (up to 36), and number is a number in the specified base. Additionally, base-16 integers may be specified by prefixing them with "0x" (case-insensitive) in all forms of arithmetic expressions โ except as numeric arguments to the test built-in utility. Prefixing numbers with a sole digit zero ("0") does not cause interpretation as octal (except in POSIX mode, as required by the standard), as that's unsafe to do.
As a special mksh extension, numbers to the base of one are treated as either (8-bit transparent) ASCII or Universal Coded Character Set codepoints, depending on the shell's utf8-mode flag (current setting). The AT&T UNIX ksh93 syntax of "'x'" instead of "1#x" is also supported. Note that NUL bytes (integral value of zero) cannot be used. An unset or empty parameter evaluates to 0 in integer context. If 'x' isn't comprised of exactly one valid character, the behaviour is undefined โ usually the shell aborts with a parse error, but rarely it succeeds, e.g. on the sequence C2 20; users of this feature (as opposed to read -a) must validate the input first. See โCAVEATSโ for UTF-8 mode handling. ๐ง
The operators are evaluated as follows:
- unary
+โ result is the argument (included for completeness). - unary
-โ negation. !โ logical NOT; the result is1if the argument is zero,0if not.~โ arithmetic (bit-wise) NOT.++โ increment; must be applied to a parameter (not a literal or other expression). The parameter is incremented by1. When used as a prefix operator, the result is the incremented value of the parameter; when used as a postfix operator, the result is the original value of the parameter.--โ similar to++, except the parameter is decremented by1.,โ separates two arithmetic expressions; the left-hand side is evaluated first, then the right. The result is the value of the expression on the right-hand side.=โ assignment; the variable on the left is set to the value on the right.+= -= *= /= %= <<= >>= ^<= ^>= &= ^= |=โ assignment operators.<var><op>=<expr>is the same as<var>=<var><op><expr>, with any operator precedence in<expr>preserved. For example,"var1 *= 5 + 3"is the same as specifying"var1 = var1 * (5 + 3)".||โ logical OR; the result is1if either argument is non-zero,0if not. The right argument is evaluated only if the left argument is zero.&&โ logical AND; the result is1if both arguments are non-zero,0if not. The right argument is evaluated only if the left argument is non-zero.|โ arithmetic (bit-wise) OR.^โ arithmetic (bit-wise) XOR (exclusive-OR). ๐ฅ&โ arithmetic (bit-wise) AND.==โ equal. You get1when both arguments are equal,0when they're not.!=โ not equal. You get0if both arguments are equal,1if they're not.<โ less than. Result is1if the left argument is less than the right,0if not.<=,>,>=โ less than or equal, greater than, greater than or equal. Same energy as<, bestie.<<,>>โ shift left (right). The result is the left argument with its bits shifted left (right) by however much the right argument says, either arithmetically (signed operation) or logically (unsigned expression).^<,^>โ rotate left (right). Basically a shift but make it fashion: the bits that get pushed out one end get pushed back in at the other end, instead of zero or sign bits. ๐ซ+,-,*,/โ addition, subtraction, multiplication and division. The classics.%โ remainder. This one is the symmetric remainder of dividing the left argument by the right. So if you want the actual mathematical modulus of โa mod bโ, you gotta use the formula โ(a % b + b) % bโ. Do not skip that step, I'm begging. ๐ฅฒ<arg1>?<arg2>:<arg3>โ if<arg1>is non-zero the result is<arg2>, otherwise the result is<arg3>. And the argument that doesn't win does not get evaluated. main character only, no wasted effort. ๐
๐ Co-processes ๐
Okay so a co-process โ which is a pipeline you create with the |& operator โ is an asynchronous process that your shell can both write to (with print -p) and read from (with read -p). You can also mess with the co-process's input and output using >&p and <&p redirections respectively. Slay.
Once a co-process has started, you can't start another one until the co-process exits, or until the co-process's input has been redirected with an exec n>&p redirection. And if the input has been redirected that way, the next co-process you start will share the output with the first co-process โ unless the output of the initial co-process got redirected with an exec n<&p redirection.
Some notes concerning co-processes:
- The only way to close a co-process's input (so that it reads an end-of-file) is to redirect the input to a numbered file descriptor and then close that file descriptor:
exec 3>&p; exec 3>&- - For co-processes to share a common output, the shell has to keep the write portion of the output pipe open. That means end-of-file won't be detected until all co-processes sharing that output have exited (once they all exit, the shell closes its own copy of the pipe). You can dodge this by redirecting the output to a numbered file descriptor (since that also makes the shell 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, rather than when all sharing co-processes exit.
print -pwill ignoreSIGPIPEsignals during writes if the signal isn't being trapped or ignored. Same thing applies if the co-process input has been duplicated to another file descriptor andprint -unis used.
๐ฆ Functions ๐ฆ
Functions get defined either with Korn shell function function-name syntax or the Bourne/POSIX shell function-name() syntax (peep below for the difference between the two forms, it matters). Functions are like .-scripts (meaning scripts sourced with the . built-in) in that they run in the current environment. But unlike .-scripts, shell arguments (so positional parameters $1, $2, etc.) are never visible inside them. When the shell is figuring out where a command lives, functions get searched after special built-in commands, and before builtins and the PATH get searched.
Got an existing function you wanna delete? unset -f function-name. Want the whole list? typeset +f. Want the actual definitions? typeset -f. And the autoload command (which is an alias for typeset -fu) lets you create undefined functions: when an undefined function runs, the shell searches the path given in the FPATH parameter for a file with the same name as the function, and if it finds one, reads and executes it. If after executing that file the named function turns out to be defined, the function runs; if not, the normal command search keeps going (so the shell searches the regular built-in command table and PATH). Also โ if a command isn't found using PATH, an attempt is made to autoload a function using FPATH. That's an undocumented feature of the original Korn shell, iykyk. ๐
Functions can carry two attributes, โtraceโ and โexportโ, set with typeset -ft and typeset -fx respectively. When a traced function runs, the shell's xtrace option gets turned on for the function's duration. The โexportโ attribute of functions is currently not used.
Since functions execute in the current shell environment, parameter assignments made inside functions are visible after the function finishes. If that's not the vibe you want, use the typeset command inside a function to make a local parameter. Note that AT&T UNIX ksh93 uses static scoping (one global scope, one local scope per function) and only allows local variables on Korn style functions, whereas mksh uses dynamic scoping (nested scopes of varying locality). Also note that special parameters (like $$, $!) can't be scoped this way.
A function's exit status is the exit status of the last command executed inside it. You can make a function finish immediately with the return command, which you can also use to explicitly set the exit status. Careful though: when called in a subshell, return only exits that subshell and will not make the original shell exit a running function (see the while...read loop FAQ). ๐
Functions defined with the function reserved word are treated differently from functions defined with the () notation in the following ways:
- The
$0parameter is set to the name of the function (Bourne-style functions leave$0untouched). OPTINDis saved/reset and restored on entry and exit from the function, sogetoptscan be used properly both inside and outside the function (Bourne-style functions leaveOPTINDuntouched, so usinggetoptsinside a function interferes with usinggetoptsoutside the function).- Shell options (
set -o) have local scope, i.e. changes made inside a function get reset when it exits.
In the future, the following differences may also be added:
- A separate trap/signal environment will be used while functions execute. That means traps set inside a function won't affect the shell's traps, and signals that aren't ignored in the shell (but may be trapped) will have their default effect inside a function.
- The
EXITtrap, if set inside a function, will be executed after the function returns.
๐ Command execution ๐
After command-line arguments, redirections and parameter assignments have all been evaluated, the type of command gets determined: a special built-in command, a function, a normal builtin, or the name of a file to execute found using the PATH parameter. The checks happen in that order, bestie.
Special built-in commands differ from other commands because the PATH parameter isn't used to find them, an error during their execution can make a non-interactive shell exit, and parameter assignments specified before the command are kept after the command completes. Regular built-in commands only differ in that the PATH parameter isn't used to find them.
POSIX special built-in utilities:
., :, break, continue, eval, exec, exit, export, readonly, return, set,
shift, times, trap, unset
Additional mksh commands keeping assignments:
source, typeset
All other builtins are not special; these are at least:
[, alias, bg, bind, builtin, cat, cd, command, echo, false, fc, fg,
getopts, jobs, kill, let, print, pwd, read, realpath, rename, sleep,
suspend, test, true, ulimit, umask, unalias, wait, whence
Once the type of command has been determined, any command-line parameter assignments are performed and exported for the duration of that command.
The following describes the special and regular built-in commands and builtin-like reserved words, plus some optional utilities:
. file [arg ...]
(keeps assignments, special) This one is called the โdotโ command. It executes 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.
: [...]
(keeps assignments, special) The null command. Exit status gets set to zero. Truly the do-nothing icon. โจ
Lb64decode [string]
(dot.mkshrc function) Decodes string or standard input to binary.
Lb64encode [string]
(dot.mkshrc function) Encodes string or standard input as base64.
Lbafh_init
Lbafh_add [string]
Lbafh_finish
(dot.mkshrc functions) Implements the Better Avalance for the Jenkins Hash. This is the same hash mksh currently uses internally. After calling Lbafh_init, call Lbafh_add multiple times until all input is read, then call Lbafh_finish, which writes the result to the unsigned integer Lbafh_v variable for your consumption. ๐
Lstripcom [file ...]
(dot.mkshrc function) Same as cat, except it strips any empty lines and comments (from any โ#โ character onwards, no escapes) and reduces any amount of whitespace to one space character.
[ expression ]
(regular) See test.
alias [-d | -t [-r] | -+x] [-p] [+] [name [=value] ...]
(regular) Without arguments, alias lists all aliases. For any name without a value, the existing alias gets listed. Any name with a value defines an alias; see โAliasesโ above. [][A-Za-z0-9_!%+,.@:-] are valid in names, except they may not begin with a plus or hyphen-minus, and [[ is not a valid alias name.
When listing aliases, one of two formats is used. Normally, aliases are listed as name=value, where value is quoted as necessary. If options were preceded with โ+โ, or a lone โ+โ is given on the command line, only name is printed.
-dโ lists or sets directory aliases (the ones that get used in tilde expansion, see "Tilde expansion" up above bestie ๐ ).-pโ every alias gets printed with the stringaliasglued onto the front of it. cute, formatted, ready to read.-tโ says we're listing/setting tracked aliases (and heads up: any values you pass along with the command are just ignored for tracked aliases, they don't care ๐).-rโ resets all the tracked aliases. fresh start energy โจ.-xโ sets the export attribute on an alias (+xclears it), or if you don't name any names it just lists all the aliases that have the export attribute set. and fr fr, exporting an alias has no effect โ that's just how it is, no cap.
๐ธ autoload
(built-in alias) โ go read "Functions" above, it's all there bestie ๐ซถ
๐ธ bg [job ...]
(regular, needs job control) โ resumes the stopped job(s) you point at, in the background ๐คโก๏ธ๐ฅ. If you don't specify any jobs, %+ is assumed. More deets in "Job control" below, iykyk.
๐ธ bind -l
(regular) โ lists the names of all the editing commands that strings can be bound to. See "Emacs editing mode" for the full lore ๐
๐ธ bind [string ...]
Lists the current bindings โ for string if you gave one, otherwise all of them. Note bestie: default prefix bindings are assumed, and those are 1=Esc, 2=^X, 3=NUL ๐
.
๐ธ bind string=[editing-command] [...]
๐ธ bind -m string=substitute [...]
So the vibe here: to string โ which should be a control character, optionally preceded by one of the three prefix characters and optionally followed by a tilde character โ the editing-command gets bound, so that future input of that string will immediately invoke that editing command โก. If there's a tilde postfix, then a tilde trailing the control character is just ignored. And if you pass -m (macro mode, bestie), future input of the string gets replaced by the given NUL-terminated substitute string โ and inside that substitute, prefix/control/tilde characters that map to editing commands will be processed (but ones mapped to other macros will not be, ok? not the same thing ๐
).
Prefix and control characters can be written using caret notation, so like ^Z means Ctrl-Z. Use a backslash to escape the caret, an equals sign, or another backslash. And note: even though only three prefix characters are supported (usually Esc, ^X and NUL), some multi-character sequences can still be supported. iconic behavior honestly.
๐ธ break [level]
(keeps assignments, special) โ exits the levelth inner-most for, select, until or while loop ๐ช๐จ. level defaults to 1.
๐ธ builtin [--] command [arg ...]
(regular) โ executes the built-in command command. periodt.
๐ธ \builtin command [arg ...]
(regular, decl-forwarder) โ same as builtin, but it also acts as a declaration utility forwarder, meaning this counts as a declaration utility (see "Tilde expansion") iff command is a declaration utility. conditional queen ๐.
๐ธ cat [-u] [file ...]
(defer with flags) โ copies files to standard output in command line order. If a file is a single dash (-) or is absent, read from standard input. For direct builtin calls, the POSIX -u option is supported as a no-op ๐ซ . For calls from the shell, if any options are given at all, an external cat(1) utility is preferred over the builtin. she's picky, we respect it.
๐ธ cd [-L] [dir]
๐ธ cd -P [-e] [dir]
๐ธ chdir [-eLP] [dir]
(regular) โ sets the working directory to dir. If the parameter CDPATH is set, it lists the search path for the directory containing dir. An unset or empty path means the current directory. If dir is found in any component of the CDPATH search path other than an unset or empty path, the name of the new working directory gets written to standard output โจ. If dir is missing, the home directory HOME is used. And if dir is -, we go back to the previous working directory (see the OLDPWD parameter, she remembers everything ๐).
If the -L option (logical path) is used, or if the physical option isn't set (peep the set command below), then references to .. in dir are relative to the path used to get to the directory. If -P (physical path) is used, or if the physical option is set, .. is relative to the filesystem directory tree. The PWD and OLDPWD parameters get updated to reflect the current and old working directory respectively. And if -e is set for physical filesystem traversal and PWD could not be set, the exit code is 1; greater than 1 if an error occurred, 0 otherwise. numbers, bestie, they matter ๐.
๐ธ cd [-eLP] old new
๐ธ chdir [-eLP] old new
(regular) โ the string new gets substituted for old in the current directory, and the shell attempts to change to the new directory. swap szn ๐.
๐ธ cls
(dot.mkshrc alias) โ reinitialises the display (a hard reset). clean slate, fresh screen, main character re-enters the room ๐ โจ
๐ธ command [-pVv] cmd [arg ...]
(regular, decl-forwarder) โ if neither -v nor -V is given, cmd is executed exactly as if command had never been specified, with two exceptions: first, cmd cannot be a shell function; and second, special built-in commands lose their specialness (meaning redirection and utility errors do not cause the shell to exit, and command assignments are not permanent). okay so it's like cmd but the training wheels are off ๐ด.
If -p is given, a default search path is used instead of the current PATH โ and the actual value of that default path is system-dependent, so don't @ me.
If -v is given, then instead of executing cmd, you just get info about what would be executed, for each argument ๐. For builtins, functions and keywords, their names are simply printed; for aliases, a command that defines them is printed; for utilities 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 -v but more verbose โ she over-shares, and we love her for it.
๐ธ continue [level]
(keeps assignments, special) โ jumps to the beginning of the levelth inner-most for, select, until or while loop. level defaults to 1. back to the top, no looking back ๐.
๐ธ dirs [-lnv]
(dot.mkshrc function) โ prints the directory stack ๐. -l makes tilde expansion happen in the output. -n causes line wrapping before 80 columns, whereas -v causes numbered vertical output. pick your format bestie.
๐ธ doch
(dot.mkshrc alias) โ executes the last command with sudo(8) ๐ฅ๐
๐ธ echo [-Een] [arg ...]
(regular) โ warning bestie: this utility is not portable; use the standard Korn shell built-in utility print in new code instead. consider this your sign ๐
Prints arguments, separated by spaces, followed by a newline, to standard output. The newline is suppressed if any of the arguments contain the backslash sequence \c. See the print command below for a list of other backslash sequences that get recognised.
The options exist for compatibility with BSD shell scripts. -E suppresses backslash interpretation, -e enables it (normally the default), -n suppresses the trailing newline, and anything else causes the word to be printed as an argument instead. chaotic but valid.
If the posix or sh option is set, or this is a direct builtin call, or print -R, then only the first argument is treated as an option โ and only if it is exactly -n. Backslash interpretation is disabled. strict mode activated ๐จ.
๐ธ enable [-anps] [name ...]
(dot.mkshrc function) โ hides and unhides built-in utilities, aliases and functions, plus the ones defined in dot.mkshrc ๐ซฃโจ.
If no name is given, or if -p is used, builtins are printed (behind the string enable , followed by -n if the builtin is currently disabled). Otherwise they're disabled (if -n is given) or re-enabled.
When printing, only enabled builtins are printed by default; -a prints all builtins, while -n prints only disabled builtins instead; -s limits the list to POSIX special builtins. so many filters, so little time ๐
.
๐ธ eval command ...
(keeps assignments, special) โ the arguments get concatenated, with a space between each, to form a single string which the shell then parses and executes in the current execution environment. one string to rule them all ๐ช.
๐ธ exec [-a argv0] [-c] [command [arg ...]]
(keeps assignments, special) โ the command (with arguments) is executed without forking, fully replacing the shell process. and this is absolute, bestie: exec never returns, even if the command isn't found ๐ญ. The -a option lets you set a different argv[0] value, and -c clears the environment before executing the child process โ except for the _ parameter and direct assignments.
If no command is given except for I/O redirection, the I/O redirection is permanent and the shell is not replaced. Any file descriptors greater than 2 which are opened or dup(2)'d in this way are not made available to other executed commands (i.e. commands that aren't built-in to the shell). And note that the Bourne shell differs here โ it does pass these file descriptors on. different era, different rules โณ.
๐ธ exit [status]
(keeps assignments, special) โ the shell or subshell exits with the specified errorlevel (or the current value of the $? parameter). bye bestie ๐๐
๐ธ export [-p] [parameter[=value]]
(keeps assignments, special, decl-util) โ sets the export attribute of the named parameters. Exported parameters get passed in the environment to executed commands ๐. If values are specified, the named parameters are also assigned. And yes, this is a declaration utility.
If no parameters are specified, all parameters with the export attribute set are printed one per line: either their names, or โ if a - with no option letter is specified โ name=value pairs, or, with the -p option, export commands suitable for re-entry. so many output modes, she contains multitudes โจ.
๐ธ extproc
(OS/2) โ a null command required for shebang-like functionality. does nothing, but does it iconically ๐.
๐ธ false
(regular) โ a command that exits with a non-zero status. she's the hater of the command world and honestly? necessary ๐.
๐ธ fc [-e editor | -l [-n]] [-r] [first [last]]
(regular) โ first and last select commands from the history ๐. Commands can be selected by history number (negative numbers go backwards from the current, most recent, line) or by a string specifying the most recent command starting with that string. The -l option lists the command on standard output, and -n inhibits the default command numbers. The -r option reverses the order of the list. Without -l, the selected commands are edited by the editor specified with the -e option or, if no -e is specified, the editor specified by the FCEDIT parameter (and if that parameter isn't set, /bin/ed is used), and the result is executed by the shell. time travel but for your command line ๐ฐ๏ธ๐
.
๐ fc -e - / -s
fc -e - | -s [-g] [old=new] [prefix]
(regular) โ bestie this one re-runs the command you picked (and yeah, the default pick is just your previous command ๐ซถ), but only after it does the optional swap of old with new. Throw in -g and every single occurrence of old gets replaced with new, not just the first one. And like, plot twist: -e - and -s mean the exact same thing โ re-execute the selected command, no editor invited to the party ๐
. You'll usually get at this one through the predefined:
alias r='fc -e -'
๐ธ fg
fg [job ...]
(regular, needs job control) โ brings the job(s) you name back to the foreground so you can actually interact with them again ๐ฆ. Don't name any jobs? Then %+ is assumed, no cap. Peep โJob controlโ below for the whole scoop.
โจ functions
functions [name ...]
(built-in alias) โ shows you the function definition commands for the functions you list โ or for every function that's currently defined if you list none. It's giving "show me your receipts" ๐ .
๐ getopts
getopts optstring name [arg ...]
(regular) โ the classic move shell procedures use to parse the arguments you handed them (or the positional parameters, if you gave it no arguments at all) and vibe-check whether the options are legal. Options that don't take arguments can be grouped together in one single argument ๐ซถ. If an option does take an argument and the option character isn't the last character of the word it's chillin' in, then the rest of that word becomes the option's argument. Otherwise? The next word is the argument. Simple as.
optstring holds the option letters you wanna recognise. If a letter is followed by a colon, that option takes an argument โ colon = commitment.
Every time getopts gets invoked, it drops the next option into the shell parameter name. If that option was introduced with a +, the character placed in name gets a + prefix slapped on it. And if the option takes an argument, that argument goes into the shell parameter OPTARG ๐.
Now for the messy part ๐ญ โ when you hit an illegal option or a missing option argument, a question mark or a colon gets placed in name (question mark = illegal option, colon = missing argument, respectively) and OPTARG is set to the option letter that caused the whole situation. And furthermore, unless optstring begins with a colon, a question mark is placed in name, OPTARG gets unset, and a diagnostic gets shown on standard error. Yeah. It's a lot. iykyk.
getopts records the index of the argument that the next call should process in OPTIND. When the end of the options rolls around, getopts returns a non-zero exit status. Options end at the first argument that doesn't start with a - (that's a non-option argument, bestie) or when a -- argument shows up ๐
Option parsing can be reset by setting OPTIND to 1 โ and yes, this happens automatically whenever the shell or a shell procedure is invoked โจ.
โ ๏ธ Warning: Changing the value of the shell parameterOPTINDto anything other than1, or parsing different sets of arguments without resettingOPTIND, may lead to unexpected results. Not me warning you twice ๐
๐ฆ hash
hash [-r] [name ...]
(built-in alias) โ with no arguments, it lists out any hashed executable command paths you've got sitting around. The -r option makes all hashed commands get removed from the cache โ clean slate energy โจ. Each name gets searched as if it were a command name, and gets added to the cache if it turns out to be an executable command.
๐ hd
hd [file ...]
(dot.mkshrc alias or function) โ hexdumps stdin or the arguments, legibly ๐. That's it. That's the whole vibe.
๐ history
history [-nr] [first [last]]
(built-in alias) โ literally the same as fc -l (peep above โฌ๏ธ). Same thing, different name, iconic behavior.
๐
integer
integer [flags] [name [=value] ...]
(built-in alias) โ same as typeset -i (scroll down for that one โฌ๏ธ). We love a shortcut.
โญ jobs
jobs [-lnp] [job ...]
(regular) โ displays info about the job(s) you specify; specify none and it shows you all of them ๐ซถ.
-nโ only shows info for jobs that have changed state since the last notification. No repeats, we hate a rerun.-lโ also lists the process ID of each process in a job.-pโ prints only the process group of each job. Nothing else, just that.
Peep โJob controlโ below for the format of job and what the displayed job actually looks like โจ.
๐ฅ kill
kill [-s signame | -signum | -signame] { job | pid | pgrp } ...
(regular) โ sends the signal you specify to the jobs, process IDs or process groups you point at ๐. Don't specify a signal? Then TERM gets sent, that's the default. And if you name a job, the signal goes to the job's process group. See โJob controlโ below for the format of job.
๐ kill -l
kill -l [exit-status ...]
(regular) โ prints the signal name that corresponds to exit-status. Give it no arguments and it prints a list of all the signals, complete with their numbers and a short description of each one ๐. Chef's kiss reference material.
๐ let
let [expression ...]
(regular) โ each expression gets evaluated (see โArithmetic expressionsโ above โจ). If every expression evaluates successfully, the exit status is 0 (1) if the last expression evaluated to non-zero (zero) โ yeah, read that again, it's the reverse of what your brain wants ๐ซ . If an error happens while parsing or evaluating an expression, the exit status is greater than 1.
And because expressions may need quoting, (( expr )) is syntactic sugar for:
{ \\builtin let 'expr'; }
๐ local
local [flags] [name [=value] ...]
(built-in alias) โ same as typeset (see below โฌ๏ธ). Local girlies rise ๐ซถ
๐ง mknod
mknod [-m mode] name b|c major minor
mknod [-m mode] name p
(optional) โ creates a device special file ๐
. The file type can be one of b (block type device), c (character type device) or p (named pipe, FIFO). The file that gets created may be modified according to its mode (via the -m option), major (major device number), and minor (minor device number).
Heads up bestie: this is not normally part of mksh; however, distributors may have added this as a builtin as a speed hack. So don't come for the shell if it's not there ๐ญ
๐ธ nameref
nameref [flags] [name [=value] ...]
(built-in alias) โ same as typeset -n (see below โฌ๏ธ). Referencing, but make it a name.
๐ popd
popd [-lnv] [+n]
(dot.mkshrc function) โ pops the directory stack and returns you to the new top directory โจ. The flags work exactly like in dirs (see above โฌ๏ธ). And a numeric argument +n selects which entry in the stack to discard ๐
๐ฆ print
print [-AcelNnprsu[n] | -R [-n]] [argument ...]
(regular) โ prints the argument(s) you hand it on the standard output, separated by spaces, and terminated with a newline ๐ซถ. The escapes mentioned in โBackslash expansionโ above get interpreted, and so does \c, which is equivalent to using the -n option.
The options are as follows, bestie:
-Aโ each argument gets arithmetically evaluated; the character corresponding to the resulting value is what actually gets printed. Empty arguments separate input words ๐ .-cโ the output gets printed columnised, line by line, similar to how thers(1)utility, tab completion, thekill -lbuilt-in utility and theselectstatement do it โจ.-eโ restores backslash expansion after a previous-r. Undo button ๐ซถ-lโ changes the output word separator to newline.-Nโ changes the output word and line separator to ASCII NUL.-nโ does not print the trailing line separator. Bye newline ๐-pโ prints to the co-process (see โCo-processesโ above โฌ๏ธ).-rโ inhibits backslash expansion. No escaping today ๐-sโ prints to the history file instead of standard output.-u[n]โ prints to the file descriptorn(defaults to1if you omit it) instead of standard output.
And the -R option? It mostly emulates the BSD echo(1) command โ which does not expand backslashes, and only interprets its first argument as an option if it is exactly -n (to suppress the trailing newline). Exactly. Character for character. No wiggle room ๐
๐ printf
printf format [arguments ...]
(optional, defer always) โ if it's compiled in, it formats and prints the arguments, supporting the bare POSIX-mandated minimum โจ. And if an external utility of the same name is found, it gets deferred to โ unless you run it as a direct builtin call or from the builtin utility. iykyk ๐ซถ
๐ pushd
pushd [-lnv]
(dot.mkshrc function) โ rotates the top two elements of the directory stack ๐. The options are the same as for dirs (see above โฌ๏ธ), and pushd changes to the topmost directory stack entry after it's done acting.
pushd [-lnv] +n
(dot.mkshrc function) โ rotates the element number n to the top ๐
pushd [-lnv] name
(dot.mkshrc function) โ pushes name on top of the stack ๐.
๐
pwd
pwd [-LP]
(regular) โ prints the present working directory โจ. Give it no options and pwd behaves as if the -P option (print physical path) was used if the physical shell option is set โ and as if the -L option (print logical path) was used otherwise.
So what's the difference, bestie? The logical path is the path you actually used to cd into the current directory. The physical path is determined from the filesystem โ by following .. directories all the way up to the root directory ๐ณ. No shortcuts, no lies.
โญ r
r [-g] [old=new] [prefix]
(built-in alias) โ same as fc -e - (see above โฌ๏ธ). Short name, big power ๐
๐ซถ read
read [-A | -a] [-d x] [-N z | -n z] [-p | -u[n]] [-t n] [-rs] [p ...]
(regular) โ reads a line of input, splits the input into fields using the IFS parameter (see โSubstitutionโ above โจ) or other specified means, and assigns each field to the specified parameters p ๐. Name no parameters and the REPLY parameter is used to store the result instead.
Got more parameters than fields? The extra parameters get set to the empty string or 0. Got more fields than parameters? Then the last parameter gets assigned all the remaining fields โ word separators included ๐.
The options are as follows:
-Aโ stores the result into the parameterp(orREPLY) as an array of words. Only no parameter or one parameter is accepted.-aโ stores the result, without applyingIFSword splitting, into the parameterp(orREPLY) as an array of characters โ wide characters if theutf8-modeoption is enacted, octets otherwise ๐ฆ. The codepoints get encoded as decimal numbers by default. Only no parameter or one parameter is accepted.-d xโ uses the first byte ofxโ andNULifxis empty โ instead of the ASCII newline character to delimit input lines. Custom delimiters, we love to see it โจ-N zโ instead of reading till end-of-line, reads exactlyzbytes ๐. Upon EOF, a partial read is returned with exit status1. After a timeout, a partial read is returned with an exit status as ifSIGALRMwere caught.-n zโ instead of reading till end-of-line, reads up tozbytes but returns as soon as any bytes are read โ like, from a slow terminal device, or if EOF or a timeout occurs ๐ซถ-pโ reads from the currently active co-process instead of from a file descriptor (peep the โCo-processesโ bit up above for the deets). ๐-u[n]โ reads from the file descriptor number n (defaults to0, i.e. standard input). โ ๏ธ the argument has to come immediately after the option character โ no space, no gap, periodt.-t nโ interrupts the read after n seconds (specified as a positive decimal value with an optional fractional part). If the timeout actually happened, the exit status ofreadis the same as ifSIGALRMwere caught โ but lowkey, partial reads may still be returned. ๐ญ-rโ normallyreadstrips backslash-newline sequences and any remaining backslashes from input. This option turns on raw mode, where backslashes are retained and ignored. โจ-sโ the input line is saved to the history. ๐
If the input is a terminal, both the -N and -n options set it into raw mode; they read an entire file if -1 is passed as z argument.
The first parameter may have a question mark and a string appended to it, in which case that string is used as a prompt โ printed to standard error before any input is read โ if the input is a tty(4). Like, for example: read nfoo?'number of foos: ' ๐
If no input is read or a timeout occurred, read exits with a non-zero status.
readonly ๐ซโ๏ธ
readonly [-p] [parameter [=value] ...]
(keeps assignments, special, decl-util) Sets the read-only attribute of the named parameters. If values are given, parameters are assigned these before disallowing writes. Once a parameter is made read-only, it cannot be unset and its value cannot be changed. No take-backs, bestie. ๐
If no parameters are specified, the names of all parameters with the read-only attribute are printed one per line โ unless the -p option is used, in which case readonly commands defining all read-only parameters, including their values, are printed. ๐
realpath ๐ฃ๏ธ
realpath [--] name
(defer with flags) Resolves an absolute pathname corresponding to name. If the resolved pathname either exists or can be created immediately, realpath returns 0 and prints the resolved pathname. Otherwise, or if an error occurs, it issues a diagnostic and returns nonzero. And if name ends with a slash (/), resolving to an extant non-directory is also treated as error. ๐
rename ๐ท๏ธ
rename [--] from to
(defer always) Renames the file from to to. Both must be complete pathnames and on the same device. Intended for emergency situations (like, when /bin/mv becomes unusable); directly calls rename(2). ๐จ
return โฉ๏ธ
return [status]
(keeps assignments, special) Returns from a function or . script with errorlevel status. If no status is given, the exit status of the last executed command is used. If used outside of a function or . script, it has the same effect as exit. ๐ Note that mksh treats both profile and ENV files as . scripts, while the original Korn shell only treated profiles as . scripts. iykyk.
rot13 ๐
(dot.mkshrc alias) ROT13-encrypts/-decrypts stdin to stdout. It's giving secret agent era. ๐ต๏ธโโ๏ธ
set โจ
set [-+abCefhiklmnprsUuvXx] [-+o option] [-+A name] [--] [arg ...]
(keeps assignments, special) The set command can be used to show all shell parameters (like typeset -), set (-) or clear (+) shell options, set an array parameter or the positional parameters. It does it all, honestly. ๐
Options can be changed using the -+o option syntax, where option is the long name of an option, or using the -+letter syntax, where letter is the option's single letter name (not all options have a single letter name, so don't come for me). The list below gives short names (if extant) and long names along with a description of what each option 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. If name ends with a +, the array is appended to instead. ๐ธ
An alternative syntax for the command set -A foo -- a b c; set -A foo+ -- d e โ which is compatible to GNU bash and also supported by AT&T UNIX ksh93 โ is:
foo=(a b c); foo+=(d e)
-a|-o allexportโ All new parameters are created with the export attribute.-b|-o notifyโ Print job notification messages asynchronously instead of just before the prompt. Only used with job control (-m).-C|-o noclobberโ Prevent>redirection from overwriting existing files. Instead,>|must be used to force an overwrite.
โ ๏ธ Note: This is not safe to use for creation of temporary files or lockfiles due to a TOCTOU in a check allowing one to redirect output to /dev/null or other device files even in noclobber mode. Don't do it, bestie. ๐
-e|-o errexitโ Exit (after executing theERRtrap) 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,untilorwhilestatements. For&&,||and pipelines (but mind-o pipefail), only the status of the last command is tested. ๐-f|-o noglobโ Do not expand file name patterns.-h|-o trackallโ Create tracked aliases for all executed commands (see โAliasesโ above). Enabled by default for non-interactive shells.-i|-o interactiveโ The shell is an interactive shell. This option can only be used when the shell is invoked. See above for details. ๐-k|-o keywordโ Parameter assignments are recognised anywhere in a command.-l|-o loginโ The shell is a login shell. This option can only be used when the shell is invoked. See above for what this means.-m|-o monitorโ Enable job control (default for interactive shells).-n|-o noexecโ Do not execute any commands. Useful for checking the syntax of scripts. Ignored if reading commands from atty. ๐ง-p|-o 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.
If the shell is privileged, setting this flag after startup files have been processed let it go full setuid and/or setgid. Clearing this flag makes the shell drop privileges. Changing this flag resets the groups vector. ๐ฅ
-r|-o restrictedโ The shell is a restricted shell. This option can only be used when the shell is invoked. See above for what this means.-s|-o 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 ASCIIbetically before assigning them to the positional parameters (or to array name, with -A). ๐ค
-U|-o utf8-modeโ Enable UTF-8 support in the โEmacs editing modeโ and internal string handling functions. This flag is disabled by default, but can be enabled by setting it on the shell command line; is enabled automatically for interactive shells if requested at compile time, your system supportssetlocale(LC_CTYPE, "")and optionallynl_langinfo(CODESET), or theLC_ALL,LC_CTYPEorLANGenvironment variables, and at least one of these returns something that matches โUTF-8โ or โutf8โ case-insensitively; for direct builtin calls depending on the aforementioned environment variables; or for stdin or scripts, if the input begins with a UTF-8 Byte Order Mark. ๐
In near future, locale tracking will be implemented, which means that set -+U is changed whenever one of the POSIX locale-related environment variables changes.
-u|-o nounsetโ Referencing of an unset parameter, other than"$@"or"$*", is treated as an error, unless one of the'-','+'or'='modifiers is used.-v|-o verboseโ Write shell input to standard error as it is read.-X|-o markdirsโ Mark directories with a trailing/during globbing.-x|-o xtraceโ Print commands when they are executed, preceded byPS4. ๐-o bgniceโ Background jobs are run with lower priority. ๐ด-o braceexpandโ Enable brace expansion. This is enabled by default.-o emacsโ Enable BRL emacs-like command-line editing (interactive shells only); see โEmacs editing modeโ. Enabled by default. ๐-o gmacsโ Enable gmacs-like command-line editing (interactive shells only). Currently identical to emacs editing except thattranspose-chars(^T) acts slightly differently.-o ignoreeofโ The shell will not (easily) exit when end-of-file is read;exitmust be used. To avoid infinite loops, the shell will exit if EOF is read 13 times in a row. ๐ค-o inherit-xtraceโ Do not reset-o xtraceupon entering functions (default).-o nohupโ Do not kill running jobs with aSIGHUPsignal when a login shell exits. Currently set by default, but this may change in the future to be compatible with AT&T UNIX ksh, which doesn't have this option, but does send theSIGHUPsignal.-o nologโ No effect. In the original Korn shell, this prevented function definitions from being stored in the history file. ๐ซ-o physicalโ makescdandpwduse โphysicalโ (aka the actual filesystem's)..directories instead of โlogicalโ ones (where the shell itself handles.., so you can live your best life blissfully unaware of symlinks pointing at directories). Clear by default. Heads up bestie: turning this on does not touch the current value of thePWDparameter โ only thecdcommand changesPWD. Scroll up tocdandpwdfor the full tea. โ-o pipefailโ makes the exit status of a pipeline the rightmost non-zero errorlevel, or zero if literally every command exited with zero. Periodt.-o posixโ behave closer to the standards (peep โPOSIX modeโ for the deets). Gets auto-enabled if the shell invocation basename, after the-andrprocessing, starts withshโ and (often used for thelkshbinary) this autodetection feature is compiled in. Side effect era: setting this flag turns off thebraceexpandandutf8-modeflags (you can flip them back on manually) and alsoshmode โ unless both are set in the same command. ๐-o shโ enables kludge/bin/shcompatibility mode (see โSH modeโ below, iykyk). Auto-enabled if the basename of the shell invocation, after-andrprocessing, begins withshand this autodetection feature is compiled in (which is pretty uncommon, ngl). Side effect: setting this flag turns off thebraceexpandflag (turn it back on manually if you want) andposixmode โ unless both are set in the same command.-o viโ enablesvi(1)-style command-line editing (interactive shells only). โVi editing modeโ has the documentation and the limitations, go look. ๐-o vi-esccompleteโ in vi command-line editing, do command and file name completion when Esc (^[) is entered in command mode.-o vi-tabcompleteโ in vi command-line editing, do command and file name completion when Tab (^I) is entered in insert mode. (this one's the default โจ)-o virawโ literally no effect. In the original Korn shell, unlessvirawwas set, the vi command-line mode would let thetty(4)driver do the work until Esc was entered. mksh is always in viraw mode, so bestie, it's giving nothing. ๐
These options can also be used upon invocation of the shell, so you can set the vibe before you even land. The current set of options (with single letter names) lives in the parameter $-. Run set -o with no option name and it lists all the options and whether each one is on or off; set +o prints a command to restore the current option set, using the internal set -o .reset construct โ which is an implementation detail, so don't @ it. Both of these commands are transient (only valid within the current shell session).
Remaining arguments, if any, are positional parameters and get assigned, in order, to the positional parameters (i.e. $1, $2, etc.). If options end with -- and there are no remaining arguments, all positional parameters are cleared. And for unknown historical reasons (the ancestors were wilding), a lone - option is treated specially โ it clears both the -v and -x options. If no options or arguments are given, the values of all parameters are printed (suitably quoted). ๐ซถ
โจ setenv [name [value]] โจ
(dot.mkshrc function) With no arguments, display the names and values of all exported parameters. Otherwise, set name's export attribute, and set its value to value (empty string if none given). Simple as. ๐ธ
โจ shift [number] โจ
(keeps assignments, special) The positional parameters number+1, number+2, etc. (number defaults to 1) are renamed to 1, 2, etc. Sliding them on over. ๐ฆ
โจ sleep seconds โจ
(regular, needs select(2)) Suspends execution for a minimum of seconds (specified as a positive decimal value with an optional fractional part). Signal delivery may continue execution earlier, so don't be shocked if it wakes up early. ๐ด
โจ smores [file ...] โจ
(dot.mkshrc function) Simple pager: <Enter> next; โqโ+<Enter> quit. Iconic name, honestly. ๐
โจ source file [arg ...] โจ
(keeps assignments) Like . (โdotโ), except that the current working directory is appended to the search path. (GNU bash extension, bestie ๐)
โจ suspend โจ
(needs job control and getsid(2)) Stops the shell as if it had received the suspend character from the terminal.
It is not possible to 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 ] โจ
(regular) test evaluates the expression and exits with status code 0 if true, 1 if false, or greater than 1 if there was an error. It's the go-to condition command for if and while statements. All file expressions, except -h and -L, follow symbolic links.
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 context dependent directory (only useful on HP-UX).-h fileโ file is a symbolic link.-k fileโ file's mode has thesticky(7)bit set.-L fileโ file is a symbolic link.-O fileโ file's owner is the shell's effective user ID.-p fileโ file is a named pipe (FIFO).-r fileโ file exists and is readable.-S fileโ file is aunix(4)-domain socket.-s fileโ file is not empty.-t fdโ File descriptor fd is atty(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.-v nameโ The shell parameter name is set.-o optionโ Shell option is set (see thesetcommand 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 optionfooexists). The same can be achieved with[ -o ?foo ]like in AT&T UNIX ksh93. option can also be the short flag prefixed with either โ-โ or โ+โ (no logical negation), for example โ-xโ or โ+xโ instead of โxtraceโ.string = stringโ Strings are equal. In double brackets, pattern matching (R59+ using extglobs) occurs if the right-hand string isn't quoted.string == stringโ Same as โ=โ (deprecated, we don't do that anymore bestie ๐).string != stringโ Strings are not equal. See โ=โ regarding pattern matching.string > stringโ First string operand is greater than second string operand.string < stringโ First string operand is less than second string operand.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.
Note that a number actually may be an arithmetic expression, such as a mathematical term or the name of an integer variable:
x=1; [ "x" -eq 1 ] evaluates to true
Note that some special rules are applied (courtesy of POSIX) if the number of arguments to test or inside the brackets [ ... ] is less than five: if leading โ!โ arguments can be stripped such that only one to three arguments remain, then the lowered comparison is executed; (thanks to XSI) parentheses \( ... \) lower four- and three-argument forms to two- and one-argument forms, respectively; three-argument forms ultimately prefer binary operations, followed by negation and parenthesis lowering; two- and four-argument forms prefer negation followed by parenthesis; the one-argument form always implies -n. To assume this is not necessarily portable. โ ๏ธ
Note: A common mistake is to use โif [ $foo = bar ]โ which fails if parameter โfooโ is empty or unset, if it has embedded spaces (i.e.IFSoctets) or if it is a unary operator like โ!โ or โ-nโ. Use tests like โif [ x"$foo" = x"bar" ]โ instead, or the double-bracket operator (see[[above): โif [[ $foo = bar ]]โ or, to avoid pattern matching, โif [[ $foo = "$bar" ]]โ; the[[ ... ]]construct is not only more secure to use but also often faster. ๐
โฑ๏ธ time โ reserved word
time [-p] [pipeline]
Bestie, heads up: time is a reserved word, so the shell parses it special. If you hand it a pipeline, it reports the times it took to execute that pipeline. If you give it nothing at all? Then it reports the user and system time used by the shell itself, plus every command it's run since it started. Iconic behavior honestly.
The times it reports are:
- real time โ elapsed time from start to finish, the wall-clock vibe
- user CPU time โ time spent running in user mode
- system CPU time โ time spent running in kernel mode
Times get reported to standard error, and the format of the output is:
0m0.03s real 0m0.02s user 0m0.01s system
If the -p option is given (and it's only permitted when pipeline is a simple command, ok?), the output is slightly longer:
real 0.03
user 0.02
sys 0.01
Also, simple redirections of standard error do not affect time's output:
$ time sleep 1 2>afile
$ { time sleep 1; } 2>afile
The times for the first command do not go to โafileโ, but those of the second command do. Sneaky little detail, iykyk. ๐
๐ฐ๏ธ times โ keeps assignments, special
Prints the accumulated user and system times (same ones as above) used by both the shell and by processes the shell started that have already exited. The format of the output is:
0m0.01s 0m.00s
wait no bestie, it's exactly this:
0m0.01s 0m0.00s
0m0.04s 0m0.02s
Two lines, four numbers, no notes. ๐
๐ชค trap n [signal ...] โ keeps assignments, special
If the first operand is a decimal unsigned integer, this resets all the specified signals to the default action. Basically it's the same as calling trap with a dash (-) as the handler, followed by the arguments (interpreted as signals). Same energy, different spelling.
๐ชค trap [handler signal ...] โ keeps assignments, special
This sets a trap handler to be executed when any of the specified signals are received. handler is one of three things:
- an empty string โ meaning the signals are to be ignored
- a dash (
-) โ meaning the default action is to be taken for the signals (seesignal(3)) - a string of shell commands to be executed at the first opportunity โ that's when the current command completes, or before printing the next
PS1prompt โ after receipt of one of the signals
signal is the name, possibly prefixed with โSIGโ, of a signal (like PIPE, ALRM or SIGINT), or the number of the signal (see the kill -l command above, bestie).
There are two special signals:
EXIT(also known as0) โ executed when the shell is about to exitERRโ executed after an error occurs; an error is something that would cause the shell to exit if theset -eorset -o errexitoption were set
EXIT handlers are executed in the environment of the last executed command. The original Korn shell's DEBUG trap, and its handling of ERR and EXIT in functions, are not yet implemented.
Note that, for non-interactive shells, the trap handler cannot be changed for signals that were ignored when the shell started.
With no arguments, the current state of the traps that have been set since the shell started is shown as a series of trap commands. But note: the output of trap cannot be usefully captured or piped to another process โ that's an artifact of the fact that traps are cleared when subprocesses are created. So don't try it, it's giving broken. ๐ญ
โ
true โ regular
A command that exits with a zero status. That's it. That's the whole job. Lowkey the most reliable bestie in the whole shell. ๐ซถ
๐ type name ... โ built-in alias
Reveals how name would be interpreted as a command. Detective work, but make it shell. ๐
๐ท๏ธ typeset
typeset [-+aglpnrtUux] [-L[n] | -R[n] | -Z[n]] [-i[n]] [name [=value] ...]
typeset -f [-tux] [name ...]
keeps assignments, decl-util โ Display or set attributes of shell parameters or functions. Okay so here's the whole deal:
With no name arguments, parameter attributes are shown. Breaking that down:
- if no options are used, the current attributes of all parameters are printed as
typesetcommands - 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 โ+โ (or โ+โ alone), only the names are printed
If any name arguments are given, the attributes of the so named parameters are set (-) or cleared (+). Inside a function, this will cause the parameters to be created (and set to โโ if no value is given) in the local scope โ except if -g is used. Values for parameters may optionally be specified. For name[*], the change affects all elements of the array, and no value may be specified.
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 names are displayed.
Now the options, one by one, no skipping:
-aโ Indexed array attribute.-fโ Function mode. Display or set shell functions and their attributes, instead of shell parameters.-gโ โglobalโ mode. Do not cause named parameters to be created in the local scope when called inside a function.-i[n]โ Integer attribute. n specifies the base to use when stringifying the integer (if not specified, the base given in the first assignment is used). Parameters with this attribute may be assigned arithmetic expressions for values.-L[n]โ Left justify attribute. n specifies the field width. If n is not specified, the current width of the parameter (or the width of its first assigned value) is used. Leading whitespace (and digit zeros, if used with the-Zoption) is stripped. If necessary, values are either truncated or padded with space to fit the field width.-lโ Lower case attribute. All upper case ASCII characters in values are converted to lower case. (In the original Korn shell, this parameter meant โlong integerโ when used with the-ioption.)-nโ Create a bound variable (name reference): any access to the variable name will access the variable value in the current scope instead (this is different from AT&T UNIX ksh93!). Also different from AT&T UNIX ksh93 is that value is lazily evaluated at the time name is accessed. This can be used by functions to access variables whose names are passed as parameters, instead of resorting toeval.-pโ Print completetypesetcommands that can be used to re-create the attributes and values of parameters.-R[n]โ Right justify attribute. n specifies the field width. If n is not specified, the current width of the parameter (or the width of its first assigned value) is used. Trailing whitespace is stripped. If necessary, values are either stripped of leading characters or padded with space to fit the field width.-rโ Read-only attribute. Parameters with this attribute may not be assigned to or unset. Once this attribute is set, it cannot be turned off. Like, ever. Periodt.-tโ Tag attribute. This attribute has no meaning to the shell for parameters and is provided for application use.
For functions, -t is the trace attribute. When functions with the trace attribute are executed, the -o xtrace (-x) shell option is temporarily turned on.
-Uโ Unsigned integer attribute. Integers are printed as unsigned values (combined with the-ioption).-uโ Upper case attribute. All lower case ASCII characters in values are converted to upper case. (In the original Korn shell, this parameter meant โunsigned integerโ when used with the-ioption, which meant upper case letters would never be used for bases greater than 10. See-Uabove.)
For functions, -u is the undefined attribute, used with FPATH. See โFunctionsโ above for the implications of this.
-xโ Export attribute. Parameters are placed in the environment of any executed commands. Functions cannot be exported for security reasons (โshellshockโ).-Z[n]โ Zero fill attribute. If not combined with-L, this is the same as-R, except zero padding is used instead of space padding. For integers, the number is padded, not the base.
Heads up bestie: if any of the-i,-L,-l,-R,-U,-uor-Zoptions are changed, all others from this set are cleared โ unless they're also given on the same command line. Same line or it doesn't count, that's the rule. ๐
๐ ulimit
ulimit [-aBCcdefHilMmnOPpqrSsTtVvwx] [value]
regular โ 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 or the word โunlimitedโ.
The limits affect the shell and any processes created by the shell after a limit is imposed. Note that systems may not allow some limits to be increased once they are set. Also note that the types of limits available are system dependent โ some systems have only the -f limit, or not even that, or can set only the soft limits, etc. So like, vibe check your OS first. ๐
-aโ Display all limits (soft limits unless-His used).-B nโ Set the socket buffer size to n kibibytes.-C nโ Set the number of cached threads to n.-c nโ Impose a size limit of n blocks on the size of core dumps. Silently ignored if the system does not support this limit.-d nโ Limit the size of the data area to n kibibytes. On some systems, read-only maximumbrk(2)size minus etext.-e nโ Set the maximum niceness to n.-f nโ Impose a size limit of n blocks on files written by the shell and its child processes (any size may be read).-Hโ Set the hard limit only (the default is to set both hard and soft limits). With-a, display all hard limits.-i nโ Set the number of pending signals to n.-l nโ Impose a limit of n kibibytes on the amount of locked (wired) physical memory.-M nโ Sets the AIO locked memory to n kibibytes. ๐-m nโ Imposes a limit of n kibibytes on the amount of physical memory used.-n nโ Imposes a limit of n file descriptors that can be open at once. On some systems attempts to set are silently ignored. ๐-O nโ Sets the number of AIO operations to n.-P nโ Limits the number of threads per process to n. This option mostly matches AT&T UNIX ksh93's-T; on AIX, see-ras used by its ksh though.-p nโ Imposes a limit of n processes that can be run by the user (uid) at any one time.-q nโ Limits the size of POSIX message queues to n bytes.-r nโ (AIX) limits the number of threads per process to n. (Linux) sets the maximum real-time priority to n. two moods, one flag โจ-Sโ Sets the soft limit only (the default is to set both hard and soft limits). With-a, displays soft limits (which is the default).-s nโ Limits the size of the stack area to n kibibytes.-T nโ Imposes a time limit of n real seconds (โhumantimeโ) to be used by each process. clock's ticking bestie โฐ-t nโ Imposes a time limit of n CPU seconds spent in user mode to be used by each process.-V nโ Sets the number of vnode monitors on Haiku to n.-v nโ Imposes a limit of n kibibytes on the amount of virtual memory (address space) used.-w nโ Limits the amount of swap space used to at most n kibibytes.-x nโ Sets the maximum number of file locks to n.
As far as ulimit is concerned, a block is 512 bytes. that's the whole lore, no cap ๐ง
๐
umask [-S] [mask]
(regular) Displays or sets the file permission creation mask, aka the umask (peep umask(2)). If you pass -S, the mask you display or set is symbolic; otherwise it's an octal number.
Symbolic masks are like the ones chmod(1) uses. When you use them, they describe what permissions may be made available (as opposed to octal masks, where 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 it's equivalent (on most systems) to the octal mask 007. ๐
๐ฆ unalias [-adt] [name ...]
(regular) The aliases for the given names get removed. With -a, all aliases get removed. With -t or -d, the indicated operations are carried out on tracked or directory aliases, respectively. bye girl ๐จ
๐ธ unset [-fv] parameter ...
(keeps assignments, special) Unsets the named parameters (-v, the default) or functions (-f). With parameter[*], attributes are retained and only the values get unset. The exit status is non-zero if any of the parameters are read-only, and zero otherwise (not portable).
โญ wait [job ...]
(regular) Waits 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 signal number (see kill -l exit-status above); if the last specified job cannot be found (because it never existed or had already finished), the exit status 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 โ and nope, that's not the case when jobs are explicitly specified. ๐
๐ whence [-pv] [name ...]
(regular) Without -v, it's the same as command -v, except aliases are printed as their definition only. With -v, it's exactly identical to command -V. In either case, with -p the search is restricted to the (current) PATH. periodt ๐
๐ which [-a] [name ...]
(dot.mkshrc function) Without -a, behaves like whence -p (does a PATH search for each name, printing the resulting pathname if found); with -a, matches in all PATH components are printed, i.e. the search isn't stopped after a match. If no name was matched, the exit status is 2; if every name was matched, it's zero; otherwise it's 1. No diagnostics are produced on failure to match. silent but deadly ๐
๐ Job control
Job control is 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; you can see all that info with the jobs commands. If job control is fully enabled (using set -m or set -o monitor), the way it is for interactive shells, the processes of a job get 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 fg and bg. main character energy fr fr ๐ฅ
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. sorry bestie, read stays put ๐ญ
When a job is created, it's 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 a 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's 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 bySIGTSTP).signal-description [โcore dumpedโ]โ the job was killed by a signal (e.g. memory fault, hangup); usekill -lfor 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.
careful bestie: when an attempt is made to exit the shell while there are jobs in the stopped state, the shell warns the user that there are stopped jobs and does not exit. If another attempt is immediately made to exit the shell, the stopped jobs are sent aSIGHUPsignal and the shell exits. Similarly, if thenohupoption is not set and there are running jobs when an attempt is made to exit a login shell, the shell warns the user and does not exit. If another attempt is immediately made to exit the shell, the running jobs are sent aSIGHUPsignal and the shell exits. ๐
๐ Terminal state
The state of the controlling terminal can be modified by a command executed in the foreground, whether or not job control is enabled, but the modified terminal state is only kept past the job's lifetime and used for later command invocations if the command exits successfully (i.e. with an exit status of 0). When such a job is momentarily stopped or restarted, the terminal state is saved and restored, respectively, but it will not be kept afterwards. In interactive mode, when line editing is enabled, the terminal state is saved before being reconfigured by the shell for the line editor, then restored before running a command. it's giving save file energy โจ
๐ซถ POSIX mode
Entering set -o posix mode will cause mksh to behave even more POSIX compliant in places where the defaults or opinions differ. Note that mksh will still operate with unsigned 32-bit arithmetic; use lksh if arithmetic on the host long data type, complete with ISO C Undefined Behaviour, is required; refer to the lksh(1) manual page for details. Most other historic, AT&T UNIX ksh-compatible or opinionated differences can be disabled by using this mode; these are:
- The incompatible GNU bash I/O redirection
&>fileis not supported. - File descriptors created by I/O redirections are inherited by child processes.
- Numbers with a leading digit zero are interpreted as octal.
- The
echobuiltin does not interpret backslashes and only supports the exact option-n. - Alias expansion with a trailing space only reruns on command words.
- Tilde expansion follows POSIX instead of Korn shell rules.
- The exit status of
fgis always0. kill -lonly lists signal names, all in one line.getoptsdoes not accept options with a leading+.execskips builtins, functions and other commands and uses aPATHsearch to determine the utility to execute.
๐ง SH mode
Compatibility mode; intended for use with legacy scripts that cannot easily be fixed; the changes are as follows:
- The incompatible GNU bash I/O redirection
&>fileis not supported.
โฆand the caveats list is STILL going, bestie, we're so close I promise ๐
- File descriptors created by I/O redirections get inherited by child processes. fr fr, they just vibe on down the family tree ๐ซถ
- The
echobuiltin does not interpret backslashes, and it only supports the exact option-nโ unless it was built with-DMKSH_MIDNIGHTBSD01ASH_COMPAT. that's the whole menu, no secret extras. - The substitution operations
${x#pat},${x##pat},${x%pat}, and${x%%pat}are lowkey buggy: they wrongly do not require a parenthesis to be escaped, and they do not parse extglobs. ๐ - The
getoptconstruct fromlksh(1)passes through the errorlevel. sh -ceats a leading--if built with-DMKSH_MIDNIGHTBSD01ASH_COMPAT.
โจ Interactive input line editing โจ
okay so when you're in an interactive session, the shell can read your command lines off a tty(4) in three whole modes, and they're controlled by the emacs, gmacs and vi options. โ ๏ธ at most one of those can be set at once, okay? pick a lane. The default is emacs.
You can set your editing mode on purpose with the set built-in. And if none of these options are enabled at all? The shell just reads lines using the normal tty(4) driver, no fancy editing, no drama. But if emacs or gmacs is set, you get emacs-like editing of the command; same energy, if vi is set you get vi-like editing. All three modes are described in detail in the sections coming up next. ๐
In these editing modes, if a line is longer than the screen width (peep the COLUMNS parameter), a '>', '+' or '<' character shows up in the last column, telling you there are more characters after, before and after, or before the current position โ respectively. The line scrolls horizontally as needed. iconic behaviour honestly.
Completed lines get pushed into the history โ unless they begin with an IFS octet or IFS white space, or they're the same as the previous line. yeah, we're not archiving your accidental repeats, bestie. ๐
๐ธ Emacs editing mode ๐ธ
When the emacs option is set, interactive input line editing is on. Warning: this mode is slightly different from the emacs mode in the original Korn shell. not a drill, just a heads up. ๐
In this mode, all the various editing commands (typically bound to one or more control characters) cause immediate actions โ no waiting around for a newline. Several editing commands are bound to particular control characters when the shell is invoked, and you can change those bindings with the bind command.
Here's the list of available editing commands. Each description starts with the name of the command, suffixed with a colon; then an [n] (if the command can be prefixed with a count); and then any keys the command is bound to by default, written in caret notation โ e.g. the ASCII Esc character is written as ^[. These control 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 thebindcommand. Also, many editing commands are only useful on terminals with a visible cursor. The user'stty(4)characters (e.g.ERASE) are bound to reasonable substitutes and override the default bindings; their customary values are shown in parentheses below. The default bindings were chosen to resemble the corresponding Emacs key bindings:
abortโ INTR (^C),^G: Abort the current command, save it to the history, empty the line buffer and set the exit state to interrupted. ๐auto-insert[n]โ Simply causes the character to appear as literal input. Most ordinary characters are bound to this.backward-char[n]โ^B,^XD,ANSI-CurLeft,PC-CurLeft: Moves the cursor backward n characters.backward-word[n]โ^[b,ANSI-Ctrl-CurLeft,ANSI-Alt-CurLeft: 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,ANSI-Home,PC-Home: Moves the cursor to the beginning of the edited input line.capitalise-word[n]โ^[C,^[c: Uppercase the first ASCII character in the next n words, leaving the cursor past the end of the last word.clear-screenโ^[^L: Prints a compile-time configurable sequence to clear the screen and home the cursor, redraws the last line of the prompt string and the currently edited input line. The default sequence works for almost all standard terminals. ๐งผ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). ๐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 thecompletecommand 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 thecompletecommand 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 thecompletecommand above. Note that^Iis usually generated by the Tab (tabulator) key.delete-char-backward[n]โERASE(^H),^?,^H: Deletes n characters before the cursor.delete-char-forward[n]โANSI-Del,PC-Del: Deletes n characters after the cursor.delete-word-backward[n]โPfx1+ERASE(^[^H),WERASE(^W),^[^?,^[^H,^[h: Deletes n words before the cursor.delete-word-forward[n]โ^[d: Deletes characters after the cursor up to the end of n words.down-history[n]โ^N,^XB,ANSI-CurDown,PC-CurDown: Scrolls the history buffer forward n lines (later). Each input line originally starts just after the last entry in the history buffer, sodown-historyis not useful until eithersearch-history,search-history-uporup-historyhas been performed. ๐ซdowncase-word[n]โ^[L,^[l: Lowercases the next n words.edit-line[n]โ^Xe: Internally run the commandfc -e "${VISUAL:-${EDITOR:-vi}}" -- non a temporary script file to interactively edit line n (if n is not specified, the current line); then, unless the editor invoked exits nonzero but even if the script was not changed, execute the resulting script as if typed on the command line; both the edited (resulting) and original lines are added onto history.end-of-historyโ^[>: Moves to the end of the history.end-of-lineโ^E,ANSI-End,PC-End: 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 canonicalisation.eot-or-delete[n]โEOF(^D): If alone on a line, same aseot, otherwise,delete-char-forward.errorโ (not bound): Error (ring the bell).evaluate-regionโ^[^E: Evaluates the text between the mark and the cursor position (the entire line if no mark is set) as function substitution (if it cannot be parsed, the editing state is unchanged and the bell is rung to signal an error);$?is updated accordingly.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,ANSI-CurRight,PC-CurRight: Moves the cursor forward n characters.forward-word[n]โ^[f,ANSI-Ctrl-CurRight,ANSI-Alt-CurRight: Moves the cursor forward to the end of the *n*th word.goto-history[n]โ^[g: Goes to history number n.kill-lineโKILL(^U): Deletes the entire input line.kill-regionโ^W: Deletes the input between the cursor and the mark.kill-to-eol[n]โ^K: Deletes the input from the cursor to the end of the line if n is not specified; otherwise deletes characters between the cursor and column n.listโ^[?: Prints a sorted, columnated list of command names or file names (if any) that can complete the partial word containing the cursor. Directory names have'/'appended to them.list-commandโ^X?: Prints a sorted, columnated list of command names (if any) that can complete the partial word containing the cursor.list-fileโ^X^Y: Prints a sorted, columnated list of file names (if any) that can complete the partial word containing the cursor. File type indicators are appended as described underlistabove.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 anup-history,search-historyorsearch-history-up.no-opโQUIT(^\): This does nothing. ๐prefix-1โ^[: Introduces a 2-character command sequence.prefix-2โ^X,^[[,^[O: Introduces a multi-character command sequence.prev-hist-word[n]โ^[.,^[_: The last word or, if given, the *n*th word (zero-based) of the previous (on repeated execution, second-last, third-last, etc.) command is inserted at the cursor. Use of this editing command trashes the mark.quoteโ^^,^V: The following character is taken literally rather than as an editing command.quote-regionโ^[Q: Escapes the text between the mark and the cursor position (the entire line if no mark is set) into a shell command argument.redraw:^Lโ prints the last line of your prompt string plus your current input line again, on a fresh new line. a lil refresh, bestie ๐search-character-backward:[n]^[^]โ hunts backward in the current line for the *n*th time the next character you type shows up.search-character-forward:[n]^]โ same energy but forward: finds the *n*th occurrence of the next character you type, within the current line.search-history:^Rโ slides you into incremental search mode ๐. The internal history list gets searched backwards for commands matching what you type. If your search string starts with a^, the search is anchored. Hit the escape key to dip out of search mode. Other commands โ including sequences of escape as prefix-1 followed by a prefix-1 or prefix-2 key โ get executed after you've left search mode. The abort command (^G) restores the input line to whatever it was before the search even started. Callingsearch-historyagain and again keeps searching backward to the next previous occurrence of the pattern. Heads up: the history buffer only holds a finite number of lines, and the oldest ones get yeeted as needed. ๐๏ธsearch-history-up:ANSI-PgUp,PC-PgUpโ searches backwards through the history buffer for commands whose beginning matches the part of the input line before the cursor. On an empty line? It behaves exactly likeup-history.search-history-down:ANSI-PgDn,PC-PgDnโ searches forwards through the history buffer for commands whose beginning matches the portion of the input line before the cursor. On an empty line it's the same asdown-history. Ngl this one only really does anything for you after anup-history,search-historyorsearch-history-up. ๐set-mark-command:^[<space>โ drops the mark right where the cursor is sitting. ๐transpose-chars:^Tโ if you're at the end of line, or if thegmacsoption is set, it swaps the two previous characters; otherwise it swaps the previous and current characters and scoots the cursor one character to the right. ๐up-history:[n]^P,^XA,ANSI-CurUp,PC-CurUpโ scrolls the history buffer backward n lines (so, earlier stuff).upcase-word:[n]^[U,^[uโ UPPERCASES the next n words. loud and proud ๐ฃversion:^[^Vโ shows you the version ofmksh. Your current edit buffer comes right back the moment you press a key. That restoring keypress is processed โ unless it's a space.yank:^Yโ sticks the most recently killed text string in at the current cursor position. ๐ซถyank-pop:^[yโ right after a yank, swaps the text it just inserted for the next previously killed text string. it's giving clipboard roulette โจ
The tab completion escapes characters the same way as this code does:
print -nr -- "${x@/[\"-\$\&-*:-?[\\\`\{-\}${IFS-$' \t\n'}]/\\$KSH_MATCH}"
๐ฆ Vi editing mode ๐ฆ
Note: the vi command-line editing mode has not yet been brought up to the same quality and feature set as the emacs mode. It is 8-bit clean but specifically does not support UTF-8 or MBCS.
The vi command-line editor in mksh has basically the same commands as the vi(1) editor, with these exceptions:
- You start out in insert mode. (iconic behaviour honestly)
- There are file name and command completion commands:
=,\,*,^X,^E,^Fand, optionally,<Tab>and<Esc>. - The
_command is different โ inmkshit's the last argument command; invi(1)it goes to the start of the current line. - The
/andGcommands move in the opposite direction to thejcommand. - Commands that don't make sense in a single line editor just aren't available (e.g. screen movement commands and
ex(1)-style colon (:) commands).
Like vi(1), there are two modes: "insert" mode and "command" mode. In insert mode, most characters just get plopped into the buffer at the current cursor position as you type them; but some characters get treated specially. Specifically, these characters are taken from current tty(4) settings (see stty(1)) and keep their usual meaning (normal values in parentheses): kill (^U), erase (^?), werase (^W), eof (^D), intr (^C) and quit (^\).
On top of all that, these characters are also treated specially in insert mode:
^Eโ Command and file name enumeration (see below).^Fโ Command and file name completion (see below). Use it twice in a row and the list of possible completions gets displayed; use it a third time and the completion is undone. ๐ญ^Hโ Erases the previous character.^J|^Mโ End of line. The current line gets read, parsed and executed by the shell.^Vโ Literal next. The next character you type isn't treated specially (handy for inserting the very characters we're describing here).^Xโ Command and file name expansion (see below).<Esc>โ Puts the editor into command mode (see below).<Tab>โ Optional file name and command completion (see^Fabove), enabled withset -o vi-tabcomplete.
In command mode, every character is interpreted as a command. Characters that don't correspond to any command, illegal combinations of commands, or commands that just can't be carried out โ all of those make it beep. ๐ In the command descriptions below, an [n] means the command can be prefixed by a number (so 10l moves right 10 characters); if no number prefix is used, n is assumed to be 1 unless it says otherwise. The term "current position" means the position between the cursor and the character right before 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 (so ab2*&^ contains two words), and a "big-word" is a sequence of non-whitespace characters.
โจ Special mksh vi commands โจ
These following commands are not in โ or are different from โ the normal vi file editor:
[n]_โ Inserts a space followed by the nth big-word from the last command in the history, at the current position, then enters insert mode; if n isn't specified, the last word gets inserted.#โ Inserts the comment character (#) at the start of the current line and returns the line to the shell (equivalent toI#^J).[n]gโ LikeG, except if n isn't specified, it goes to the most recent remembered line.[n]vโ Internally runs the commandfc -e "${VISUAL:-${EDITOR:-vi}}" -- non a temporary script file to interactively edit line n (if n isn't specified, the current line); then, unless the editor invoked exits nonzero โ but even if the script was not changed โ it executes the resulting script as if it were typed on the command line; both the edited (resulting) and original lines get added onto history. ๐*and^Xโ Command or file name expansion gets 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 one 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 matches the big-word against all aliases, functions and built-in commands, as well as any executable files found by searching the directories in thePATHparameter. 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. Replaces the current big-word with the longest unique match obtained after performing command and file name expansion.<Tab>is only recognised if thevi-tabcompleteoption is set, while<Esc>is only recognised if thevi-esccompleteoption is set (seeset -o). If n is specified, the *n*th possible completion gets selected (as reported by the command/file name enumeration command).=and^Eโ Command/file name enumeration. Lists all the commands or files that match the current big-word.^Vโ Displays the version ofmksh. The current edit buffer is restored as soon as a key is pressed. The restoring keypress is ignored. ๐@cโ Macro expansion. Executes the commands found in the alias_c.
๐ Intra-line movement commands ๐
[n]hand[n]^Hโ Move left n characters.[n]land[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, 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 lastf,F,torTcommand.[n],โ Repeats the lastf,F,torTcommand, but moves in the opposite direction.
๐ง Inter-line movement commands ๐ง
[n]j,[n]+, and[n]^Nโ Move to the *n*th next line in the history.[n]k,[n]-, and[n]^Pโ Move to the *n*th previous line in the history.[n]Gโ Move to line n in the history; if n isn't specified, the number of the first remembered line is used.[n]gโ LikeG, except if n isn't 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 energy as/, except it searches forward through the history. iykyk.[n]nโ hunts down the *n*th occurrence of the last search string you used, going the same direction as last time. no thinking required, just vibes.[n]Nโ same thing but the direction is the opposite of the last search. contrarian queen behavior ๐ANSI-CurUp,PC-PgUpโ grabs everything from the start of the line up to wherever your cursor is chilling, uses it as the search string, then does a history search backwards for lines that begin with that string, and keeps your cursor exactly where it was. โจ Heads up: this only works in insert mode, and it keeps insert mode on.ANSI-CurDown,PC-PgDnโ same deal as above but searching forwards instead of backwards. Also only in insert mode, also keeps it enabled. ๐ฆ
๐ Edit commands ๐
[n]aโ append text n times; drops you into insert mode just after the current position. ngl the append only gets replicated if you re-enter command mode, i.e. you hit<Esc>.[n]Aโ literallyabut it appends at the end of the line instead.[n]iโ insert text n times; goes into insert mode at the current position. Same rule asa: the insertion only replicates if you re-enter command mode, i.e.<Esc>.[n]Iโ same asi, except the insertion happens just before the first non-blank character.[n]sโ substitute the next n characters (aka delete them and go into insert mode). slay.Sโ substitute the whole line. Every character from the first non-blank one to the end of the line gets deleted, then insert mode is entered.[n]cmove-cmdโ change from the current position to wherever n move-cmds land you (read: delete the indicated region and go into insert mode); ifmove-cmdisc, then the line starting from the first non-blank character is the thing that gets changed.Cโ change from the current position to the end of the line (delete to end of line, enter insert mode). iconic.[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 wherever n move-cmds take you;move-cmdis a movement command (see above) ord, in which case the current line gets deleted.[n]rcโ replace the next n characters with the character c.[n]Rโ Replace. Enters insert mode but overwrites existing characters instead of inserting before them. The replacement repeats n times.[n]~โ change the case of the next n characters. โจ[n]ymove-cmdโ yank from the current position to wherever n move-cmds take you, straight into the yank buffer; ifmove-cmdisy, the whole line gets 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 asp, except the buffer gets pasted at the current position.
๐ Miscellaneous vi commands ๐
^Jand^Mโ the current line is read, parsed and executed by the shell. ๐ซถ^Land^Rโ redraw the current line.[n].โ redo the last edit command n times.uโ undo the last edit command. the way that this one saves lives ๐ญUโ undo all changes made to the current line.- PC Home, End, Del and cursor keys โ they move as expected, both in insert and command mode. no notes.
intrandquitโ the interrupt and quit terminal characters cause the current line to be removed to the history and a brand new prompt to be printed.
๐ FILES ๐
~/.mkshrcโ user mkshrc profile (for non-privileged interactive shells); see "Startup files." The location can be changed at compile time (e.g. for embedded systems); AOSP Android builds use/system/etc/mkshrc.~/.profileโ user profile (non-privileged login shells); see "Startup files" near the top of this manual./etc/profileโ system profile (login shells); see "Startup files."/etc/shellsโ shell database./etc/suid_profileโ privileged shells' profile (sugid); see "Startup files."
๐ Note: On Android, /system/etc/ contains the system and suid profile.
โญ SEE ALSO โญ
awk(1), cat(1), ed(1), getopt(1), lksh(1), sed(1), sh(1), stty(1), dup(2), execve(2), getgid(2), getuid(2), mknod(2), mkfifo(2), open(2), pipe(2), rename(2), wait(2), getopt(3), nl_langinfo(3), setlocale(3), signal(3), system(3), tty(4), shells(5), environ(7), script(7), utf-8(7), mknod(8)
The FAQ lives at http://www.mirbsd.org/mksh-faq.htm or in the mksh.faq file. ๐ง
http://www.mirbsd.org/ksh-chan.htm
Morris Bolsky, The KornShell Command and Programming Language, Prentice Hall PTR, xvi + 356 pages, 1989, ISBN 978-0-13-516972-8 (0-13-516972-0).
Morris I. Bolsky and David G. Korn, The New KornShell Command and Programming Language (2nd Edition), Prentice Hall PTR, xvi + 400 pages, 1995, ISBN 978-0-13-182700-4 (0-13-182700-6).
Stephen G. Kochan and Patrick H. Wood, UNIX Shell Programming, Sams, 3rd Edition, xiii + 437 pages, 2003, ISBN 978-0-672-32490-1 (0-672-32490-3).
IEEE Inc., IEEE Standard for Information Technology โ Portable Operating System Interface (POSIX), IEEE Press, Part 2: Shell and Utilities, xvii + 1195 pages, 1993, ISBN 978-1-55937-255-8 (1-55937-255-9).
Bill Rosenblatt, Learning the Korn Shell, O'Reilly, 360 pages, 1993, ISBN 978-1-56592-054-5 (1-56592-054-6).
Bill Rosenblatt and Arnold Robbins, Learning the Korn Shell, Second Edition, O'Reilly, 432 pages, 2002, ISBN 978-0-596-00195-7 (0-596-00195-9).
Barry Rosenberg, KornShell Programming Tutorial, Addison-Wesley Professional, xxi + 324 pages, 1991, ISBN 978-0-201-56324-5 (0-201-56324-X).
๐ AUTHORS ๐
The MirBSD Korn Shell is developed by mirabilos <m@mirbsd.org> as part of The MirOS Project. โจ
This shell is based on the public domain 7th edition Bourne shell clone by Charles Forsyth, who kindly agreed to, in countries where the Public Domain status of the work may not be valid, grant a copyright licence to the general public to deal in the work without restriction and permission to sublicence derivatives under the terms of any (OSI approved) Open Source licence โ plus 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, Simon J. Gerraty and Michael Rendell. The effort of several projects, such as Debian and OpenBSD, and other contributors including our users, to improve the shell is appreciated. ๐ซถ See the documentation, website and source code (CVS) for details.
mksh-os2 is developed by KO Myung-Hun <komh@chollian.net>.
mksh-w32 is developed by Michael Langguth <lan@scalaris.com>.
mksh/z/OS is contributed by Daniel Richard G. <skunk@iSKUNK.ORG>.
The BSD daemon is Copyright ยฉ Marshall Kirk McKusick. The complete legalese is at: http://www.mirbsd.org/TaC-mksh.txt
โ ๏ธ CAVEATS โ ๏ธ
mksh provides a consistent, clear interface normally. This may deviate from POSIX in historic or opinionated places. set -o posix (see "POSIX mode" for details) will make the shell more conformant, but mind the FAQ (see "SEE ALSO"), especially regarding locales. ๐
mksh (but not lksh) provides a consistent 32-bit integer arithmetic implementation, both signed and unsigned, with sign of the result of a remainder operation and wraparound defined, even (defying POSIX) on 36-bit and 64-bit systems. ๐
mksh currently uses OPTU-16 internally, which is the same as UTF-8 and CESU-8 with 0000..FFFD being valid codepoints; raw octets are mapped into the PUA range EF80..EFFF, which is assigned by CSUR for this purpose.
๐ BUGS ๐
Suspending (using ^Z) pipelines like the one below will only suspend the currently running part of the pipeline; in this example, "fubar" is immediately printed on suspension (but not later after an fg). ๐ญ
$ /bin/sleep 666 && echo fubar
The truncation process involved when changing HISTFILE does not free old history entries (leaks memory) and leaks old entries into the new history if their line numbers are not overwritten by same-number entries from the persistent history file; truncating the on-disc file to HISTSIZE lines has always been broken and prone to history file corruption when multiple shells are accessing the file; the rollover process for the in-memory portion of the history is slow, should use memmove(3). ๐
This document attempts to describe mksh R59c and up, compiled without any options impacting functionality, such as MKSH_SMALL, when not called as /bin/sh which, on some systems only, enables set -o posix or set -o sh automatically (whose behaviour differs across targets), for an operating environment supporting all of its advanced needs.
Please report bugs in mksh to the public development mailing list at <miros-mksh@mirbsd.org> (please note the EU-DSGVO/GDPR notice on http://www.mirbsd.org/rss.htm#lists and in the SMTP banner!) or in the #!/bin/mksh (or #ksh) IRC channel at irc.freenode.net (Port 6697 SSL, 6667 unencrypted), or at: https://launchpad.net/mksh ๐ธ
and that's a wrap bestie!! ๐โจ this page is from MirBSD, dated October 1, 2020, and it's the MKSH(1) manual โ go forth and shell like the main character you are ๐ ๐๐
๐ฆ where this page comes from
- alpine 3.22: mksh-doc 59c-r4 ยท MirOS AND Unicode-DFS-2016
- alpine 3.23: mksh-doc 59c-r4 ยท MirOS AND Unicode-DFS-2016
- alpine 3.24: mksh-doc 59c-r4 ยท MirOS AND Unicode-DFS-2016
- centos-stream 10: mksh 59c-13.el10 ยท MirOS AND ISC
- centos-stream 9: mksh 59c-6.el9 ยท MirOS and ISC and BSD
- fedora 43: mksh 59c-14.fc43 ยท MirOS AND ISC
- fedora 44: mksh 59c-15.fc44 ยท MirOS AND ISC
- nixos 26.05: mksh 59c
- nixpkgs unstable: mksh 59c
- Copyright ยฉ 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms