1MKSH(1)                   BSD General Commands Manual                  MKSH(1)
2

NAME

4     mksh, sh — MirBSD Korn shell
5

SYNOPSIS

7     mksh [-+abCefhiklmnprUuvXx] [-T [!]tty | -] [-+o option] [-c string | -s
8          | file [argument ...]]
9     builtin-name [argument ...]
10

DESCRIPTION

12     mksh is a command interpreter intended for both interactive and shell
13     script use.  Its command language is a superset of the sh(C) shell lan‐
14     guage and largely compatible to the original Korn shell.  At times, this
15     manual page may give scripting advice; while it sometimes does take por‐
16     table shell scripting or various standards into account all information
17     is first and foremost presented with mksh in mind and should be taken as
18     such.
19
20   I use Android, OS/2, etc. so what...?
21     Please see the FAQ at the end of this document.
22
23   Invocation
24     Most builtins can be called directly, for example if a link points from
25     its name to the shell; not all make sense, have been tested or work at
26     all though.
27
28     The options are as follows:
29
30     -c string  mksh will execute the command(s) contained in string.
31
32     -i         Interactive shell.  A shell that reads commands from standard
33                input is “interactive” if this option is used or if both stan‐
34                dard input and standard error are attached to a tty(4).  An
35                interactive shell has job control enabled, ignores the SIGINT,
36                SIGQUIT and SIGTERM signals, and prints prompts before reading
37                input (see the PS1 and PS2 parameters).  It also processes the
38                ENV parameter or the mkshrc file (see below).  For non-inter‐
39                active shells, the trackall option is on by default (see the
40                set command below).
41
42     -l         Login shell.  If the basename the shell is called with (i.e.
43                argv[0]) starts with ‘-’ or if this option is used, the shell
44                is assumed to be a login shell; see Startup files below.
45
46     -p         Privileged shell.  A shell is “privileged” if the real user ID
47                or group ID does not match the effective user ID or group ID
48                (see getuid(2) and getgid(2)).  Clearing the privileged option
49                causes the shell to set its effective user ID (group ID) to
50                its real user ID (group ID).  For further implications, see
51                Startup files.  If the shell is privileged and this flag is
52                not explicitly set, the “privileged” option is cleared auto‐
53                matically after processing the startup files.
54
55     -r         Restricted shell.  A shell is “restricted” if this option is
56                used.  The following restrictions come into effect after the
57                shell processes any profile and ENV files:
58
59                ·   The cd (and chdir) command is disabled.
60                ·   The SHELL, ENV and PATH parameters cannot be changed.
61                ·   Command names can't be specified with absolute or relative
62                    paths.
63                ·   The -p option of the built-in command command can't be
64                    used.
65                ·   Redirections that create files can't be used (i.e. “>”,
66                    “>|”, “>>”, “<>”).
67
68     -s         The shell reads commands from standard input; all non-option
69                arguments are positional parameters.
70
71     -T name    Spawn mksh on the tty(4) device given.  The paths name,
72                /dev/ttyCname and /dev/ttyname are attempted in order.  Unless
73                name begins with an exclamation mark (‘!’), this is done in a
74                subshell and returns immediately.  If name is a dash (‘-’),
75                detach from controlling terminal (daemonise) instead.
76
77     In addition to the above, the options described in the set built-in com‐
78     mand can also be used on the command line: both [-+abCefhkmnuvXx] and
79     [-+o option] can be used for single letter or long options, respectively.
80
81     If neither the -c nor the -s option is specified, the first non-option
82     argument specifies the name of a file the shell reads commands from.  If
83     there are no non-option arguments, the shell reads commands from the
84     standard input.  The name of the shell (i.e. the contents of $0) is
85     determined as follows: if the -c option is used and there is a non-option
86     argument, it is used as the name; if commands are being read from a file,
87     the file is used as the name; otherwise, the basename the shell was
88     called with (i.e. argv[0]) is used.
89
90     The exit status of the shell is 127 if the command file specified on the
91     command line could not be opened, or non-zero if a fatal syntax error
92     occurred during the execution of a script.  In the absence of fatal
93     errors, the exit status is that of the last command executed, or zero if
94     no command is executed.
95
96   Startup files
97     For the actual location of these files, see FILES.  A login shell pro‐
98     cesses the system profile first.  A privileged shell then processes the
99     suid profile.  A non-privileged login shell processes the user profile
100     next.  A non-privileged interactive shell checks the value of the ENV
101     parameter after subjecting it to parameter, command, arithmetic and tilde
102     (‘~’) substitution; if unset or empty, the user mkshrc profile is pro‐
103     cessed; otherwise, if a file whose name is the substitution result
104     exists, it is processed; non-existence is silently ignored.  A privileged
105     shell then drops privileges if neither was the -p option given on the
106     command line nor set during execution of the startup files.
107
108   Command syntax
109     The shell begins parsing its input by removing any backslash-newline com‐
110     binations, then breaking it into words.  Words (which are sequences of
111     characters) are delimited by unquoted whitespace characters (space, tab
112     and newline) or meta-characters (‘<’, ‘>’, ‘|’, ‘;’, ‘(’, ‘)’ and ‘&’).
113     Aside from delimiting words, spaces and tabs are ignored, while newlines
114     usually delimit commands.  The meta-characters are used in building the
115     following tokens: “<”, “<&”, “<<”, “<<<”, “>”, “>&”, “>>”, “&>”, etc. are
116     used to specify redirections (see Input/output redirection below); “|” is
117     used to create pipelines; “|&” is used to create co-processes (see
118     Co-processes below); “;” is used to separate commands; “&” is used to
119     create asynchronous pipelines; “&&” and “||” are used to specify condi‐
120     tional execution; “;;”, “;&” and “;|” are used in case statements; “((
121     ... ))” is used in arithmetic expressions; and lastly, “( ... )” is used
122     to create subshells.
123
124     Whitespace and meta-characters can be quoted individually using a back‐
125     slash (‘\’), or in groups using double (‘"’) or single (“'”) quotes.
126     Note that the following characters are also treated specially by the
127     shell and must be quoted if they are to represent themselves: ‘\’, ‘"’,
128     “'”, ‘#’, ‘$’, ‘`’, ‘~’, ‘{’, ‘}’, ‘*’, ‘?’ and ‘[’.  The first three of
129     these are the above mentioned quoting characters (see Quoting below);
130     ‘#’, if used at the beginning of a word, introduces a comment – every‐
131     thing after the ‘#’ up to the nearest newline is ignored; ‘$’ is used to
132     introduce parameter, command and arithmetic substitutions (see
133     Substitution below); ‘`’ introduces an old-style command substitution
134     (see Substitution below); ‘~’ begins a directory expansion (see Tilde
135     expansion below); ‘{’ and ‘}’ delimit csh(1)-style alternations (see
136     Brace expansion below); and finally, ‘*’, ‘?’ and ‘[’ are used in file
137     name generation (see File name patterns below).
138
139     As words and tokens are parsed, the shell builds commands, of which there
140     are two basic types: simple-commands, typically programmes that are exe‐
141     cuted, and compound-commands, such as for and if statements, grouping
142     constructs and function definitions.
143
144     A simple-command consists of some combination of parameter assignments
145     (see Parameters below), input/output redirections (see Input/output
146     redirections below) and command words; the only restriction is that
147     parameter assignments come before any command words.  The command words,
148     if any, define the command that is to be executed and its arguments.  The
149     command may be a shell built-in command, a function or an external com‐
150     mand (i.e. a separate executable file that is located using the PATH
151     parameter; see Command execution below).  Note that all command con‐
152     structs have an exit status: for external commands, this is related to
153     the status returned by wait(2) (if the command could not be found, the
154     exit status is 127; if it could not be executed, the exit status is 126);
155     the exit status of other command constructs (built-in commands, func‐
156     tions, compound-commands, pipelines, lists, etc.) are all well-defined
157     and are described where the construct is described.  The exit status of a
158     command consisting only of parameter assignments is that of the last com‐
159     mand substitution performed during the parameter assignment or 0 if there
160     were no command substitutions.
161
162     Commands can be chained together using the “|” token to form pipelines,
163     in which the standard output of each command but the last is piped (see
164     pipe(2)) to the standard input of the following command.  The exit status
165     of a pipeline is that of its last command, unless the pipefail option is
166     set (see there).  All commands of a pipeline are executed in separate
167     subshells; this is allowed by POSIX but differs from both variants of
168     AT&T UNIX ksh, where all but the last command were executed in subshells;
169     see the read builtin's description for implications and workarounds.  A
170     pipeline may be prefixed by the “!” reserved word which causes the exit
171     status of the pipeline to be logically complemented: if the original sta‐
172     tus was 0, the complemented status will be 1; if the original status was
173     not 0, the complemented status will be 0.
174
175     Lists of commands can be created by separating pipelines by any of the
176     following tokens: “&&”, “||”, “&”, “|&” and “;”.  The first two are for
177     conditional execution: “cmd1 && cmd2” executes cmd2 only if the exit sta‐
178     tus of cmd1 is zero; “||” is the opposite – cmd2 is executed only if the
179     exit status of cmd1 is non-zero.  “&&” and “||” have equal precedence
180     which is higher than that of “&”, “|&” and “;”, which also have equal
181     precedence.  Note that the “&&” and “||” operators are
182     "left-associative".  For example, both of these commands will print only
183     "bar":
184
185           $ false && echo foo || echo bar
186           $ true || echo foo && echo bar
187
188     The “&” token causes the preceding command to be executed asynchronously;
189     that is, the shell starts the command but does not wait for it to com‐
190     plete (the shell does keep track of the status of asynchronous commands;
191     see Job control below).  When an asynchronous command is started when job
192     control is disabled (i.e. in most scripts), the command is started with
193     signals SIGINT and SIGQUIT ignored and with input redirected from
194     /dev/null (however, redirections specified in the asynchronous command
195     have precedence).  The “|&” operator starts a co-process which is a spe‐
196     cial kind of asynchronous process (see Co-processes below).  Note that a
197     command must follow the “&&” and “||” operators, while it need not follow
198     “&”, “|&” or “;”.  The exit status of a list is that of the last command
199     executed, with the exception of asynchronous lists, for which the exit
200     status is 0.
201
202     Compound commands are created using the following reserved words.  These
203     words are only recognised if they are unquoted and if they are used as
204     the first word of a command (i.e. they can't be preceded by parameter
205     assignments or redirections):
206
207           case     else     function     then      !       (
208           do       esac     if           time      [[      ((
209           done     fi       in           until     {
210           elif     for      select       while     }
211
212     In the following compound command descriptions, command lists (denoted as
213     list) that are followed by reserved words must end with a semicolon, a
214     newline or a (syntactically correct) reserved word.  For example, the
215     following are all valid:
216
217           $ { echo foo; echo bar; }
218           $ { echo foo; echo bar<newline>}
219           $ { { echo foo; echo bar; } }
220
221     This is not valid:
222
223           $ { echo foo; echo bar }
224
225     (list)
226           Execute list in a subshell.  There is no implicit way to pass envi‐
227           ronment changes from a subshell back to its parent.
228
229     { list; }
230           Compound construct; list is executed, but not in a subshell.  Note
231           that “{” and “}” are reserved words, not meta-characters.
232
233     case word in [[(] pattern [| pattern] ...) list terminator] ... esac
234           The case statement attempts to match word against a specified
235           pattern; the list associated with the first successfully matched
236           pattern is executed.  Patterns used in case statements are the same
237           as those used for file name patterns except that the restrictions
238           regarding ‘.’ and ‘/’ are dropped.  Note that any unquoted space
239           before and after a pattern is stripped; any space within a pattern
240           must be quoted.  Both the word and the patterns are subject to
241           parameter, command and arithmetic substitution, as well as tilde
242           substitution.
243
244           For historical reasons, open and close braces may be used instead
245           of in and esac e.g. case $foo { *) echo bar ;; }.
246
247           The list terminators are:
248
249           “;;”  Terminate after the list.
250
251           “;&”  Fall through into the next list.
252
253           “;|”  Evaluate the remaining pattern-list tuples.
254
255           The exit status of a case statement is that of the executed list;
256           if no list is executed, the exit status is zero.
257
258     for name [in word ...]; do list; done
259           For each word in the specified word list, the parameter name is set
260           to the word and list is executed.  If in is not used to specify a
261           word list, the positional parameters ($1, $2, etc.) are used
262           instead.  For historical reasons, open and close braces may be used
263           instead of do and done e.g. for i; { echo $i; }.  The exit status
264           of a for statement is the last exit status of list; if list is
265           never executed, the exit status is zero.
266
267     if list; then list; [elif list; then list;] ... [else list;] fi
268           If the exit status of the first list is zero, the second list is
269           executed; otherwise, the list following the elif, if any, is exe‐
270           cuted with similar consequences.  If all the lists following the if
271           and elifs fail (i.e. exit with non-zero status), the list following
272           the else is executed.  The exit status of an if statement is that
273           of non-conditional list that is executed; if no non-conditional
274           list is executed, the exit status is zero.
275
276     select name [in word ...]; do list; done
277           The select statement provides an automatic method of presenting the
278           user with a menu and selecting from it.  An enumerated list of the
279           specified word(s) is printed on standard error, followed by a
280           prompt (PS3: normally “#? ”).  A number corresponding to one of the
281           enumerated words is then read from standard input, name is set to
282           the selected word (or unset if the selection is not valid), REPLY
283           is set to what was read (leading/trailing space is stripped), and
284           list is executed.  If a blank line (i.e. zero or more IFS octets)
285           is entered, the menu is reprinted without executing list.
286
287           When list completes, the enumerated list is printed if REPLY is
288           empty, the prompt is printed, and so on.  This process continues
289           until an end-of-file is read, an interrupt is received, or a break
290           statement is executed inside the loop.  If “in word ...” is omit‐
291           ted, the positional parameters are used (i.e. $1, $2, etc.).  For
292           historical reasons, open and close braces may be used instead of do
293           and done e.g. select i; { echo $i; }.  The exit status of a select
294           statement is zero if a break statement is used to exit the loop,
295           non-zero otherwise.
296
297     until list; do list; done
298           This works like while, except that the body is executed only while
299           the exit status of the first list is non-zero.
300
301     while list; do list; done
302           A while is a pre-checked loop.  Its body is executed as often as
303           the exit status of the first list is zero.  The exit status of a
304           while statement is the last exit status of the list in the body of
305           the loop; if the body is not executed, the exit status is zero.
306
307     function name { list; }
308           Defines the function name (see Functions below).  Note that redi‐
309           rections specified after a function definition are performed when‐
310           ever the function is executed, not when the function definition is
311           executed.
312
313     name() command
314           Mostly the same as function (see Functions below).  Whitespace
315           (space or tab) after name will be ignored most of the time.
316
317     function name() { list; }
318           The same as name() (bashism).  The function keyword is ignored.
319
320     time [-p] [pipeline]
321           The Command execution section describes the time reserved word.
322
323     (( expression ))
324           The arithmetic expression expression is evaluated; equivalent to
325           “let "expression"” (see Arithmetic expressions and the let command,
326           below) in a compound construct.
327
328     [[ expression ]]
329           Similar to the test and [ ... ] commands (described later), with
330           the following exceptions:
331
332           ·   Field splitting and file name generation are not performed on
333               arguments.
334
335           ·   The -a (AND) and -o (OR) operators are replaced with “&&” and
336               “||”, respectively.
337
338           ·   Operators (e.g. “-f”, “=”, “!”) must be unquoted.
339
340           ·   Parameter, command and arithmetic substitutions are performed
341               as expressions are evaluated and lazy expression evaluation is
342               used for the “&&” and “||” operators.  This means that in the
343               following statement, $(<foo) is evaluated if and only if the
344               file foo exists and is readable:
345
346                     $ [[ -r foo && $(<foo) = b*r ]]
347
348           ·   The second operand of the “!=” and “=” expressions are a subset
349               of patterns (e.g. the comparison [[ foobar = f*r ]] succeeds).
350               This even works indirectly:
351
352                     $ bar=foobar; baz='f*r'
353                     $ [[ $bar = $baz ]]; echo $?
354                     $ [[ $bar = "$baz" ]]; echo $?
355
356               Perhaps surprisingly, the first comparison succeeds, whereas
357               the second doesn't.  This does not apply to all extglob
358               metacharacters, currently.
359
360   Quoting
361     Quoting is used to prevent the shell from treating characters or words
362     specially.  There are three methods of quoting.  First, ‘\’ quotes the
363     following character, unless it is at the end of a line, in which case
364     both the ‘\’ and the newline are stripped.  Second, a single quote (“'”)
365     quotes everything up to the next single quote (this may span lines).
366     Third, a double quote (‘"’) quotes all characters, except ‘$’, ‘\’ and
367     ‘`’, up to the next unescaped double quote.  ‘$’ and ‘`’ inside double
368     quotes have their usual meaning (i.e. parameter, arithmetic or command
369     substitution) except no field splitting is carried out on the results of
370     double-quoted substitutions, and the old-style form of command substitu‐
371     tion has backslash-quoting for double quotes enabled.  If a ‘\’ inside a
372     double-quoted string is followed by ‘"’, ‘$’, ‘\’ or ‘`’, only the ‘\’ is
373     removed, i.e. the combination is replaced by the second character; if it
374     is followed by a newline, both the ‘\’ and the newline are stripped; oth‐
375     erwise, both the ‘\’ and the character following are unchanged.
376
377     If a single-quoted string is preceded by an unquoted ‘$’, C style back‐
378     slash expansion (see below) is applied (even single quote characters
379     inside can be escaped and do not terminate the string then); the expanded
380     result is treated as any other single-quoted string.  If a double-quoted
381     string is preceded by an unquoted ‘$’, the ‘$’ is simply ignored.
382
383   Backslash expansion
384     In places where backslashes are expanded, certain C and AT&T UNIX ksh or
385     GNU bash style escapes are translated.  These include “\a”, “\b”, “\f”,
386     “\n”, “\r”, “\t”, “\U########”, “\u####” and “\v”.  For “\U########” and
387     “\u####”, “#” means a hexadecimal digit, of which there may be none up to
388     four or eight; these escapes translate a Unicode codepoint to UTF-8.
389     Furthermore, “\E” and “\e” expand to the escape character.
390
391     In the print builtin mode, “\"”, “\'” and “\?” are explicitly excluded;
392     octal sequences must have the none up to three octal digits “#” prefixed
393     with the digit zero (“\0###”); hexadecimal sequences “\x##” are limited
394     to none up to two hexadecimal digits “#”; both octal and hexadecimal
395     sequences convert to raw octets; “\#”, where # is none of the above,
396     translates to \# (backslashes are retained).
397
398     Backslash expansion in the C style mode slightly differs: octal sequences
399     “\###” must have no digit zero prefixing the one up to three octal digits
400     “#” and yield raw octets; hexadecimal sequences “\x#*” greedily eat up as
401     many hexadecimal digits “#” as they can and terminate with the first non-
402     hexadecimal digit; these translate a Unicode codepoint to UTF-8.  The
403     sequence “\c#”, where “#” is any octet, translates to Ctrl-# (which basi‐
404     cally means, “\c?” becomes DEL, everything else is bitwise ANDed with
405     0x1F).  Finally, “\#”, where # is none of the above, translates to # (has
406     the backslash trimmed), even if it is a newline.
407
408   Aliases
409     There are two types of aliases: normal command aliases and tracked
410     aliases.  Command aliases are normally used as a short hand for a long or
411     often used command.  The shell expands command aliases (i.e. substitutes
412     the alias name for its value) when it reads the first word of a command.
413     An expanded alias is re-processed to check for more aliases.  If a com‐
414     mand alias ends in a space or tab, the following word is also checked for
415     alias expansion.  The alias expansion process stops when a word that is
416     not an alias is found, when a quoted word is found, or when an alias word
417     that is currently being expanded is found.  Aliases are specifically an
418     interactive feature: while they do happen to work in scripts and on the
419     command line in some cases, aliases are expanded during lexing, so their
420     use must be in a separate command tree from their definition; otherwise,
421     the alias will not be found.  Noticeably, command lists (separated by
422     semicolon, in command substitutions also by newline) may be one same
423     parse tree.
424
425     The following command aliases are defined automatically by the shell:
426
427           autoload='\\builtin typeset -fu'
428           functions='\\builtin typeset -f'
429           hash='\\builtin alias -t'
430           history='\\builtin fc -l'
431           integer='\\builtin typeset -i'
432           local='\\builtin typeset'
433           login='\\builtin exec login'
434           nameref='\\builtin typeset -n'
435           nohup='nohup '
436           r='\\builtin fc -e -'
437           type='\\builtin whence -v'
438
439     Tracked aliases allow the shell to remember where it found a particular
440     command.  The first time the shell does a path search for a command that
441     is marked as a tracked alias, it saves the full path of the command.  The
442     next time the command is executed, the shell checks the saved path to see
443     that it is still valid, and if so, avoids repeating the path search.
444     Tracked aliases can be listed and created using alias -t.  Note that
445     changing the PATH parameter clears the saved paths for all tracked
446     aliases.  If the trackall option is set (i.e. set -o trackall or set -h),
447     the shell tracks all commands.  This option is set automatically for non-
448     interactive shells.  For interactive shells, only the following commands
449     are automatically tracked: cat(1), cc(1), chmod(1), cp(1), date(1),
450     ed(1), emacs(1), grep(1), ls(1), make(1), mv(1), pr(1), rm(1), sed(1),
451     sh(1), vi(1) and who(1).
452
453   Substitution
454     The first step the shell takes in executing a simple-command is to per‐
455     form substitutions on the words of the command.  There are three kinds of
456     substitution: parameter, command and arithmetic.  Parameter substitu‐
457     tions, which are described in detail in the next section, take the form
458     $name or ${...}; command substitutions take the form $(command) or (dep‐
459     recated) `command` or (executed in the current environment) ${ command;}
460     and strip trailing newlines; and arithmetic substitutions take the form
461     $((expression)).  Parsing the current-environment command substitution
462     requires a space, tab or newline after the opening brace and that the
463     closing brace be recognised as a keyword (i.e. is preceded by a newline
464     or semicolon).  They are also called funsubs (function substitutions) and
465     behave like functions in that local and return work, and in that exit
466     terminates the parent shell; shell options are shared.
467
468     Another variant of substitution are the valsubs (value substitutions)
469     ${|command;} which are also executed in the current environment, like
470     funsubs, but share their I/O with the parent; instead, they evaluate to
471     whatever the, initially empty, expression-local variable REPLY is set to
472     within the commands.
473
474     If a substitution appears outside of double quotes, the results of the
475     substitution are generally subject to word or field splitting according
476     to the current value of the IFS parameter.  The IFS parameter specifies a
477     list of octets which are used to break a string up into several words;
478     any octets from the set space, tab and newline that appear in the IFS
479     octets are called “IFS whitespace”.  Sequences of one or more IFS white‐
480     space octets, in combination with zero or one non-IFS whitespace octets,
481     delimit a field.  As a special case, leading and trailing IFS whitespace
482     is stripped (i.e. no leading or trailing empty field is created by it);
483     leading or trailing non-IFS whitespace does create an empty field.
484
485     Example: If IFS is set to “<space>:” and VAR is set to
486     “<space>A<space>:<space><space>B::D”, the substitution for $VAR results
487     in four fields: “A”, “B”, “” (an empty field) and “D”.  Note that if the
488     IFS parameter is set to the empty string, no field splitting is done; if
489     it is unset, the default value of space, tab and newline is used.
490
491     Also, note that the field splitting applies only to the immediate result
492     of the substitution.  Using the previous example, the substitution for
493     $VAR:E results in the fields: “A”, “B”, “” and “D:E”, not “A”, “B”, “”,
494     “D” and “E”.  This behavior is POSIX compliant, but incompatible with
495     some other shell implementations which do field splitting on the word
496     which contained the substitution or use IFS as a general whitespace
497     delimiter.
498
499     The results of substitution are, unless otherwise specified, also subject
500     to brace expansion and file name expansion (see the relevant sections
501     below).
502
503     A command substitution is replaced by the output generated by the speci‐
504     fied command which is run in a subshell.  For $(command) and ${|command;}
505     and ${ command;} substitutions, normal quoting rules are used when
506     command is parsed; however, for the deprecated `command` form, a ‘\’ fol‐
507     lowed by any of ‘$’, ‘`’ or ‘\’ is stripped (as is ‘"’ when the substitu‐
508     tion is part of a double-quoted string); a backslash ‘\’ followed by any
509     other character is unchanged.  As a special case in command substitu‐
510     tions, a command of the form <file is interpreted to mean substitute the
511     contents of file.  Note that $(<foo) has the same effect as $(cat foo).
512
513     Note that some shells do not use a recursive parser for command substitu‐
514     tions, leading to failure for certain constructs; to be portable, use as
515     workaround “x=$(cat) <<\EOF” (or the newline-keeping “x=<<\EOF” exten‐
516     sion) instead to merely slurp the string.  IEEE Std 1003.1 (“POSIX.1”)
517     recommends using case statements of the form x=$(case $foo in (bar) echo
518     $bar ;; (*) echo $baz ;; esac) instead, which would work but not serve as
519     example for this portability issue.
520
521           x=$(case $foo in bar) echo $bar ;; *) echo $baz ;; esac)
522           # above fails to parse on old shells; below is the workaround
523           x=$(eval $(cat)) <<\EOF
524           case $foo in bar) echo $bar ;; *) echo $baz ;; esac
525           EOF
526
527     Arithmetic substitutions are replaced by the value of the specified
528     expression.  For example, the command print $((2+3*4)) displays 14.  See
529     Arithmetic expressions for a description of an expression.
530
531   Parameters
532     Parameters are shell variables; they can be assigned values and their
533     values can be accessed using a parameter substitution.  A parameter name
534     is either one of the special single punctuation or digit character param‐
535     eters described below, or a letter followed by zero or more letters or
536     digits (‘_’ counts as a letter).  The latter form can be treated as
537     arrays by appending an array index of the form [expr] where expr is an
538     arithmetic expression.  Array indices in mksh are limited to the range 0
539     through 4294967295, inclusive.  That is, they are a 32-bit unsigned inte‐
540     ger.
541
542     Parameter substitutions take the form $name, ${name} or ${name[expr]}
543     where name is a parameter name.  Substitution of all array elements with
544     ${name[*]} and ${name[@]} works equivalent to $* and $@ for positional
545     parameters.  If substitution is performed on a parameter (or an array
546     parameter element) that is not set, an empty string is substituted unless
547     the nounset option (set -u) is set, in which case an error occurs.
548
549     Parameters can be assigned values in a number of ways.  First, the shell
550     implicitly sets some parameters like “#”, “PWD” and “$”; this is the only
551     way the special single character parameters are set.  Second, parameters
552     are imported from the shell's environment at startup.  Third, parameters
553     can be assigned values on the command line: for example, FOO=bar sets the
554     parameter “FOO” to “bar”; multiple parameter assignments can be given on
555     a single command line and they can be followed by a simple-command, in
556     which case the assignments are in effect only for the duration of the
557     command (such assignments are also exported; see below for the implica‐
558     tions of this).  Note that both the parameter name and the ‘=’ must be
559     unquoted for the shell to recognise a parameter assignment.  The con‐
560     struct FOO+=baz is also recognised; the old and new values are immedi‐
561     ately concatenated.  The fourth way of setting a parameter is with the
562     export, global, readonly and typeset commands; see their descriptions in
563     the Command execution section.  Fifth, for and select loops set parame‐
564     ters as well as the getopts, read and set -A commands.  Lastly, parame‐
565     ters can be assigned values using assignment operators inside arithmetic
566     expressions (see Arithmetic expressions below) or using the ${name=value}
567     form of the parameter substitution (see below).
568
569     Parameters with the export attribute (set using the export or typeset -x
570     commands, or by parameter assignments followed by simple commands) are
571     put in the environment (see environ(7)) of commands run by the shell as
572     name=value pairs.  The order in which parameters appear in the environ‐
573     ment of a command is unspecified.  When the shell starts up, it extracts
574     parameters and their values from its environment and automatically sets
575     the export attribute for those parameters.
576
577     Modifiers can be applied to the ${name} form of parameter substitution:
578
579     ${name:-word}
580             If name is set and not empty, it is substituted; otherwise, word
581             is substituted.
582
583     ${name:+word}
584             If name is set and not empty, word is substituted; otherwise,
585             nothing is substituted.
586
587     ${name:=word}
588             If name is set and not empty, it is substituted; otherwise, it is
589             assigned word and the resulting value of name is substituted.
590
591     ${name:?word}
592             If name is set and not empty, it is substituted; otherwise, word
593             is printed on standard error (preceded by name:) and an error
594             occurs (normally causing termination of a shell script, function,
595             or a script sourced using the “.” built-in).  If word is omitted,
596             the string “parameter null or not set” is used instead.
597
598     Note that, for all of the above, word is actually considered quoted, and
599     special parsing rules apply.  The parsing rules also differ on whether
600     the expression is double-quoted: word then uses double-quoting rules,
601     except for the double quote itself (‘"’) and the closing brace, which, if
602     backslash escaped, gets quote removal applied.
603
604     In the above modifiers, the ‘:’ can be omitted, in which case the condi‐
605     tions only depend on name being set (as opposed to set and not empty).
606     If word is needed, parameter, command, arithmetic and tilde substitution
607     are performed on it; if word is not needed, it is not evaluated.
608
609     The following forms of parameter substitution can also be used (if name
610     is an array, the element with the key “0” will be substituted in scalar
611     context):
612
613     ${#name}
614             The number of positional parameters if name is “*”, “@” or not
615             specified; otherwise the length (in characters) of the string
616             value of parameter name.
617
618     ${#name[*]}
619     ${#name[@]}
620             The number of elements in the array name.
621
622     ${%name}
623             The width (in screen columns) of the string value of parameter
624             name, or -1 if ${name} contains a control character.
625
626     ${!name}
627             The name of the variable referred to by name.  This will be name
628             except when name is a name reference (bound variable), created by
629             the nameref command (which is an alias for typeset -n).  name
630             cannot be one of most special parameters (see below).
631
632     ${!name[*]}
633     ${!name[@]}
634             The names of indices (keys) in the array name.
635
636     ${name#pattern}
637     ${name##pattern}
638             If pattern matches the beginning of the value of parameter name,
639             the matched text is deleted from the result of substitution.  A
640             single ‘#’ results in the shortest match, and two of them result
641             in the longest match.  Cannot be applied to a vector (${*} or
642             ${@} or ${array[*]} or ${array[@]}).
643
644     ${name%pattern}
645     ${name%%pattern}
646             Like ${...#...} substitution, but it deletes from the end of the
647             value.  Cannot be applied to a vector.
648
649     ${name/pattern/string}
650     ${name/#pattern/string}
651     ${name/%pattern/string}
652     ${name//pattern/string}
653             The longest match of pattern in the value of parameter name is
654             replaced with string (deleted if string is empty; the trailing
655             slash (‘/’) may be omitted in that case).  A leading slash fol‐
656             lowed by ‘#’ or ‘%’ causes the pattern to be anchored at the
657             beginning or end of the value, respectively; empty unanchored
658             patterns cause no replacement; a single leading slash or use of a
659             pattern that matches the empty string causes the replacement to
660             happen only once; two leading slashes cause all occurrences of
661             matches in the value to be replaced.  Cannot be applied to a vec‐
662             tor.  Inefficiently implemented, may be slow.
663
664     ${name@/pattern/string}
665             The same as ${name//pattern/string}, except that both pattern and
666             string are expanded anew for each iteration.
667
668     ${name:pos:len}
669             The first len characters of name, starting at position pos, are
670             substituted.  Both pos and :len are optional.  If pos is nega‐
671             tive, counting starts at the end of the string; if it is omitted,
672             it defaults to 0.  If len is omitted or greater than the length
673             of the remaining string, all of it is substituted.  Both pos and
674             len are evaluated as arithmetic expressions.  Currently, pos must
675             start with a space, opening parenthesis or digit to be recog‐
676             nised.  Cannot be applied to a vector.
677
678     ${name@#}
679             The hash (using the BAFH algorithm) of the expansion of name.
680             This is also used internally for the shell's hashtables.
681
682     ${name@Q}
683             A quoted expression safe for re-entry, whose value is the value
684             of the name parameter, is substituted.
685
686     Note that pattern may need extended globbing pattern (@(...)), single
687     ('...') or double ("...") quote escaping unless -o sh is set.
688
689     The following special parameters are implicitly set by the shell and can‐
690     not be set directly using assignments:
691
692     !       Process ID of the last background process started.  If no back‐
693             ground processes have been started, the parameter is not set.
694
695     #       The number of positional parameters ($1, $2, etc.).
696
697     $       The PID of the shell or, if it is a subshell, the PID of the
698             original shell.  Do NOT use this mechanism for generating tempo‐
699             rary file names; see mktemp(1) instead.
700
701     -       The concatenation of the current single letter options (see the
702             set command below for a list of options).
703
704     ?       The exit status of the last non-asynchronous command executed.
705             If the last command was killed by a signal, $? is set to 128 plus
706             the signal number, but at most 255.
707
708     0       The name of the shell, determined as follows: the first argument
709             to mksh if it was invoked with the -c option and arguments were
710             given; otherwise the file argument, if it was supplied; or else
711             the basename the shell was invoked with (i.e. argv[0]).  $0 is
712             also set to the name of the current script or the name of the
713             current function, if it was defined with the function keyword
714             (i.e. a Korn shell style function).
715
716     1 .. 9  The first nine positional parameters that were supplied to the
717             shell, function, or script sourced using the “.” built-in.  Fur‐
718             ther positional parameters may be accessed using ${number}.
719
720     *       All positional parameters (except 0), i.e. $1, $2, $3, ...
721             If used outside of double quotes, parameters are separate words
722             (which are subjected to word splitting); if used within double
723             quotes, parameters are separated by the first character of the
724             IFS parameter (or the empty string if IFS is unset.
725
726     @       Same as $*, unless it is used inside double quotes, in which case
727             a separate word is generated for each positional parameter.  If
728             there are no positional parameters, no word is generated.  "$@"
729             can be used to access arguments, verbatim, without losing empty
730             arguments or splitting arguments with spaces (IFS, actually).
731
732     The following parameters are set and/or used by the shell:
733
734     _            (underscore) When an external command is executed by the
735                  shell, this parameter is set in the environment of the new
736                  process to the path of the executed command.  In interactive
737                  use, this parameter is also set in the parent shell to the
738                  last word of the previous command.
739
740     BASHPID      The PID of the shell or subshell.
741
742     CDPATH       Like PATH, but used to resolve the argument to the cd built-
743                  in command.  Note that if CDPATH is set and does not contain
744                  “.” or an empty string element, the current directory is not
745                  searched.  Also, the cd built-in command will display the
746                  resulting directory when a match is found in any search path
747                  other than the empty path.
748
749     COLUMNS      Set to the number of columns on the terminal or window.
750                  Always set, defaults to 80, unless the value as reported by
751                  stty(1) is non-zero and sane enough (minimum is 12x3); simi‐
752                  lar for LINES.  This parameter is used by the interactive
753                  line editing modes and by the select, set -o and kill -l
754                  commands to format information columns.  Importing from the
755                  environment or unsetting this parameter removes the binding
756                  to the actual terminal size in favour of the provided value.
757
758     ENV          If this parameter is found to be set after any profile files
759                  are executed, the expanded value is used as a shell startup
760                  file.  It typically contains function and alias definitions.
761
762     EPOCHREALTIME
763                  Time since the epoch, as returned by gettimeofday(2), for‐
764                  matted as decimal tv_sec followed by a dot (‘.’) and tv_usec
765                  padded to exactly six decimal digits.
766
767     EXECSHELL    If set, this parameter is assumed to contain the shell that
768                  is to be used to execute commands that execve(2) fails to
769                  execute and which do not start with a “#!shell” sequence.
770
771     FCEDIT       The editor used by the fc command (see below).
772
773     FPATH        Like PATH, but used when an undefined function is executed
774                  to locate the file defining the function.  It is also
775                  searched when a command can't be found using PATH.  See
776                  Functions below for more information.
777
778     HISTFILE     The name of the file used to store command history.  When
779                  assigned to or unset, the file is opened, history is trun‐
780                  cated then loaded from the file; subsequent new commands
781                  (possibly consisting of several lines) are appended once
782                  they successfully compiled.  Also, several invocations of
783                  the shell will share history if their HISTFILE parameters
784                  all point to the same file.
785
786                  Note: If HISTFILE is unset or empty, no history file is
787                  used.  This is different from AT&T UNIX ksh.
788
789     HISTSIZE     The number of commands normally stored for history.  The
790                  default is 2047.  Do not set this value to insanely high
791                  values such as 1000000000 because mksh can then not allocate
792                  enough memory for the history and will not start.
793
794     HOME         The default directory for the cd command and the value sub‐
795                  stituted for an unqualified ~ (see Tilde expansion below).
796
797     IFS          Internal field separator, used during substitution and by
798                  the read command, to split values into distinct arguments;
799                  normally set to space, tab and newline.  See Substitution
800                  above for details.
801
802                  Note: This parameter is not imported from the environment
803                  when the shell is started.
804
805     KSHEGID      The effective group id of the shell.
806
807     KSHGID       The real group id of the shell.
808
809     KSHUID       The real user id of the shell.
810
811     KSH_MATCH    The last matched string.  In a future version, this will be
812                  an indexed array, with indexes 1 and up capturing matching
813                  groups.  Set by string comparisons (== and !=) in double-
814                  bracket test expressions when a match is found (when !=
815                  returns false), by case when a match is encountered, and by
816                  the substitution operations ${x#pat}, ${x##pat}, ${x%pat},
817                  ${x%%pat}, ${x/pat/rpl}, ${x/#pat/rpl}, ${x/%pat/rpl},
818                  ${x//pat/rpl}, and ${x@/pat/rpl}.  See the end of the Emacs
819                  editing mode documentation for an example.
820
821     KSH_VERSION  The name and version of the shell (read-only).  See also the
822                  version commands in Emacs editing mode and Vi editing mode
823                  sections, below.
824
825     LINENO       The line number of the function or shell script that is cur‐
826                  rently being executed.
827
828     LINES        Set to the number of lines on the terminal or window.
829                  Always set, defaults to 24.  See COLUMNS.
830
831     OLDPWD       The previous working directory.  Unset if cd has not suc‐
832                  cessfully changed directories since the shell started or if
833                  the shell doesn't know where it is.
834
835     OPTARG       When using getopts, it contains the argument for a parsed
836                  option, if it requires one.
837
838     OPTIND       The index of the next argument to be processed when using
839                  getopts.  Assigning 1 to this parameter causes getopts to
840                  process arguments from the beginning the next time it is
841                  invoked.
842
843     PATH         A colon (semicolon on OS/2) separated list of directories
844                  that are searched when looking for commands and files
845                  sourced using the “.” command (see below).  An empty string
846                  resulting from a leading or trailing (semi)colon, or two
847                  adjacent ones, is treated as a “.” (the current directory).
848
849     PATHSEP      A colon (semicolon on OS/2), for the user's convenience.
850
851     PGRP         The process ID of the shell's process group leader.
852
853     PIPESTATUS   An array containing the errorlevel (exit status) codes, one
854                  by one, of the last pipeline run in the foreground.
855
856     PPID         The process ID of the shell's parent.
857
858     PS1          The primary prompt for interactive shells.  Parameter, com‐
859                  mand and arithmetic substitutions are performed, and ‘!’ is
860                  replaced with the current command number (see the fc command
861                  below).  A literal ‘!’ can be put in the prompt by placing
862                  “!!” in PS1.
863
864                  The default prompt is “$ ” for non-root users, “# ” for
865                  root.  If mksh is invoked by root and PS1 does not contain a
866                  ‘#’ character, the default value will be used even if PS1
867                  already exists in the environment.
868
869                  The mksh distribution comes with a sample dot.mkshrc con‐
870                  taining a sophisticated example, but you might like the fol‐
871                  lowing one (note that ${HOSTNAME:=$(hostname)} and the root-
872                  vs-user distinguishing clause are (in this example) executed
873                  at PS1 assignment time, while the $USER and $PWD are escaped
874                  and thus will be evaluated each time a prompt is displayed):
875
876                  PS1='${USER:=$(id -un)}'"@${HOSTNAME:=$(hostname)}:\$PWD $(
877                          if (( USER_ID )); then print \$; else print \#; fi) "
878
879                  Note that since the command-line editors try to figure out
880                  how long the prompt is (so they know how far it is to the
881                  edge of the screen), escape codes in the prompt tend to mess
882                  things up.  You can tell the shell not to count certain
883                  sequences (such as escape codes) by prefixing your prompt
884                  with a character (such as Ctrl-A) followed by a carriage
885                  return and then delimiting the escape codes with this char‐
886                  acter.  Any occurrences of that character in the prompt are
887                  not printed.  By the way, don't blame me for this hack; it's
888                  derived from the original ksh88(1), which did print the
889                  delimiter character so you were out of luck if you did not
890                  have any non-printing characters.
891
892                  Since backslashes and other special characters may be inter‐
893                  preted by the shell, to set PS1 either escape the backslash
894                  itself or use double quotes.  The latter is more practical.
895                  This is a more complex example, avoiding to directly enter
896                  special characters (for example with ^V in the emacs editing
897                  mode), which embeds the current working directory, in
898                  reverse video (colour would work, too), in the prompt
899                  string:
900
901                        x=$(print \\001) # otherwise unused char
902                        PS1="$x$(print \\r)$x$(tput so)$x\$PWD$x$(tput se)$x> "
903
904                  Due to a strong suggestion from David G. Korn, mksh now also
905                  supports the following form:
906
907                        PS1=$'\1\r\1\e[7m\1$PWD\1\e[0m\1> '
908
909     PS2          Secondary prompt string, by default “> ”, used when more
910                  input is needed to complete a command.
911
912     PS3          Prompt used by the select statement when reading a menu
913                  selection.  The default is “#? ”.
914
915     PS4          Used to prefix commands that are printed during execution
916                  tracing (see the set -x command below).  Parameter, command
917                  and arithmetic substitutions are performed before it is
918                  printed.  The default is “+ ”.  You may want to set it to
919                  “[$EPOCHREALTIME] ” instead, to include timestamps.
920
921     PWD          The current working directory.  May be unset or empty if the
922                  shell doesn't know where it is.
923
924     RANDOM       Each time RANDOM is referenced, it is assigned a number
925                  between 0 and 32767 from a Linear Congruential PRNG first.
926
927     REPLY        Default parameter for the read command if no names are
928                  given.  Also used in select loops to store the value that is
929                  read from standard input.
930
931     SECONDS      The number of seconds since the shell started or, if the
932                  parameter has been assigned an integer value, the number of
933                  seconds since the assignment plus the value that was
934                  assigned.
935
936     TMOUT        If set to a positive integer in an interactive shell, it
937                  specifies the maximum number of seconds the shell will wait
938                  for input after printing the primary prompt (PS1).  If the
939                  time is exceeded, the shell exits.
940
941     TMPDIR       The directory temporary shell files are created in.  If this
942                  parameter is not set or does not contain the absolute path
943                  of a writable directory, temporary files are created in
944                  /tmp.
945
946     USER_ID      The effective user id of the shell.
947
948   Tilde expansion
949     Tilde expansion, which is done in parallel with parameter substitution,
950     is applied to words starting with an unquoted ‘~’.  In parameter assign‐
951     ments (such as those preceding a simple-command or those occurring in the
952     arguments of a declaration utility), tilde expansion is done after any
953     assignment (i.e. after the equals sign) or after an unquoted colon (‘:’);
954     login names are also delimited by colons.  The Korn shell, except in
955     POSIX mode, always expands tildes after unquoted equals signs, not just
956     in assignment context (see below), and enables tab completion for tildes
957     after all unquoted colons during command line editing.
958
959     The characters following the tilde, up to the first ‘/’, if any, are
960     assumed to be a login name.  If the login name is empty, ‘+’ or ‘-’, the
961     simplified value of the HOME, PWD or OLDPWD parameter is substituted,
962     respectively.  Otherwise, the password file is searched for the login
963     name, and the tilde expression is substituted with the user's home direc‐
964     tory.  If the login name is not found in the password file or if any
965     quoting or parameter substitution occurs in the login name, no substitu‐
966     tion is performed.
967
968     The home directory of previously expanded login names are cached and re-
969     used.  The alias -d command may be used to list, change and add to this
970     cache (e.g. alias -d fac=/usr/local/facilities; cd ~fac/bin).
971
972   Brace expansion (alternation)
973     Brace expressions take the following form:
974
975           prefix{str1,...,strN}suffix
976
977     The expressions are expanded to N words, each of which is the concatena‐
978     tion of prefix, stri and suffix (e.g. “a{c,b{X,Y},d}e” expands to four
979     words: “ace”, “abXe”, “abYe” and “ade”).  As noted in the example, brace
980     expressions can be nested and the resulting words are not sorted.  Brace
981     expressions must contain an unquoted comma (‘,’) for expansion to occur
982     (e.g. {} and {foo} are not expanded).  Brace expansion is carried out
983     after parameter substitution and before file name generation.
984
985   File name patterns
986     A file name pattern is a word containing one or more unquoted ‘?’, ‘*’,
987     ‘+’, ‘@’ or ‘!’ characters or “[...]” sequences.  Once brace expansion
988     has been performed, the shell replaces file name patterns with the sorted
989     names of all the files that match the pattern (if no files match, the
990     word is left unchanged).  The pattern elements have the following mean‐
991     ing:
992
993     ?       Matches any single character.
994
995     *       Matches any sequence of octets.
996
997     [...]   Matches any of the octets inside the brackets.  Ranges of octets
998             can be specified by separating two octets by a ‘-’ (e.g. “[a0-9]”
999             matches the letter ‘a’ or any digit).  In order to represent
1000             itself, a ‘-’ must either be quoted or the first or last octet in
1001             the octet list.  Similarly, a ‘]’ must be quoted or the first
1002             octet in the list if it is to represent itself instead of the end
1003             of the list.  Also, a ‘!’ appearing at the start of the list has
1004             special meaning (see below), so to represent itself it must be
1005             quoted or appear later in the list.
1006
1007     [!...]  Like [...], except it matches any octet not inside the brackets.
1008
1009     *(pattern|...|pattern)
1010             Matches any string of octets that matches zero or more occur‐
1011             rences of the specified patterns.  Example: The pattern
1012             *(foo|bar) matches the strings “”, “foo”, “bar”, “foobarfoo”,
1013             etc.
1014
1015     +(pattern|...|pattern)
1016             Matches any string of octets that matches one or more occurrences
1017             of the specified patterns.  Example: The pattern +(foo|bar)
1018             matches the strings “foo”, “bar”, “foobar”, etc.
1019
1020     ?(pattern|...|pattern)
1021             Matches the empty string or a string that matches one of the
1022             specified patterns.  Example: The pattern ?(foo|bar) only matches
1023             the strings “”, “foo” and “bar”.
1024
1025     @(pattern|...|pattern)
1026             Matches a string that matches one of the specified patterns.
1027             Example: The pattern @(foo|bar) only matches the strings “foo”
1028             and “bar”.
1029
1030     !(pattern|...|pattern)
1031             Matches any string that does not match one of the specified pat‐
1032             terns.  Examples: The pattern !(foo|bar) matches all strings
1033             except “foo” and “bar”; the pattern !(*) matches no strings; the
1034             pattern !(?)* matches all strings (think about it).
1035
1036     Note that complicated globbing, especially with alternatives, is slow;
1037     using separate comparisons may (or may not) be faster.
1038
1039     Note that mksh (and pdksh) never matches “.” and “..”, but AT&T UNIX ksh,
1040     Bourne sh and GNU bash do.
1041
1042     Note that none of the above pattern elements match either a period (‘.’)
1043     at the start of a file name or a slash (‘/’), even if they are explicitly
1044     used in a [...] sequence; also, the names “.” and “..” are never matched,
1045     even by the pattern “.*”.
1046
1047     If the markdirs option is set, any directories that result from file name
1048     generation are marked with a trailing ‘/’.
1049
1050   Input/output redirection
1051     When a command is executed, its standard input, standard output and stan‐
1052     dard error (file descriptors 0, 1 and 2, respectively) are normally
1053     inherited from the shell.  Three exceptions to this are commands in pipe‐
1054     lines, for which standard input and/or standard output are those set up
1055     by the pipeline, asynchronous commands created when job control is dis‐
1056     abled, for which standard input is initially set to /dev/null, and com‐
1057     mands for which any of the following redirections have been specified:
1058
1059     >file       Standard output is redirected to file.  If file does not
1060                 exist, it is created; if it does exist, is a regular file,
1061                 and the noclobber option is set, an error occurs; otherwise,
1062                 the file is truncated.  Note that this means the command cmd
1063                 <foo >foo will open foo for reading and then truncate it when
1064                 it opens it for writing, before cmd gets a chance to actually
1065                 read foo.
1066
1067     >|file      Same as >, except the file is truncated, even if the
1068                 noclobber option is set.
1069
1070     >>file      Same as >, except if file exists it is appended to instead of
1071                 being truncated.  Also, the file is opened in append mode, so
1072                 writes always go to the end of the file (see open(2)).
1073
1074     <file       Standard input is redirected from file, which is opened for
1075                 reading.
1076
1077     <>file      Same as <, except the file is opened for reading and writing.
1078
1079     <<marker    After reading the command line containing this kind of redi‐
1080                 rection (called a “here document”), the shell copies lines
1081                 from the command source into a temporary file until a line
1082                 matching marker is read.  When the command is executed, stan‐
1083                 dard input is redirected from the temporary file.  If marker
1084                 contains no quoted characters, the contents of the temporary
1085                 file are processed as if enclosed in double quotes each time
1086                 the command is executed, so parameter, command and arithmetic
1087                 substitutions are performed, along with backslash (‘\’)
1088                 escapes for ‘$’, ‘`’, ‘\’ and “\newline”, but not for ‘"’.
1089                 If multiple here documents are used on the same command line,
1090                 they are saved in order.
1091
1092                 If no marker is given, the here document ends at the next <<
1093                 and substitution will be performed.  If marker is only a set
1094                 of either single “''” or double ‘""’ quotes with nothing in
1095                 between, the here document ends at the next empty line and
1096                 substitution will not be performed.
1097
1098     <<-marker   Same as <<, except leading tabs are stripped from lines in
1099                 the here document.
1100
1101     <<<word     Same as <<, except that word is the here document.  This is
1102                 called a here string.
1103
1104     <&fd        Standard input is duplicated from file descriptor fd.  fd can
1105                 be a single digit, indicating the number of an existing file
1106                 descriptor; the letter ‘p’, indicating the file descriptor
1107                 associated with the output of the current co-process; or the
1108                 character ‘-’, indicating standard input is to be closed.
1109
1110     >&fd        Same as <&, except the operation is done on standard output.
1111
1112     &>file      Same as >file 2>&1.  This is a deprecated (legacy) GNU bash
1113                 extension supported by mksh which also supports the preceding
1114                 explicit fd digit, for example, 3&>file is the same as 3>file
1115                 2>&3 in mksh but a syntax error in GNU bash.
1116
1117     &>|file, &>>file, &>&fd
1118                 Same as >|file, >>file or >&fd, followed by 2>&1, as above.
1119                 These are mksh extensions.
1120
1121     In any of the above redirections, the file descriptor that is redirected
1122     (i.e. standard input or standard output) can be explicitly given by pre‐
1123     ceding the redirection with a single digit.  Parameter, command and
1124     arithmetic substitutions, tilde substitutions, and, if the shell is
1125     interactive, file name generation are all performed on the file, marker
1126     and fd arguments of redirections.  Note, however, that the results of any
1127     file name generation are only used if a single file is matched; if multi‐
1128     ple files match, the word with the expanded file name generation charac‐
1129     ters is used.  Note that in restricted shells, redirections which can
1130     create files cannot be used.
1131
1132     For simple-commands, redirections may appear anywhere in the command; for
1133     compound-commands (if statements, etc.), any redirections must appear at
1134     the end.  Redirections are processed after pipelines are created and in
1135     the order they are given, so the following will print an error with a
1136     line number prepended to it:
1137
1138           $ cat /foo/bar 2>&1 >/dev/null | pr -n -t
1139
1140     File descriptors created by I/O redirections are private to the shell.
1141
1142   Arithmetic expressions
1143     Integer arithmetic expressions can be used with the let command, inside
1144     $((...)) expressions, inside array references (e.g. name[expr]), as
1145     numeric arguments to the test command, and as the value of an assignment
1146     to an integer parameter.  Warning: This also affects implicit conversion
1147     to integer, for example as done by the let command.  Never use unchecked
1148     user input, e.g. from the environment, in an arithmetic context!
1149
1150     Expressions are calculated using signed arithmetic and the mksh_ari_t
1151     type (a 32-bit signed integer), unless they begin with a sole ‘#’ charac‐
1152     ter, in which case they use mksh_uari_t (a 32-bit unsigned integer).
1153
1154     Expressions may contain alpha-numeric parameter identifiers, array refer‐
1155     ences and integer constants and may be combined with the following C
1156     operators (listed and grouped in increasing order of precedence):
1157
1158     Unary operators:
1159
1160           + - ! ~ ++ --
1161
1162     Binary operators:
1163
1164           ,
1165           = += -= *= /= %= <<= >>= ^<= ^>= &= ^= |=
1166           ||
1167           &&
1168           |
1169           ^
1170           &
1171           == !=
1172           < <= > >=
1173           << >> ^< ^>
1174           + -
1175           * / %
1176
1177     Ternary operators:
1178
1179           ?: (precedence is immediately higher than assignment)
1180
1181     Grouping operators:
1182
1183           ( )
1184
1185     Integer constants and expressions are calculated using an exactly 32-bit
1186     wide, signed or unsigned, type with silent wraparound on integer over‐
1187     flow.  Integer constants may be specified with arbitrary bases using the
1188     notation base#number, where base is a decimal integer specifying the base
1189     (up to 36), and number is a number in the specified base.  Additionally,
1190     base-16 integers may be specified by prefixing them with “0x”
1191     (case-insensitive) in all forms of arithmetic expressions, except as
1192     numeric arguments to the test built-in utility.  Prefixing numbers with a
1193     sole digit zero (“0”) does not cause interpretation as octal (except in
1194     POSIX mode, as required by the standard), as that's unsafe to do.
1195
1196     As a special mksh extension, numbers to the base of one are treated as
1197     either (8-bit transparent) ASCII or Unicode codepoints, depending on the
1198     shell's utf8-mode flag (current setting).  The AT&T UNIX ksh93 syntax of
1199     “'x'” instead of “1#x” is also supported.  Note that NUL bytes (integral
1200     value of zero) cannot be used.  An unset or empty parameter evaluates to
1201     0 in integer context.  In Unicode mode, raw octets are mapped into the
1202     range EF80..EFFF as in OPTU-8, which is in the PUA and has been assigned
1203     by CSUR for this use.  If more than one octet in ASCII mode, or a
1204     sequence of more than one octet not forming a valid and minimal CESU-8
1205     sequence is passed, the behaviour is undefined (usually, the shell aborts
1206     with a parse error, but rarely, it succeeds, e.g. on the sequence C2 20).
1207     That's why you should always use ASCII mode unless you know that the
1208     input is well-formed UTF-8 in the range of 0000..FFFD if you use this
1209     feature, as opposed to read -a.
1210
1211     The operators are evaluated as follows:
1212
1213           unary +
1214                   Result is the argument (included for completeness).
1215
1216           unary -
1217                   Negation.
1218
1219           !       Logical NOT; the result is 1 if argument is zero, 0 if not.
1220
1221           ~       Arithmetic (bit-wise) NOT.
1222
1223           ++      Increment; must be applied to a parameter (not a literal or
1224                   other expression).  The parameter is incremented by 1.
1225                   When used as a prefix operator, the result is the incre‐
1226                   mented value of the parameter; when used as a postfix oper‐
1227                   ator, the result is the original value of the parameter.
1228
1229           --      Similar to ++, except the parameter is decremented by 1.
1230
1231           ,       Separates two arithmetic expressions; the left-hand side is
1232                   evaluated first, then the right.  The result is the value
1233                   of the expression on the right-hand side.
1234
1235           =       Assignment; the variable on the left is set to the value on
1236                   the right.
1237
1238           += -= *= /= %= <<= >>= ^<= ^>= &= ^= |=
1239                   Assignment operators.  <var><op>=<expr> is the same as
1240                   <var>=<var><op><expr>, with any operator precedence in
1241                   <expr> preserved.  For example, “var1 *= 5 + 3” is the same
1242                   as specifying “var1 = var1 * (5 + 3)”.
1243
1244           ||      Logical OR; the result is 1 if either argument is non-zero,
1245                   0 if not.  The right argument is evaluated only if the left
1246                   argument is zero.
1247
1248           &&      Logical AND; the result is 1 if both arguments are non-
1249                   zero, 0 if not.  The right argument is evaluated only if
1250                   the left argument is non-zero.
1251
1252           |       Arithmetic (bit-wise) OR.
1253
1254           ^       Arithmetic (bit-wise) XOR (exclusive-OR).
1255
1256           &       Arithmetic (bit-wise) AND.
1257
1258           ==      Equal; the result is 1 if both arguments are equal, 0 if
1259                   not.
1260
1261           !=      Not equal; the result is 0 if both arguments are equal, 1
1262                   if not.
1263
1264           <       Less than; the result is 1 if the left argument is less
1265                   than the right, 0 if not.
1266
1267           <= > >=
1268                   Less than or equal, greater than, greater than or equal.
1269                   See <.
1270
1271           << >>   Shift left (right); the result is the left argument with
1272                   its bits arithmetically (signed operation) or logically
1273                   (unsigned expression) shifted left (right) by the amount
1274                   given in the right argument.
1275
1276           ^< ^>   Rotate left (right); the result is similar to shift, except
1277                   that the bits shifted out at one end are shifted in at the
1278                   other end, instead of zero or sign bits.
1279
1280           + - * /
1281                   Addition, subtraction, multiplication and division.
1282
1283           %       Remainder; the result is the symmetric remainder of the
1284                   division of the left argument by the right.  To get the
1285                   mathematical modulus of “a mod b”, use the formula “(a % b
1286                   + b) % b”.
1287
1288           <arg1>?<arg2>:<arg3>
1289                   If <arg1> is non-zero, the result is <arg2>; otherwise the
1290                   result is <arg3>.  The non-result argument is not evalu‐
1291                   ated.
1292
1293   Co-processes
1294     A co-process (which is a pipeline created with the “|&” operator) is an
1295     asynchronous process that the shell can both write to (using print -p)
1296     and read from (using read -p).  The input and output of the co-process
1297     can also be manipulated using >&p and <&p redirections, respectively.
1298     Once a co-process has been started, another can't be started until the
1299     co-process exits, or until the co-process's input has been redirected
1300     using an exec n>&p redirection.  If a co-process's input is redirected in
1301     this way, the next co-process to be started will share the output with
1302     the first co-process, unless the output of the initial co-process has
1303     been redirected using an exec n<&p redirection.
1304
1305     Some notes concerning co-processes:
1306
1307     ·   The only way to close the co-process's input (so the co-process reads
1308         an end-of-file) is to redirect the input to a numbered file descrip‐
1309         tor and then close that file descriptor: exec 3>&p; exec 3>&-
1310
1311     ·   In order for co-processes to share a common output, the shell must
1312         keep the write portion of the output pipe open.  This means that end-
1313         of-file will not be detected until all co-processes sharing the co-
1314         process's output have exited (when they all exit, the shell closes
1315         its copy of the pipe).  This can be avoided by redirecting the output
1316         to a numbered file descriptor (as this also causes the shell to close
1317         its copy).  Note that this behaviour is slightly different from the
1318         original Korn shell which closes its copy of the write portion of the
1319         co-process output when the most recently started co-process (instead
1320         of when all sharing co-processes) exits.
1321
1322     ·   print -p will ignore SIGPIPE signals during writes if the signal is
1323         not being trapped or ignored; the same is true if the co-process
1324         input has been duplicated to another file descriptor and print -un is
1325         used.
1326
1327   Functions
1328     Functions are defined using either Korn shell function function-name syn‐
1329     tax or the Bourne/POSIX shell function-name() syntax (see below for the
1330     difference between the two forms).  Functions are like .‐scripts (i.e.
1331     scripts sourced using the “.” built-in) in that they are executed in the
1332     current environment.  However, unlike .‐scripts, shell arguments (i.e.
1333     positional parameters $1, $2, etc.) are never visible inside them.  When
1334     the shell is determining the location of a command, functions are
1335     searched after special built-in commands, before builtins and the PATH is
1336     searched.
1337
1338     An existing function may be deleted using unset -f function-name.  A list
1339     of functions can be obtained using typeset +f and the function defini‐
1340     tions can be listed using typeset -f.  The autoload command (which is an
1341     alias for typeset -fu) may be used to create undefined functions: when an
1342     undefined function is executed, the shell searches the path specified in
1343     the FPATH parameter for a file with the same name as the function which,
1344     if found, is read and executed.  If after executing the file the named
1345     function is found to be defined, the function is executed; otherwise, the
1346     normal command search is continued (i.e. the shell searches the regular
1347     built-in command table and PATH).  Note that if a command is not found
1348     using PATH, an attempt is made to autoload a function using FPATH (this
1349     is an undocumented feature of the original Korn shell).
1350
1351     Functions can have two attributes, “trace” and “export”, which can be set
1352     with typeset -ft and typeset -fx, respectively.  When a traced function
1353     is executed, the shell's xtrace option is turned on for the function's
1354     duration.  The “export” attribute of functions is currently not used.  In
1355     the original Korn shell, exported functions are visible to shell scripts
1356     that are executed.
1357
1358     Since functions are executed in the current shell environment, parameter
1359     assignments made inside functions are visible after the function com‐
1360     pletes.  If this is not the desired effect, the typeset command can be
1361     used inside a function to create a local parameter.  Note that AT&T UNIX
1362     ksh93 uses static scoping (one global scope, one local scope per func‐
1363     tion) and allows local variables only on Korn style functions, whereas
1364     mksh uses dynamic scoping (nested scopes of varying locality).  Note that
1365     special parameters (e.g. $$, $!) can't be scoped in this way.
1366
1367     The exit status of a function is that of the last command executed in the
1368     function.  A function can be made to finish immediately using the return
1369     command; this may also be used to explicitly specify the exit status.
1370     Note that when called in a subshell, return will only exit that subshell
1371     and will not cause the original shell to exit a running function (see the
1372     while...read loop FAQ below).
1373
1374     Functions defined with the function reserved word are treated differently
1375     in the following ways from functions defined with the () notation:
1376
1377     ·   The $0 parameter is set to the name of the function (Bourne-style
1378         functions leave $0 untouched).
1379
1380     ·   Parameter assignments preceding function calls are not kept in the
1381         shell environment (executing Bourne-style functions will keep assign‐
1382         ments).
1383
1384     ·   OPTIND is saved/reset and restored on entry and exit from the func‐
1385         tion so getopts can be used properly both inside and outside the
1386         function (Bourne-style functions leave OPTIND untouched, so using
1387         getopts inside a function interferes with using getopts outside the
1388         function).
1389
1390     ·   Shell options (set -o) have local scope, i.e. changes inside a func‐
1391         tion are reset upon its exit.
1392
1393     In the future, the following differences may also be added:
1394
1395     ·   A separate trap/signal environment will be used during the execution
1396         of functions.  This will mean that traps set inside a function will
1397         not affect the shell's traps and signals that are not ignored in the
1398         shell (but may be trapped) will have their default effect in a func‐
1399         tion.
1400
1401     ·   The EXIT trap, if set in a function, will be executed after the func‐
1402         tion returns.
1403
1404   Command execution
1405     After evaluation of command-line arguments, redirections and parameter
1406     assignments, the type of command is determined: a special built-in com‐
1407     mand, a function, a normal builtin or the name of a file to execute found
1408     using the PATH parameter.  The checks are made in the above order.  Spe‐
1409     cial built-in commands differ from other commands in that the PATH param‐
1410     eter is not used to find them, an error during their execution can cause
1411     a non-interactive shell to exit, and parameter assignments that are spec‐
1412     ified before the command are kept after the command completes.  Regular
1413     built-in commands are different only in that the PATH parameter is not
1414     used to find them.
1415
1416     The original ksh and POSIX differ somewhat in which commands are consid‐
1417     ered special or regular.
1418
1419     POSIX special built-in utilities:
1420
1421     ., :, break, continue, eval, exec, exit, export, readonly, return, set,
1422     shift, times, trap, unset
1423
1424     Additional mksh commands keeping assignments:
1425
1426     global, source, typeset
1427
1428     Builtins that are not special:
1429
1430     [, alias, bg, bind, builtin, cat, cd, command, echo, false, fc, fg,
1431     getopts, jobs, kill, let, print, pwd, read, realpath, rename, sleep,
1432     suspend, test, true, ulimit, umask, unalias, wait, whence
1433
1434     Once the type of command has been determined, any command-line parameter
1435     assignments are performed and exported for the duration of the command.
1436
1437     The following describes the special and regular built-in commands and
1438     builtin-like reserved words:
1439
1440     . file [arg ...]
1441            This is called the “dot” command.  Execute the commands in file in
1442            the current environment.  The file is searched for in the directo‐
1443            ries of PATH.  If arguments are given, the positional parameters
1444            may be used to access them while file is being executed.  If no
1445            arguments are given, the positional parameters are those of the
1446            environment the command is used in.
1447
1448     : [...]
1449            The null command.  Exit status is set to zero.
1450
1451     [ expression ]
1452            See test.
1453
1454     alias [-d | -t [-r] | +-x] [-p] [+] [name [=value] ...]
1455            Without arguments, alias lists all aliases.  For any name without
1456            a value, the existing alias is listed.  Any name with a value
1457            defines an alias; see Aliases above.  [][A-Za-z0-9_!%,.@:-] are
1458            valid in names, except they may not begin with a hyphen-minus, and
1459            [[ is not a valid alias name.
1460
1461            When listing aliases, one of two formats is used.  Normally,
1462            aliases are listed as name=value, where value is quoted.  If
1463            options were preceded with ‘+’, or a lone ‘+’ is given on the com‐
1464            mand line, only name is printed.
1465
1466            The -d option causes directory aliases which are used in tilde
1467            expansion to be listed or set (see Tilde expansion above).
1468
1469            If the -p option is used, each alias is prefixed with the string
1470            “alias ”.
1471
1472            The -t option indicates that tracked aliases are to be listed/set
1473            (values specified on the command line are ignored for tracked
1474            aliases).  The -r option indicates that all tracked aliases are to
1475            be reset.
1476
1477            The -x option sets (+x clears) the export attribute of an alias,
1478            or, if no names are given, lists the aliases with the export
1479            attribute (exporting an alias has no effect).
1480
1481     bg [job ...]
1482            Resume the specified stopped job(s) in the background.  If no jobs
1483            are specified, %+ is assumed.  See Job control below for more
1484            information.
1485
1486     bind [-l]
1487            The current bindings are listed.  If the -l flag is given, bind
1488            instead lists the names of the functions to which keys may be
1489            bound.  See Emacs editing mode for more information.
1490
1491     bind [-m] string=[substitute] ...
1492     bind string=[editing-command] ...
1493            The specified editing command is bound to the given string, which
1494            should consist of a control character optionally preceded by one
1495            of the two prefix characters and optionally succeeded by a tilde
1496            character.  Future input of the string will cause the editing com‐
1497            mand to be immediately invoked.  If the -m flag is given, the
1498            specified input string will afterwards be immediately replaced by
1499            the given substitute string which may contain editing commands but
1500            not other macros.  If a tilde postfix is given, a tilde trailing
1501            the one or two prefices and the control character is ignored, any
1502            other trailing character will be processed afterwards.
1503
1504            Control characters may be written using caret notation i.e. ^X
1505            represents Ctrl-X.  The caret itself can be escaped by a back‐
1506            slash, which also escapes itself.  Note that although only three
1507            prefix characters (usually ESC, ^X and NUL) are supported, some
1508            multi-character sequences can be supported.
1509
1510            The following default bindings show how the arrow keys, the home,
1511            end and delete key on a BSD wsvt25, xterm-xfree86 or GNU screen
1512            terminal are bound (of course some escape sequences won't work out
1513            quite this nicely):
1514
1515                  bind '^X'=prefix-2
1516                  bind '^[['=prefix-2
1517                  bind '^XA'=up-history
1518                  bind '^XB'=down-history
1519                  bind '^XC'=forward-char
1520                  bind '^XD'=backward-char
1521                  bind '^X1~'=beginning-of-line
1522                  bind '^X7~'=beginning-of-line
1523                  bind '^XH'=beginning-of-line
1524                  bind '^X4~'=end-of-line
1525                  bind '^X8~'=end-of-line
1526                  bind '^XF'=end-of-line
1527                  bind '^X3~'=delete-char-forward
1528
1529     break [level]
1530            Exit the levelth inner-most for, select, until or while loop.
1531            level defaults to 1.
1532
1533     builtin [--] command [arg ...]
1534            Execute the built-in command command.
1535
1536     \builtin command [arg ...]
1537            Same as builtin.  Additionally acts as declaration utility for‐
1538            warder, i.e. this is a declaration utility (see Tilde expansion)
1539            iff command is a declaration utility.
1540
1541     cat [-u] [file ...]
1542            Read files sequentially, in command line order, and write them to
1543            standard output.  If a file is a single dash (“-”) or absent, read
1544            from standard input.  For direct builtin calls, the POSIX -u
1545            option is supported as a no-op.  For calls from shell, if any
1546            options are given, an external cat(1) utility is preferred over
1547            the builtin.
1548
1549     cd [-L] [dir]
1550     cd -P [-e] [dir]
1551     chdir [-eLP] [dir]
1552            Set the working directory to dir.  If the parameter CDPATH is set,
1553            it lists the search path for the directory containing dir.  An
1554            unset or empty path means the current directory.  If dir is found
1555            in any component of the CDPATH search path other than an unset or
1556            empty path, the name of the new working directory will be written
1557            to standard output.  If dir is missing, the home directory HOME is
1558            used.  If dir is “-”, the previous working directory is used (see
1559            the OLDPWD parameter).
1560
1561            If the -L option (logical path) is used or if the physical option
1562            isn't set (see the set command below), references to “..” in dir
1563            are relative to the path used to get to the directory.  If the -P
1564            option (physical path) is used or if the physical option is set,
1565            “..” is relative to the filesystem directory tree.  The PWD and
1566            OLDPWD parameters are updated to reflect the current and old work‐
1567            ing directory, respectively.  If the -e option is set for physical
1568            filesystem traversal and PWD could not be set, the exit code is 1;
1569            greater than 1 if an error occurred, 0 otherwise.
1570
1571     cd [-eLP] old new
1572     chdir [-eLP] old new
1573            The string new is substituted for old in the current directory,
1574            and the shell attempts to change to the new directory.
1575
1576     command [-pVv] cmd [arg ...]
1577            If neither the -v nor -V option is given, cmd is executed exactly
1578            as if command had not been specified, with two exceptions:
1579            firstly, cmd cannot be a shell function; and secondly, special
1580            built-in commands lose their specialness (i.e. redirection and
1581            utility errors do not cause the shell to exit, and command assign‐
1582            ments are not permanent).  The declaration utility property is not
1583            reset.
1584
1585            If the -p option is given, a default search path is used instead
1586            of the current value of PATH, the actual value of which is system
1587            dependent.
1588
1589            If the -v option is given, instead of executing cmd, information
1590            about what would be executed is given (and the same is done for
1591            arg ...).  For builtins, functions and keywords, their names are
1592            simply printed; for aliases, a command that defines them is
1593            printed; for utilities found by searching the PATH parameter, the
1594            full path of the command is printed.  If no command is found (i.e.
1595            the path search fails), nothing is printed and command exits with
1596            a non-zero status.  The -V option is like the -v option, except it
1597            is more verbose.
1598
1599     continue [level]
1600            Jumps to the beginning of the levelth inner-most for, select,
1601            until or while loop.  level defaults to 1.
1602
1603     echo [-Een] [arg ...]
1604            Warning: this utility is not portable; use the Korn shell builtin
1605            print instead.
1606
1607            Prints its arguments (separated by spaces) followed by a newline,
1608            to the standard output.  The newline is suppressed if any of the
1609            arguments contain the backslash sequence “\c”.  See the print com‐
1610            mand below for a list of other backslash sequences that are recog‐
1611            nised.
1612
1613            The options are provided for compatibility with BSD shell scripts.
1614            The -n option suppresses the trailing newline, -e enables back‐
1615            slash interpretation (a no-op, since this is normally done), and
1616            -E suppresses backslash interpretation.
1617
1618            If the posix or sh option is set or this is a direct builtin call
1619            or print -R, only the first argument is treated as an option, and
1620            only if it is exactly “-n”.  Backslash interpretation is disabled.
1621
1622     eval command ...
1623            The arguments are concatenated (with spaces between them) to form
1624            a single string which the shell then parses and executes in the
1625            current environment.
1626
1627     exec [-a argv0] [-c] [command [arg ...]]
1628            The command is executed without forking, replacing the shell
1629            process.  This is currently absolute, i.e. exec never returns,
1630            even if the command is not found.  The -a option permits setting a
1631            different argv[0] value, and -c clears the environment before exe‐
1632            cuting the child process, except for the _ variable and direct
1633            assignments.
1634
1635            If no command is given except for I/O redirection, the I/O redi‐
1636            rection is permanent and the shell is not replaced.  Any file
1637            descriptors greater than 2 which are opened or dup(2)'d in this
1638            way are not made available to other executed commands (i.e. com‐
1639            mands that are not built-in to the shell).  Note that the Bourne
1640            shell differs here; it does pass these file descriptors on.
1641
1642     exit [status]
1643            The shell or subshell exits with the specified exit status.  If
1644            status is not specified, the exit status is the current value of
1645            the $? parameter.
1646
1647     export [-p] [parameter[=value]]
1648            Sets the export attribute of the named parameters.  Exported
1649            parameters are passed in the environment to executed commands.  If
1650            values are specified, the named parameters are also assigned.
1651            This is a declaration utility.
1652
1653            If no parameters are specified, all parameters with the export
1654            attribute set are printed one per line; either their names, or, if
1655            a “-” with no option letter is specified, name=value pairs, or,
1656            with -p, export commands suitable for re-entry.
1657
1658     false  A command that exits with a non-zero status.
1659
1660     fc [-e editor | -l [-n]] [-r] [first [last]]
1661            first and last select commands from the history.  Commands can be
1662            selected by history number (negative numbers go backwards from the
1663            current, most recent, line) or a string specifying the most recent
1664            command starting with that string.  The -l option lists the com‐
1665            mand on standard output, and -n inhibits the default command num‐
1666            bers.  The -r option reverses the order of the list.  Without -l,
1667            the selected commands are edited by the editor specified with the
1668            -e option or, if no -e is specified, the editor specified by the
1669            FCEDIT parameter (if this parameter is not set, /bin/ed is used),
1670            and then executed by the shell.
1671
1672     fc -e - | -s [-g] [old=new] [prefix]
1673            Re-execute the selected command (the previous command by default)
1674            after performing the optional substitution of old with new.  If -g
1675            is specified, all occurrences of old are replaced with new.  The
1676            meaning of -e - and -s is identical: re-execute the selected com‐
1677            mand without invoking an editor.  This command is usually accessed
1678            with the predefined: alias r='fc -e -'
1679
1680     fg [job ...]
1681            Resume the specified job(s) in the foreground.  If no jobs are
1682            specified, %+ is assumed.  See Job control below for more informa‐
1683            tion.
1684
1685     getopts optstring name [arg ...]
1686            Used by shell procedures to parse the specified arguments (or
1687            positional parameters, if no arguments are given) and to check for
1688            legal options.  optstring contains the option letters that getopts
1689            is to recognise.  If a letter is followed by a colon, the option
1690            is expected to have an argument.  Options that do not take argu‐
1691            ments may be grouped in a single argument.  If an option takes an
1692            argument and the option character is not the last character of the
1693            argument it is found in, the remainder of the argument is taken to
1694            be the option's argument; otherwise, the next argument is the
1695            option's argument.
1696
1697            Each time getopts is invoked, it places the next option in the
1698            shell parameter name and the index of the argument to be processed
1699            by the next call to getopts in the shell parameter OPTIND.  If the
1700            option was introduced with a ‘+’, the option placed in name is
1701            prefixed with a ‘+’.  When an option requires an argument, getopts
1702            places it in the shell parameter OPTARG.
1703
1704            When an illegal option or a missing option argument is encoun‐
1705            tered, a question mark or a colon is placed in name (indicating an
1706            illegal option or missing argument, respectively) and OPTARG is
1707            set to the option character that caused the problem.  Furthermore,
1708            if optstring does not begin with a colon, a question mark is
1709            placed in name, OPTARG is unset, and an error message is printed
1710            to standard error.
1711
1712            When the end of the options is encountered, getopts exits with a
1713            non-zero exit status.  Options end at the first (non-option argu‐
1714            ment) argument that does not start with a ‘-’, or when a “--”
1715            argument is encountered.
1716
1717            Option parsing can be reset by setting OPTIND to 1 (this is done
1718            automatically whenever the shell or a shell procedure is invoked).
1719
1720            Warning: Changing the value of the shell parameter OPTIND to a
1721            value other than 1 or parsing different sets of arguments without
1722            resetting OPTIND may lead to unexpected results.
1723
1724     global [+-aglpnrtUux] [-L[n] | -R[n] | -Z[n]] [-i[n]] [name [=value] ...]
1725            See typeset -g.  Deprecated, will be removed from a future version
1726            of mksh.
1727
1728     hash [-r] [name ...]
1729            Without arguments, any hashed executable command pathnames are
1730            listed.  The -r option causes all hashed commands to be removed
1731            from the hash table.  Each name is searched as if it were a com‐
1732            mand name and added to the hash table if it is an executable com‐
1733            mand.
1734
1735     jobs [-lnp] [job ...]
1736            Display information about the specified job(s); if no jobs are
1737            specified, all jobs are displayed.  The -n option causes informa‐
1738            tion to be displayed only for jobs that have changed state since
1739            the last notification.  If the -l option is used, the process ID
1740            of each process in a job is also listed.  The -p option causes
1741            only the process group of each job to be printed.  See Job control
1742            below for the format of job and the displayed job.
1743
1744     kill [-s signame | -signum | -signame] { job | pid | pgrp } ...
1745            Send the specified signal to the specified jobs, process IDs or
1746            process groups.  If no signal is specified, the TERM signal is
1747            sent.  If a job is specified, the signal is sent to the job's
1748            process group.  See Job control below for the format of job.
1749
1750     kill -l [exit-status ...]
1751            Print the signal name corresponding to exit-status.  If no argu‐
1752            ments are specified, a list of all the signals with their numbers
1753            and a short description of each are printed.
1754
1755     let [expression ...]
1756            Each expression is evaluated (see Arithmetic expressions above).
1757            If all expressions are successfully evaluated, the exit status is
1758            0 (1) if the last expression evaluated to non-zero (zero).  If an
1759            error occurs during the parsing or evaluation of an expression,
1760            the exit status is greater than 1.  Since expressions may need to
1761            be quoted, (( expr )) is syntactic sugar for:
1762                  { \\builtin let 'expr'; }
1763
1764     mknod [-m mode] name b|c major minor
1765     mknod [-m mode] name p
1766            Create a device special file.  The file type may be b (block type
1767            device), c (character type device) or p (named pipe, FIFO).  The
1768            file created may be modified according to its mode (via the -m
1769            option), major (major device number), and minor (minor device num‐
1770            ber).  This is not normally part of mksh; however, distributors
1771            may have added this as builtin as a speed hack.
1772
1773     print [-AcelNnprsu[n] | -R [-n]] [argument ...]
1774            Print the specified argument(s) on the standard output, separated
1775            by spaces, terminated with a newline.  The escapes mentioned in
1776            Backslash expansion above, as well as “\c”, which is equivalent to
1777            using the -n option, are interpreted.
1778
1779            The options are as follows:
1780
1781            -A      Each argument is arithmetically evaluated; the character
1782                    corresponding to the resulting value is printed.  Empty
1783                    arguments separate input words.
1784
1785            -c      The output is printed columnised, line by line, similar to
1786                    how the rs(1) utility, tab completion, the kill -l built-
1787                    in utility and the select statement do.
1788
1789            -e      Restore backslash expansion after a previous -r.
1790
1791            -l      Change the output word separator to newline.
1792
1793            -N      Change the output word and line separator to ASCII NUL.
1794
1795            -n      Do not print the trailing line separator.
1796
1797            -p      Print to the co-process (see Co-processes above).
1798
1799            -r      Inhibit backslash expansion.
1800
1801            -s      Print to the history file instead of standard output.
1802
1803            -u[n]   Print to the file descriptor n (defaults to 1 if omitted)
1804                    instead of standard output.
1805
1806            The -R option mostly emulates the BSD echo(1) command which does
1807            not expand backslashes and interprets its first argument as option
1808            only if it is exactly “-n” (to suppress the trailing newline).
1809
1810     pwd [-LP]
1811            Print the present working directory.  If the -L option is used or
1812            if the physical option isn't set (see the set command below), the
1813            logical path is printed (i.e. the path used to cd to the current
1814            directory).  If the -P option (physical path) is used or if the
1815            physical option is set, the path determined from the filesystem
1816            (by following “..” directories to the root directory) is printed.
1817
1818     read [-A | -a] [-d x] [-N z | -n z] [-p | -u[n]] [-t n] [-rs] [p ...]
1819            Reads a line of input, separates the input into fields using the
1820            IFS parameter (see Substitution above), and assigns each field to
1821            the specified parameters p.  If no parameters are specified, the
1822            REPLY parameter is used to store the result.  With the -A and -a
1823            options, only no or one parameter is accepted.  If there are more
1824            parameters than fields, the extra parameters are set to the empty
1825            string or 0; if there are more fields than parameters, the last
1826            parameter is assigned the remaining fields (including the word
1827            separators).
1828
1829            The options are as follows:
1830
1831            -A     Store the result into the parameter p (or REPLY) as array
1832                   of words.
1833
1834            -a     Store the result without word splitting into the parameter
1835                   p (or REPLY) as array of characters (wide characters if the
1836                   utf8-mode option is enacted, octets otherwise); the code‐
1837                   points are encoded as decimal numbers by default.
1838
1839            -d x   Use the first byte of x, NUL if empty, instead of the ASCII
1840                   newline character as input line delimiter.
1841
1842            -N z   Instead of reading till end-of-line, read exactly z bytes.
1843                   Upon EOF, a partial read is returned with exit status 1.
1844                   After timeout, a partial read is returned with an exit sta‐
1845                   tus as if SIGALRM were caught.
1846
1847            -n z   Instead of reading till end-of-line, read up to z bytes but
1848                   return as soon as any bytes are read, e.g. from a slow ter‐
1849                   minal device, or if EOF or a timeout occurs.
1850
1851            -p     Read from the currently active co-process, see Co-processes
1852                   above for details on this.
1853
1854            -u[n]  Read from the file descriptor n (defaults to 0, i.e. stan‐
1855                   dard input).  The argument must immediately follow the
1856                   option character.
1857
1858            -t n   Interrupt reading after n seconds (specified as positive
1859                   decimal value with an optional fractional part).  The exit
1860                   status of read is the same as if SIGALRM were caught if the
1861                   timeout occurred, but partial reads may still be returned.
1862
1863            -r     Normally, the ASCII backslash character escapes the special
1864                   meaning of the following character and is stripped from the
1865                   input; read does not stop when encountering a backslash-
1866                   newline sequence and does not store that newline in the
1867                   result.  This option enables raw mode, in which backslashes
1868                   are not processed.
1869
1870            -s     The input line is saved to the history.
1871
1872            If the input is a terminal, both the -N and -n options set it into
1873            raw mode; they read an entire file if -1 is passed as z argument.
1874
1875            The first parameter may have a question mark and a string appended
1876            to it, in which case the string is used as a prompt (printed to
1877            standard error before any input is read) if the input is a tty(4)
1878            (e.g. read nfoo?'number of foos: ').
1879
1880            If no input is read or a timeout occurred, read exits with a non-
1881            zero status.
1882
1883     readonly [-p] [parameter [=value] ...]
1884            Sets the read-only attribute of the named parameters.  This is a
1885            declaration utility.  If values are given, parameters are set to
1886            them before setting the attribute.  Once a parameter is made read-
1887            only, it cannot be unset and its value cannot be changed.
1888
1889            If no parameters are specified, the names of all parameters with
1890            the read-only attribute are printed one per line, unless the -p
1891            option is used, in which case readonly commands defining all read-
1892            only parameters, including their values, are printed.
1893
1894     realpath [--] name
1895            Prints the resolved absolute pathname corresponding to name.  If
1896            name ends with a slash (‘/’), it's also checked for existence and
1897            whether it is a directory; otherwise, realpath returns 0 if the
1898            pathname either exists or can be created immediately, i.e. all but
1899            the last component exist and are directories.  For calls from the
1900            shell, if any options are given, an external realpath(1) utility
1901            is preferred over the builtin.
1902
1903     rename [--] from to
1904            Renames the file from to to.  Both must be complete pathnames and
1905            on the same device.  An external utility is preferred over this
1906            builtin, which is intended for emergency situations (where /bin/mv
1907            becomes unusable) and directly calls rename(2).
1908
1909     return [status]
1910            Returns from a function or . script, with exit status status.  If
1911            no status is given, the exit status of the last executed command
1912            is used.  If used outside of a function or . script, it has the
1913            same effect as exit.  Note that mksh treats both profile and ENV
1914            files as . scripts, while the original Korn shell only treats pro‐
1915            files as . scripts.
1916
1917     set [+-abCefhiklmnprsUuvXx] [+-o option] [+-A name] [--] [arg ...]
1918            The set command can be used to set (-) or clear (+) shell options,
1919            set the positional parameters, or set an array parameter.  Options
1920            can be changed using the +-o option syntax, where option is the
1921            long name of an option, or using the +-letter syntax, where letter
1922            is the option's single letter name (not all options have a single
1923            letter name).  The following table lists both option letters (if
1924            they exist) and long names along with a description of what the
1925            option does:
1926
1927            -A name
1928                 Sets the elements of the array parameter name to arg ... If
1929                 -A is used, the array is reset (i.e. emptied) first; if +A is
1930                 used, the first N elements are set (where N is the number of
1931                 arguments); the rest are left untouched.
1932
1933                 An alternative syntax for the command set -A foo -- a b c
1934                 which is compatible to GNU bash and also supported by AT&T
1935                 UNIX ksh93 is: foo=(a b c); foo+=(d e)
1936
1937            -a | -o allexport
1938                 All new parameters are created with the export attribute.
1939
1940            -b | -o notify
1941                 Print job notification messages asynchronously, instead of
1942                 just before the prompt.  Only used if job control is enabled
1943                 (-m).
1944
1945            -C | -o noclobber
1946                 Prevent > redirection from overwriting existing files.
1947                 Instead, >| must be used to force an overwrite.  Note that
1948                 this is not safe to use for creation of temporary files or
1949                 lockfiles due to a TOCTOU in a check allowing one to redirect
1950                 output to /dev/null or other device files even in noclobber
1951                 mode.
1952
1953            -e | -o errexit
1954                 Exit (after executing the ERR trap) as soon as an error
1955                 occurs or a command fails (i.e. exits with a non-zero sta‐
1956                 tus).  This does not apply to commands whose exit status is
1957                 explicitly tested by a shell construct such as if, until,
1958                 while or ! statements.  For && or ||, only the status of the
1959                 last command is tested.
1960
1961            -f | -o noglob
1962                 Do not expand file name patterns.
1963
1964            -h | -o trackall
1965                 Create tracked aliases for all executed commands (see Aliases
1966                 above).  Enabled by default for non-interactive shells.
1967
1968            -i | -o interactive
1969                 The shell is an interactive shell.  This option can only be
1970                 used when the shell is invoked.  See above for a description
1971                 of what this means.
1972
1973            -k | -o keyword
1974                 Parameter assignments are recognised anywhere in a command.
1975
1976            -l | -o login
1977                 The shell is a login shell.  This option can only be used
1978                 when the shell is invoked.  See above for a description of
1979                 what this means.
1980
1981            -m | -o monitor
1982                 Enable job control (default for interactive shells).
1983
1984            -n | -o noexec
1985                 Do not execute any commands.  Useful for checking the syntax
1986                 of scripts (ignored if interactive).
1987
1988            -p | -o privileged
1989                 The shell is a privileged shell.  It is set automatically if,
1990                 when the shell starts, the real UID or GID does not match the
1991                 effective UID (EUID) or GID (EGID), respectively.  See above
1992                 for a description of what this means.
1993
1994            -r | -o restricted
1995                 The shell is a restricted shell.  This option can only be
1996                 used when the shell is invoked.  See above for a description
1997                 of what this means.
1998
1999            -s | -o stdin
2000                 If used when the shell is invoked, commands are read from
2001                 standard input.  Set automatically if the shell is invoked
2002                 with no arguments.
2003
2004                 When -s is used with the set command it causes the specified
2005                 arguments to be sorted before assigning them to the posi‐
2006                 tional parameters (or to array name, if -A is used).
2007
2008            -U | -o utf8-mode
2009                 Enable UTF-8 support in the Emacs editing mode and internal
2010                 string handling functions.  This flag is disabled by default,
2011                 but can be enabled by setting it on the shell command line;
2012                 is enabled automatically for interactive shells if requested
2013                 at compile time, your system supports setlocale(LC_CTYPE, "")
2014                 and optionally nl_langinfo(CODESET), or the LC_ALL, LC_CTYPE
2015                 or LANG environment variables, and at least one of these
2016                 returns something that matches “UTF-8” or “utf8” case-insen‐
2017                 sitively; for direct builtin calls depending on the aforemen‐
2018                 tioned environment variables; or for stdin or scripts, if the
2019                 input begins with a UTF-8 Byte Order Mark.
2020
2021                 In near future, locale tracking will be implemented, which
2022                 means that set -+U is changed whenever one of the POSIX
2023                 locale-related environment variables changes.
2024
2025            -u | -o nounset
2026                 Referencing of an unset parameter, other than “$@” or “$*”,
2027                 is treated as an error, unless one of the ‘-’, ‘+’ or ‘=’
2028                 modifiers is used.
2029
2030            -v | -o verbose
2031                 Write shell input to standard error as it is read.
2032
2033            -X | -o markdirs
2034                 Mark directories with a trailing ‘/’ during file name genera‐
2035                 tion.
2036
2037            -x | -o xtrace
2038                 Print command trees when they are executed, preceded by the
2039                 value of PS4.
2040
2041            -o bgnice
2042                 Background jobs are run with lower priority.
2043
2044            -o braceexpand
2045                 Enable brace expansion (a.k.a. alternation).  This is enabled
2046                 by default.
2047
2048            -o emacs
2049                 Enable BRL emacs-like command-line editing (interactive
2050                 shells only); see Emacs editing mode.
2051
2052            -o gmacs
2053                 Enable gmacs-like command-line editing (interactive shells
2054                 only).  Currently identical to emacs editing except that
2055                 transpose-chars (^T) acts slightly differently.
2056
2057            -o ignoreeof
2058                 The shell will not (easily) exit when end-of-file is read;
2059                 exit must be used.  To avoid infinite loops, the shell will
2060                 exit if EOF is read 13 times in a row.
2061
2062            -o inherit-xtrace
2063                 Do not reset -o xtrace upon entering functions.  This is
2064                 enabled by default.
2065
2066            -o nohup
2067                 Do not kill running jobs with a SIGHUP signal when a login
2068                 shell exits.  Currently set by default, but this may change
2069                 in the future to be compatible with AT&T UNIX ksh, which
2070                 doesn't have this option, but does send the SIGHUP signal.
2071
2072            -o nolog
2073                 No effect.  In the original Korn shell, this prevents func‐
2074                 tion definitions from being stored in the history file.
2075
2076            -o physical
2077                 Causes the cd and pwd commands to use “physical” (i.e. the
2078                 filesystem's) “..” directories instead of “logical” directo‐
2079                 ries (i.e. the shell handles “..”, which allows the user to
2080                 be oblivious of symbolic links to directories).  Clear by
2081                 default.  Note that setting this option does not affect the
2082                 current value of the PWD parameter; only the cd command
2083                 changes PWD.  See the cd and pwd commands above for more
2084                 details.
2085
2086            -o pipefail
2087                 Make the exit status of a pipeline (before logically comple‐
2088                 menting) the rightmost non-zero errorlevel, or zero if all
2089                 commands exited with zero.
2090
2091            -o posix
2092                 Behave closer to the standards (see POSIX mode for details).
2093                 Automatically enabled if the basename of the shell invocation
2094                 begins with “sh” and this autodetection feature is compiled
2095                 in (not in MirBSD).  As a side effect, setting this flag
2096                 turns off the braceexpand and utf8-mode flags, which can be
2097                 turned back on manually, and sh mode (unless both are enabled
2098                 at the same time).
2099
2100            -o sh
2101                 Enable /bin/sh (kludge) mode (see SH mode).  Automatically
2102                 enabled if the basename of the shell invocation begins with
2103                 “sh” and this autodetection feature is compiled in (not in
2104                 MirBSD).  As a side effect, setting this flag turns off
2105                 braceexpand mode, which can be turned back on manually, and
2106                 posix mode (unless both are enabled at the same time).
2107
2108            -o vi
2109                 Enable vi(1)-like command-line editing (interactive shells
2110                 only).  See Vi editing mode for documentation and limita‐
2111                 tions.
2112
2113            -o vi-esccomplete
2114                 In vi command-line editing, do command and file name comple‐
2115                 tion when escape (^[) is entered in command mode.
2116
2117            -o vi-tabcomplete
2118                 In vi command-line editing, do command and file name comple‐
2119                 tion when tab (^I) is entered in insert mode.  This is the
2120                 default.
2121
2122            -o viraw
2123                 No effect.  In the original Korn shell, unless viraw was set,
2124                 the vi command-line mode would let the tty(4) driver do the
2125                 work until ESC (^[) was entered.  mksh is always in viraw
2126                 mode.
2127
2128            These options can also be used upon invocation of the shell.  The
2129            current set of options (with single letter names) can be found in
2130            the parameter “$-”.  set -o with no option name will list all the
2131            options and whether each is on or off; set +o will print the long
2132            names of all options that are currently on.  In a future version,
2133            set +o will behave POSIX compliant and print commands to restore
2134            the current options instead.
2135
2136            Remaining arguments, if any, are positional parameters and are
2137            assigned, in order, to the positional parameters (i.e. $1, $2,
2138            etc.).  If options end with “--” and there are no remaining argu‐
2139            ments, all positional parameters are cleared.  If no options or
2140            arguments are given, the values of all names are printed.  For
2141            unknown historical reasons, a lone “-” option is treated specially
2142            – it clears both the -v and -x options.
2143
2144     shift [number]
2145            The positional parameters number+1, number+2, etc. are renamed to
2146            1, 2, etc.  number defaults to 1.
2147
2148     sleep seconds
2149            Suspends execution for a minimum of the seconds specified as posi‐
2150            tive decimal value with an optional fractional part.  Signal
2151            delivery may continue execution earlier.
2152
2153     source file [arg ...]
2154            Like . (“dot”), except that the current working directory is
2155            appended to the search path (GNU bash extension).
2156
2157     suspend
2158            Stops the shell as if it had received the suspend character from
2159            the terminal.  It is not possible to suspend a login shell unless
2160            the parent process is a member of the same terminal session but is
2161            a member of a different process group.  As a general rule, if the
2162            shell was started by another shell or via su(1), it can be sus‐
2163            pended.
2164
2165     test expression
2166     [ expression ]
2167            test evaluates the expression and returns zero status if true, 1
2168            if false, or greater than 1 if there was an error.  It is normally
2169            used as the condition command of if and while statements.  Sym‐
2170            bolic links are followed for all file expressions except -h and
2171            -L.
2172
2173            The following basic expressions are available:
2174
2175            -a file            file exists.
2176
2177            -b file            file is a block special device.
2178
2179            -c file            file is a character special device.
2180
2181            -d file            file is a directory.
2182
2183            -e file            file exists.
2184
2185            -f file            file is a regular file.
2186
2187            -G file            file's group is the shell's effective group ID.
2188
2189            -g file            file's mode has the setgid bit set.
2190
2191            -H file            file is a context dependent directory (only
2192                               useful on HP-UX).
2193
2194            -h file            file is a symbolic link.
2195
2196            -k file            file's mode has the sticky(8) bit set.
2197
2198            -L file            file is a symbolic link.
2199
2200            -O file            file's owner is the shell's effective user ID.
2201
2202            -p file            file is a named pipe (FIFO).
2203
2204            -r file            file exists and is readable.
2205
2206            -S file            file is a unix(4)-domain socket.
2207
2208            -s file            file is not empty.
2209
2210            -t fd              File descriptor fd is a tty(4) device.
2211
2212            -u file            file's mode has the setuid bit set.
2213
2214            -w file            file exists and is writable.
2215
2216            -x file            file exists and is executable.
2217
2218            file1 -nt file2    file1 is newer than file2 or file1 exists and
2219                               file2 does not.
2220
2221            file1 -ot file2    file1 is older than file2 or file2 exists and
2222                               file1 does not.
2223
2224            file1 -ef file2    file1 is the same file as file2.
2225
2226            string             string has non-zero length.
2227
2228            -n string          string is not empty.
2229
2230            -z string          string is empty.
2231
2232            -v name            The shell parameter name is set.
2233
2234            -o option          Shell option is set (see the set command above
2235                               for a list of options).  As a non-standard
2236                               extension, if the option starts with a ‘!’, the
2237                               test is negated; the test always fails if
2238                               option doesn't exist (so [ -o foo -o -o !foo ]
2239                               returns true if and only if option foo exists).
2240                               The same can be achieved with [ -o ?foo ] like
2241                               in AT&T UNIX ksh93.  option can also be the
2242                               short flag led by either ‘-’ or ‘+’ (no logical
2243                               negation), for example “-x” or “+x” instead of
2244                               “xtrace”.
2245
2246            string = string    Strings are equal.
2247
2248            string == string   Strings are equal.
2249
2250            string > string    First string operand is greater than second
2251                               string operand.
2252
2253            string < string    First string operand is less than second string
2254                               operand.
2255
2256            string != string   Strings are not equal.
2257
2258            number -eq number  Numbers compare equal.
2259
2260            number -ne number  Numbers compare not equal.
2261
2262            number -ge number  Numbers compare greater than or equal.
2263
2264            number -gt number  Numbers compare greater than.
2265
2266            number -le number  Numbers compare less than or equal.
2267
2268            number -lt number  Numbers compare less than.
2269
2270            The above basic expressions, in which unary operators have prece‐
2271            dence over binary operators, may be combined with the following
2272            operators (listed in increasing order of precedence):
2273
2274                  expr -o expr            Logical OR.
2275                  expr -a expr            Logical AND.
2276                  ! expr                  Logical NOT.
2277                  ( expr )                Grouping.
2278
2279            Note that a number actually may be an arithmetic expression, such
2280            as a mathematical term or the name of an integer variable:
2281
2282                  x=1; [ "x" -eq 1 ]      evaluates to true
2283
2284            Note that some special rules are applied (courtesy of POSIX) if
2285            the number of arguments to test or inside the brackets [ ... ] is
2286            less than five: if leading “!” arguments can be stripped such that
2287            only one to three arguments remain, then the lowered comparison is
2288            executed; (thanks to XSI) parentheses \( ... \) lower four- and
2289            three-argument forms to two- and one-argument forms, respectively;
2290            three-argument forms ultimately prefer binary operations, followed
2291            by negation and parenthesis lowering; two- and four-argument forms
2292            prefer negation followed by parenthesis; the one-argument form
2293            always implies -n.
2294
2295            Note: A common mistake is to use “if [ $foo = bar ]” which fails
2296            if parameter “foo” is empty or unset, if it has embedded spaces
2297            (i.e. IFS octets) or if it is a unary operator like “!” or “-n”.
2298            Use tests like “if [ x"$foo" = x"bar" ]” instead, or the double-
2299            bracket operator “if [[ $foo = bar ]]” or, to avoid pattern match‐
2300            ing (see [[ above): “if [[ $foo = "$bar" ]]”
2301
2302            The [[ ... ]] construct is not only more secure to use but also
2303            often faster.
2304
2305     time [-p] [pipeline]
2306            If a pipeline is given, the times used to execute the pipeline are
2307            reported.  If no pipeline is given, then the user and system time
2308            used by the shell itself, and all the commands it has run since it
2309            was started, are reported.  The times reported are the real time
2310            (elapsed time from start to finish), the user CPU time (time spent
2311            running in user mode), and the system CPU time (time spent running
2312            in kernel mode).  Times are reported to standard error; the format
2313            of the output is:
2314
2315                  0m0.00s real     0m0.00s user     0m0.00s system
2316
2317            If the -p option is given the output is slightly longer:
2318
2319                  real     0.00
2320                  user     0.00
2321                  sys      0.00
2322
2323            It is an error to specify the -p option unless pipeline is a sim‐
2324            ple command.
2325
2326            Simple redirections of standard error do not affect the output of
2327            the time command:
2328
2329                  $ time sleep 1 2>afile
2330                  $ { time sleep 1; } 2>afile
2331
2332            Times for the first command do not go to “afile”, but those of the
2333            second command do.
2334
2335     times  Print the accumulated user and system times used both by the shell
2336            and by processes that the shell started which have exited.  The
2337            format of the output is:
2338
2339                  0m0.00s 0m0.00s
2340                  0m0.00s 0m0.00s
2341
2342     trap n [signal ...]
2343            If the first operand is a decimal unsigned integer, this resets
2344            all specified signals to the default action, i.e. is the same as
2345            calling trap with a dash (“-”) as handler, followed by the argu‐
2346            ments (n [signal ...]), all of which are treated as signals.
2347
2348     trap [handler signal ...]
2349            Sets a trap handler that is to be executed when any of the speci‐
2350            fied signals are received.  handler is either an empty string,
2351            indicating the signals are to be ignored, a dash (“-”), indicating
2352            that the default action is to be taken for the signals (see
2353            signal(3)), or a string containing shell commands to be executed
2354            at the first opportunity (i.e. when the current command completes
2355            or before printing the next PS1 prompt) after receipt of one of
2356            the signals.  signal is the name of a signal (e.g. PIPE or ALRM)
2357            or the number of the signal (see the kill -l command above).
2358
2359            There are two special signals: EXIT (also known as 0), which is
2360            executed when the shell is about to exit, and ERR, which is exe‐
2361            cuted after an error occurs; an error is something that would
2362            cause the shell to exit if the set -e or set -o errexit option
2363            were set.  EXIT handlers are executed in the environment of the
2364            last executed command.
2365
2366            Note that, for non-interactive shells, the trap handler cannot be
2367            changed for signals that were ignored when the shell started.
2368
2369            With no arguments, the current state of the traps that have been
2370            set since the shell started is shown as a series of trap commands.
2371            Note that the output of trap cannot be usefully piped to another
2372            process (an artifact of the fact that traps are cleared when sub‐
2373            processes are created).
2374
2375            The original Korn shell's DEBUG trap and the handling of ERR and
2376            EXIT traps in functions are not yet implemented.
2377
2378     true   A command that exits with a zero value.
2379
2380     typeset [+-aglpnrtUux] [-L[n] | -R[n] | -Z[n]] [-i[n]] [name [=value]
2381            ...]
2382     typeset -f [-tux] [name ...]
2383            Display or set parameter attributes.  This is a declaration util‐
2384            ity.  With no name arguments, parameter attributes are displayed;
2385            if no options are used, the current attributes of all parameters
2386            are printed as typeset commands; if an option is given (or “-”
2387            with no option letter), all parameters and their values with the
2388            specified attributes are printed; if options are introduced with
2389            ‘+’, parameter values are not printed.
2390
2391            If name arguments are given, the attributes of the named parame‐
2392            ters are set (-) or cleared (+); inside a function, this will
2393            cause the parameters to be created (with no value) in the local
2394            scope (but see -g).  Values for parameters may optionally be spec‐
2395            ified.  For name[*], the change affects all elements of the array,
2396            and no value may be specified.
2397
2398            When -f is used, typeset operates on the attributes of functions.
2399            As with parameters, if no name arguments are given, functions are
2400            listed with their values (i.e. definitions) unless options are
2401            introduced with ‘+’, in which case only the function names are
2402            reported.
2403
2404            -a      Indexed array attribute.
2405
2406            -f      Function mode.  Display or set functions and their
2407                    attributes, instead of parameters.
2408
2409            -g      Do not cause named parameters to be created in the local
2410                    scope when called inside a function.
2411
2412            -i[n]   Integer attribute.  n specifies the base to use when dis‐
2413                    playing the integer (if not specified, the base given in
2414                    the first assignment is used).  Parameters with this
2415                    attribute may be assigned values containing arithmetic
2416                    expressions.
2417
2418            -L[n]   Left justify attribute.  n specifies the field width.  If
2419                    n is not specified, the current width of a parameter (or
2420                    the width of its first assigned value) is used.  Leading
2421                    whitespace (and zeros, if used with the -Z option) is
2422                    stripped.  If necessary, values are either truncated or
2423                    space padded to fit the field width.
2424
2425            -l      Lower case attribute.  All upper case ASCII characters in
2426                    values are converted to lower case.  (In the original Korn
2427                    shell, this parameter meant “long integer” when used with
2428                    the -i option.)
2429
2430            -n      Create a bound variable (name reference): any access to
2431                    the variable name will access the variable value in the
2432                    current scope (this is different from AT&T UNIX ksh93!)
2433                    instead.  Also different from AT&T UNIX ksh93 is that
2434                    value is lazily evaluated at the time name is accessed.
2435                    This can be used by functions to access variables whose
2436                    names are passed as parameters, instead of using eval.
2437
2438            -p      Print complete typeset commands that can be used to re-
2439                    create the attributes and values of parameters.
2440
2441            -R[n]   Right justify attribute.  n specifies the field width.  If
2442                    n is not specified, the current width of a parameter (or
2443                    the width of its first assigned value) is used.  Trailing
2444                    whitespace is stripped.  If necessary, values are either
2445                    stripped of leading characters or space padded to make
2446                    them fit the field width.
2447
2448            -r      Read-only attribute.  Parameters with this attribute may
2449                    not be assigned to or unset.  Once this attribute is set,
2450                    it cannot be turned off.
2451
2452            -t      Tag attribute.  Has no meaning to the shell; provided for
2453                    application use.
2454
2455                    For functions, -t is the trace attribute.  When functions
2456                    with the trace attribute are executed, the xtrace (-x)
2457                    shell option is temporarily turned on.
2458
2459            -U      Unsigned integer attribute.  Integers are printed as
2460                    unsigned values (combine with the -i option).  This option
2461                    is not in the original Korn shell.
2462
2463            -u      Upper case attribute.  All lower case ASCII characters in
2464                    values are converted to upper case.  (In the original Korn
2465                    shell, this parameter meant “unsigned integer” when used
2466                    with the -i option which meant upper case letters would
2467                    never be used for bases greater than 10.  See the -U
2468                    option.)
2469
2470                    For functions, -u is the undefined attribute.  See
2471                    Functions above for the implications of this.
2472
2473            -x      Export attribute.  Parameters (or functions) are placed in
2474                    the environment of any executed commands.  Exported func‐
2475                    tions are not yet implemented.
2476
2477            -Z[n]   Zero fill attribute.  If not combined with -L, this is the
2478                    same as -R, except zero padding is used instead of space
2479                    padding.  For integers, the number instead of the base is
2480                    padded.
2481
2482            If any of the -i, -L, -l, -R, -U, -u or -Z options are changed,
2483            all others from this set are cleared, unless they are also given
2484            on the same command line.
2485
2486     ulimit [-aBCcdefHilMmnOPpqrSsTtVvw] [value]
2487            Display or set process limits.  If no options are used, the file
2488            size limit (-f) is assumed.  value, if specified, may be either an
2489            arithmetic expression or the word “unlimited”.  The limits affect
2490            the shell and any processes created by the shell after a limit is
2491            imposed.  Note that some systems may not allow limits to be
2492            increased once they are set.  Also note that the types of limits
2493            available are system dependent – some systems have only the -f
2494            limit, or not even that, or can set only the soft limits
2495
2496            -a     Display all limits; unless -H is used, soft limits are dis‐
2497                   played.
2498
2499            -B n   Set the socket buffer size to n kibibytes.
2500
2501            -C n   Set the number of cached threads to n.
2502
2503            -c n   Impose a size limit of n blocks on the size of core dumps.
2504
2505            -d n   Impose a size limit of n kibibytes on the size of the data
2506                   area.
2507
2508            -e n   Set the maximum niceness to n.
2509
2510            -f n   Impose a size limit of n blocks on files written by the
2511                   shell and its child processes (files of any size may be
2512                   read).
2513
2514            -H     Set the hard limit only (the default is to set both hard
2515                   and soft limits).
2516
2517            -i n   Set the number of pending signals to n.
2518
2519            -l n   Impose a limit of n kibibytes on the amount of locked
2520                   (wired) physical memory.
2521
2522            -M n   Set the AIO locked memory to n kibibytes.
2523
2524            -m n   Impose a limit of n kibibytes on the amount of physical
2525                   memory used.
2526
2527            -n n   Impose a limit of n file descriptors that can be open at
2528                   once.
2529
2530            -O n   Set the number of AIO operations to n.
2531
2532            -P n   Limit the number of threads per process to n.
2533
2534            -p n   Impose a limit of n processes that can be run by the user
2535                   at any one time.
2536
2537            -q n   Limit the size of POSIX message queues to n bytes.
2538
2539            -r n   Set the maximum real-time priority to n.
2540
2541            -S     Set the soft limit only (the default is to set both hard
2542                   and soft limits).
2543
2544            -s n   Impose a size limit of n kibibytes on the size of the stack
2545                   area.
2546
2547            -T n   Impose a time limit of n real seconds to be used by each
2548                   process.
2549
2550            -t n   Impose a time limit of n CPU seconds spent in user mode to
2551                   be used by each process.
2552
2553            -V n   Set the number of vnode monitors on Haiku to n.
2554
2555            -v n   Impose a limit of n kibibytes on the amount of virtual mem‐
2556                   ory (address space) used.
2557
2558            -w n   Impose a limit of n kibibytes on the amount of swap space
2559                   used.
2560
2561            As far as ulimit is concerned, a block is 512 bytes.
2562
2563     umask [-S] [mask]
2564            Display or set the file permission creation mask or umask (see
2565            umask(2)).  If the -S option is used, the mask displayed or set is
2566            symbolic; otherwise, it is an octal number.
2567
2568            Symbolic masks are like those used by chmod(1).  When used, they
2569            describe what permissions may be made available (as opposed to
2570            octal masks in which a set bit means the corresponding bit is to
2571            be cleared).  For example, “ug=rwx,o=” sets the mask so files will
2572            not be readable, writable or executable by “others”, and is equiv‐
2573            alent (on most systems) to the octal mask “007”.
2574
2575     unalias [-adt] [name ...]
2576            The aliases for the given names are removed.  If the -a option is
2577            used, all aliases are removed.  If the -t or -d options are used,
2578            the indicated operations are carried out on tracked or directory
2579            aliases, respectively.
2580
2581     unset [-fv] parameter ...
2582            Unset the named parameters (-v, the default) or functions (-f).
2583            With parameter[*], attributes are kept, only values are unset.
2584
2585            The exit status is non-zero if any of the parameters have the
2586            read-only attribute set, zero otherwise.
2587
2588     wait [job ...]
2589            Wait for the specified job(s) to finish.  The exit status of wait
2590            is that of the last specified job; if the last job is killed by a
2591            signal, the exit status is 128 + the number of the signal (see
2592            kill -l exit-status above); if the last specified job can't be
2593            found (because it never existed or had already finished), the exit
2594            status of wait is 127.  See Job control below for the format of
2595            job.  wait will return if a signal for which a trap has been set
2596            is received or if a SIGHUP, SIGINT or SIGQUIT signal is received.
2597
2598            If no jobs are specified, wait waits for all currently running
2599            jobs (if any) to finish and exits with a zero status.  If job mon‐
2600            itoring is enabled, the completion status of jobs is printed (this
2601            is not the case when jobs are explicitly specified).
2602
2603     whence [-pv] [name ...]
2604            Without the -v option, it is the same as command -v, except
2605            aliases are not printed as alias command.  With the -v option, it
2606            is exactly the same as command -V.  In either case, the -p option
2607            differs: the search path is not affected in whence, but the search
2608            is restricted to the path.
2609
2610   Job control
2611     Job control refers to the shell's ability to monitor and control jobs
2612     which are processes or groups of processes created for commands or pipe‐
2613     lines.  At a minimum, the shell keeps track of the status of the back‐
2614     ground (i.e. asynchronous) jobs that currently exist; this information
2615     can be displayed using the jobs commands.  If job control is fully
2616     enabled (using set -m or set -o monitor), as it is for interactive
2617     shells, the processes of a job are placed in their own process group.
2618     Foreground jobs can be stopped by typing the suspend character from the
2619     terminal (normally ^Z), jobs can be restarted in either the foreground or
2620     background using the fg and bg commands, and the state of the terminal is
2621     saved or restored when a foreground job is stopped or restarted, respec‐
2622     tively.
2623
2624     Note that only commands that create processes (e.g. asynchronous com‐
2625     mands, subshell commands and non-built-in, non-function commands) can be
2626     stopped; commands like read cannot be.
2627
2628     When a job is created, it is assigned a job number.  For interactive
2629     shells, this number is printed inside “[...]”, followed by the process
2630     IDs of the processes in the job when an asynchronous command is run.  A
2631     job may be referred to in the bg, fg, jobs, kill and wait commands either
2632     by the process ID of the last process in the command pipeline (as stored
2633     in the $! parameter) or by prefixing the job number with a percent sign
2634     (‘%’).  Other percent sequences can also be used to refer to jobs:
2635
2636     %+ | %% | %    The most recently stopped job or, if there are no stopped
2637                    jobs, the oldest running job.
2638
2639     %-             The job that would be the %+ job if the latter did not
2640                    exist.
2641
2642     %n             The job with job number n.
2643
2644     %?string       The job with its command containing the string string (an
2645                    error occurs if multiple jobs are matched).
2646
2647     %string        The job with its command starting with the string string
2648                    (an error occurs if multiple jobs are matched).
2649
2650     When a job changes state (e.g. a background job finishes or foreground
2651     job is stopped), the shell prints the following status information:
2652
2653           [number] flag status command
2654
2655     where...
2656
2657     number   is the job number of the job;
2658
2659     flag     is the ‘+’ or ‘-’ character if the job is the %+ or %- job,
2660              respectively, or space if it is neither;
2661
2662     status   indicates the current state of the job and can be:
2663
2664              Done [number]
2665                         The job exited.  number is the exit status of the job
2666                         which is omitted if the status is zero.
2667
2668              Running    The job has neither stopped nor exited (note that
2669                         running does not necessarily mean consuming CPU time
2670                         – the process could be blocked waiting for some
2671                         event).
2672
2673              Stopped [signal]
2674                         The job was stopped by the indicated signal (if no
2675                         signal is given, the job was stopped by SIGTSTP).
2676
2677              signal-description [“core dumped”]
2678                         The job was killed by a signal (e.g. memory fault,
2679                         hangup); use kill -l for a list of signal descrip‐
2680                         tions.  The “core dumped” message indicates the
2681                         process created a core file.
2682
2683     command  is the command that created the process.  If there are multiple
2684              processes in the job, each process will have a line showing its
2685              command and possibly its status, if it is different from the
2686              status of the previous process.
2687
2688     When an attempt is made to exit the shell while there are jobs in the
2689     stopped state, the shell warns the user that there are stopped jobs and
2690     does not exit.  If another attempt is immediately made to exit the shell,
2691     the stopped jobs are sent a SIGHUP signal and the shell exits.  Simi‐
2692     larly, if the nohup option is not set and there are running jobs when an
2693     attempt is made to exit a login shell, the shell warns the user and does
2694     not exit.  If another attempt is immediately made to exit the shell, the
2695     running jobs are sent a SIGHUP signal and the shell exits.
2696
2697   POSIX mode
2698     Entering set -o posix mode will cause mksh to behave even more POSIX com‐
2699     pliant in places where the defaults or opinions differ.  Note that mksh
2700     will still operate with unsigned 32-bit arithmetic; use lksh if arith‐
2701     metic on the host long data type, complete with ISO C Undefined Behav‐
2702     iour, is required; refer to the lksh(1) manual page for details.  Most
2703     other historic, AT&T UNIX ksh-compatible or opinionated differences can
2704     be disabled by using this mode; these are:
2705
2706     ·   The incompatible GNU bash I/O redirection &>file is not supported.
2707
2708     ·   File descriptors created by I/O redirections are inherited by child
2709         processes.
2710
2711     ·   Numbers with a leading digit zero are interpreted as octal.
2712
2713     ·   The echo builtin does not interpret backslashes and only supports the
2714         exact option -n.
2715
2716     ·   Alias expansion with a trailing space only reruns on command words.
2717
2718     ·   Tilde expansion follows POSIX instead of Korn shell rules.
2719
2720     ·   The exit status of fg is always 0.
2721
2722     ·   kill -l only lists signal names, all in one line.
2723
2724     ·   getopts does not accept options with a leading ‘+’.
2725
2726     ·   exec skips builtins, functions and other commands and uses a PATH
2727         search to determine the utility to execute.
2728
2729   SH mode
2730     Compatibility mode; intended for use with legacy scripts that cannot eas‐
2731     ily be fixed; the changes are as follows:
2732
2733     ·   The incompatible GNU bash I/O redirection &>file is not supported.
2734
2735     ·   File descriptors created by I/O redirections are inherited by child
2736         processes.
2737
2738     ·   The echo builtin does not interpret backslashes and only supports the
2739         exact option -n, unless built with -DMKSH_MIDNIGHTBSD01ASH_COMPAT.
2740
2741     ·   The substitution operations ${x#pat}, ${x##pat}, ${x%pat}, and
2742         ${x%%pat} wrongly do not require a parenthesis to be escaped and do
2743         not parse extglobs.
2744
2745     ·   The getopt construct from lksh(1) passes through the errorlevel.
2746
2747     ·   sh -c eats a leading -- if built with -DMKSH_MIDNIGHTBSD01ASH_COMPAT.
2748
2749   Interactive input line editing
2750     The shell supports three modes of reading command lines from a tty(4) in
2751     an interactive session, controlled by the emacs, gmacs and vi options (at
2752     most one of these can be set at once).  The default is emacs.  Editing
2753     modes can be set explicitly using the set built-in.  If none of these
2754     options are enabled, the shell simply reads lines using the normal tty(4)
2755     driver.  If the emacs or gmacs option is set, the shell allows emacs-like
2756     editing of the command; similarly, if the vi option is set, the shell
2757     allows vi-like editing of the command.  These modes are described in
2758     detail in the following sections.
2759
2760     In these editing modes, if a line is longer than the screen width (see
2761     the COLUMNS parameter), a ‘>’, ‘+’ or ‘<’ character is displayed in the
2762     last column indicating that there are more characters after, before and
2763     after, or before the current position, respectively.  The line is
2764     scrolled horizontally as necessary.
2765
2766     Completed lines are pushed into the history, unless they begin with an
2767     IFS octet or IFS white space or are the same as the previous line.
2768
2769   Emacs editing mode
2770     When the emacs option is set, interactive input line editing is enabled.
2771     Warning: This mode is slightly different from the emacs mode in the orig‐
2772     inal Korn shell.  In this mode, various editing commands (typically bound
2773     to one or more control characters) cause immediate actions without wait‐
2774     ing for a newline.  Several editing commands are bound to particular con‐
2775     trol characters when the shell is invoked; these bindings can be changed
2776     using the bind command.
2777
2778     The following is a list of available editing commands.  Each description
2779     starts with the name of the command, suffixed with a colon; an [n] (if
2780     the command can be prefixed with a count); and any keys the command is
2781     bound to by default, written using caret notation e.g. the ASCII ESC
2782     character is written as ^[.  These control sequences are not case sensi‐
2783     tive.  A count prefix for a command is entered using the sequence ^[n,
2784     where n is a sequence of 1 or more digits.  Unless otherwise specified,
2785     if a count is omitted, it defaults to 1.
2786
2787     Note that editing command names are used only with the bind command.
2788     Furthermore, many editing commands are useful only on terminals with a
2789     visible cursor.  The user's tty(4) characters (e.g. ERASE) are bound to
2790     reasonable substitutes and override the default bindings; their customary
2791     values are shown in parentheses below.  The default bindings were chosen
2792     to resemble corresponding Emacs key bindings:
2793
2794     abort: INTR (^C), ^G
2795             Abort the current command, save it to the history, empty the line
2796             buffer and set the exit state to interrupted.
2797
2798     auto-insert: [n]
2799             Simply causes the character to appear as literal input.  Most
2800             ordinary characters are bound to this.
2801
2802     backward-char: [n] ^B, ^XD, ANSI-CurLeft, PC-CurLeft
2803             Moves the cursor backward n characters.
2804
2805     backward-word: [n] ^[b, ANSI-Ctrl-CurLeft, ANSI-Alt-CurLeft
2806             Moves the cursor backward to the beginning of the word; words
2807             consist of alphanumerics, underscore (‘_’) and dollar sign (‘$’)
2808             characters.
2809
2810     beginning-of-history: ^[<
2811             Moves to the beginning of the history.
2812
2813     beginning-of-line: ^A, ANSI-Home, PC-Home
2814             Moves the cursor to the beginning of the edited input line.
2815
2816     capitalise-word: [n] ^[C, ^[c
2817             Uppercase the first ASCII character in the next n words, leaving
2818             the cursor past the end of the last word.
2819
2820     clear-screen: ^[^L
2821             Prints a compile-time configurable sequence to clear the screen
2822             and home the cursor, redraws the last line of the prompt string
2823             and the currently edited input line.  The default sequence works
2824             for almost all standard terminals.
2825
2826     comment: ^[#
2827             If the current line does not begin with a comment character, one
2828             is added at the beginning of the line and the line is entered (as
2829             if return had been pressed); otherwise, the existing comment
2830             characters are removed and the cursor is placed at the beginning
2831             of the line.
2832
2833     complete: ^[^[
2834             Automatically completes as much as is unique of the command name
2835             or the file name containing the cursor.  If the entire remaining
2836             command or file name is unique, a space is printed after its com‐
2837             pletion, unless it is a directory name in which case ‘/’ is
2838             appended.  If there is no command or file name with the current
2839             partial word as its prefix, a bell character is output (usually
2840             causing a beep to be sounded).
2841
2842     complete-command: ^X^[
2843             Automatically completes as much as is unique of the command name
2844             having the partial word up to the cursor as its prefix, as in the
2845             complete command above.
2846
2847     complete-file: ^[^X
2848             Automatically completes as much as is unique of the file name
2849             having the partial word up to the cursor as its prefix, as in the
2850             complete command described above.
2851
2852     complete-list: ^I, ^[=
2853             Complete as much as is possible of the current word and list the
2854             possible completions for it.  If only one completion is possible,
2855             match as in the complete command above.  Note that ^I is usually
2856             generated by the TAB (tabulator) key.
2857
2858     delete-char-backward: [n] ERASE (^H), ^?, ^H
2859             Deletes n characters before the cursor.
2860
2861     delete-char-forward: [n] ANSI-Del, PC-Del
2862             Deletes n characters after the cursor.
2863
2864     delete-word-backward: [n] Pfx1+ERASE (^[^H), WERASE (^W), ^[^?, ^[^H, ^[h
2865             Deletes n words before the cursor.
2866
2867     delete-word-forward: [n] ^[d
2868             Deletes characters after the cursor up to the end of n words.
2869
2870     down-history: [n] ^N, ^XB, ANSI-CurDown, PC-CurDown
2871             Scrolls the history buffer forward n lines (later).  Each input
2872             line originally starts just after the last entry in the history
2873             buffer, so down-history is not useful until either
2874             search-history, search-history-up or up-history has been per‐
2875             formed.
2876
2877     downcase-word: [n] ^[L, ^[l
2878             Lowercases the next n words.
2879
2880     edit-line: [n] ^Xe
2881             Edit line n or the current line, if not specified, interactively.
2882             The actual command executed is fc -e ${VISUAL:-${EDITOR:-vi}} n.
2883
2884     end-of-history: ^[>
2885             Moves to the end of the history.
2886
2887     end-of-line: ^E, ANSI-End, PC-End
2888             Moves the cursor to the end of the input line.
2889
2890     eot: ^_
2891             Acts as an end-of-file; this is useful because edit-mode input
2892             disables normal terminal input canonicalisation.
2893
2894     eot-or-delete: [n] EOF (^D)
2895             If alone on a line, same as eot, otherwise, delete-char-forward.
2896
2897     error: (not bound)
2898             Error (ring the bell).
2899
2900     evaluate-region: ^[^E
2901             Evaluates the text between the mark and the cursor position (the
2902             entire line if no mark is set) as function substitution (if it
2903             cannot be parsed, the editing state is unchanged and the bell is
2904             rung to signal an error); $? is updated accordingly.
2905
2906     exchange-point-and-mark: ^X^X
2907             Places the cursor where the mark is and sets the mark to where
2908             the cursor was.
2909
2910     expand-file: ^[*
2911             Appends a ‘*’ to the current word and replaces the word with the
2912             result of performing file globbing on the word.  If no files
2913             match the pattern, the bell is rung.
2914
2915     forward-char: [n] ^F, ^XC, ANSI-CurRight, PC-CurRight
2916             Moves the cursor forward n characters.
2917
2918     forward-word: [n] ^[f, ANSI-Ctrl-CurRight, ANSI-Alt-CurRight
2919             Moves the cursor forward to the end of the nth word.
2920
2921     goto-history: [n] ^[g
2922             Goes to history number n.
2923
2924     kill-line: KILL (^U)
2925             Deletes the entire input line.
2926
2927     kill-region: ^W
2928             Deletes the input between the cursor and the mark.
2929
2930     kill-to-eol: [n] ^K
2931             Deletes the input from the cursor to the end of the line if n is
2932             not specified; otherwise deletes characters between the cursor
2933             and column n.
2934
2935     list: ^[?
2936             Prints a sorted, columnated list of command names or file names
2937             (if any) that can complete the partial word containing the cur‐
2938             sor.  Directory names have ‘/’ appended to them.
2939
2940     list-command: ^X?
2941             Prints a sorted, columnated list of command names (if any) that
2942             can complete the partial word containing the cursor.
2943
2944     list-file: ^X^Y
2945             Prints a sorted, columnated list of file names (if any) that can
2946             complete the partial word containing the cursor.  File type indi‐
2947             cators are appended as described under list above.
2948
2949     newline: ^J, ^M
2950             Causes the current input line to be processed by the shell.  The
2951             current cursor position may be anywhere on the line.
2952
2953     newline-and-next: ^O
2954             Causes the current input line to be processed by the shell, and
2955             the next line from history becomes the current line.  This is
2956             only useful after an up-history, search-history or
2957             search-history-up.
2958
2959     no-op: QUIT (^\)
2960             This does nothing.
2961
2962     prefix-1: ^[
2963             Introduces a 2-character command sequence.
2964
2965     prefix-2: ^X, ^[[, ^[O
2966             Introduces a multi-character command sequence.
2967
2968     prev-hist-word: [n] ^[., ^[_
2969             The last word or, if given, the nth word (zero-based) of the pre‐
2970             vious (on repeated execution, second-last, third-last, etc.) com‐
2971             mand is inserted at the cursor.  Use of this editing command
2972             trashes the mark.
2973
2974     quote: ^^, ^V
2975             The following character is taken literally rather than as an
2976             editing command.
2977
2978     redraw: ^L
2979             Reprints the last line of the prompt string and the current input
2980             line on a new line.
2981
2982     search-character-backward: [n] ^[^]
2983             Search backward in the current line for the nth occurrence of the
2984             next character typed.
2985
2986     search-character-forward: [n] ^]
2987             Search forward in the current line for the nth occurrence of the
2988             next character typed.
2989
2990     search-history: ^R
2991             Enter incremental search mode.  The internal history list is
2992             searched backwards for commands matching the input.  An initial
2993             ‘^’ in the search string anchors the search.  The escape key will
2994             leave search mode.  Other commands, including sequences of escape
2995             as prefix-1 followed by a prefix-1 or prefix-2 key will be exe‐
2996             cuted after leaving search mode.  The abort (^G) command will
2997             restore the input line before search started.  Successive
2998             search-history commands continue searching backward to the next
2999             previous occurrence of the pattern.  The history buffer retains
3000             only a finite number of lines; the oldest are discarded as neces‐
3001             sary.
3002
3003     search-history-up: ANSI-PgUp, PC-PgUp
3004             Search backwards through the history buffer for commands whose
3005             beginning match the portion of the input line before the cursor.
3006             When used on an empty line, this has the same effect as
3007             up-history.
3008
3009     search-history-down: ANSI-PgDn, PC-PgDn
3010             Search forwards through the history buffer for commands whose
3011             beginning match the portion of the input line before the cursor.
3012             When used on an empty line, this has the same effect as
3013             down-history.  This is only useful after an up-history,
3014             search-history or search-history-up.
3015
3016     set-mark-command: ^[<space>
3017             Set the mark at the cursor position.
3018
3019     transpose-chars: ^T
3020             If at the end of line or, if the gmacs option is set, this
3021             exchanges the two previous characters; otherwise, it exchanges
3022             the previous and current characters and moves the cursor one
3023             character to the right.
3024
3025     up-history: [n] ^P, ^XA, ANSI-CurUp, PC-CurUp
3026             Scrolls the history buffer backward n lines (earlier).
3027
3028     upcase-word: [n] ^[U, ^[u
3029             Uppercase the next n words.
3030
3031     version: ^[^V
3032             Display the version of mksh.  The current edit buffer is restored
3033             as soon as a key is pressed.  The restoring keypress is pro‐
3034             cessed, unless it is a space.
3035
3036     yank: ^Y
3037             Inserts the most recently killed text string at the current cur‐
3038             sor position.
3039
3040     yank-pop: ^[y
3041             Immediately after a yank, replaces the inserted text string with
3042             the next previously killed text string.
3043
3044     The tab completion escapes characters the same way as the following code:
3045
3046     print -nr -- "${x@/[\"-\$\&-*:-?[\\\`{-\}${IFS-$' \t\n'}]/\\$KSH_MATCH}"
3047
3048   Vi editing mode
3049     Note: The vi command-line editing mode is orphaned, yet still functional.
3050     It is 8-bit clean but specifically does not support UTF-8 or MBCS.
3051
3052     The vi command-line editor in mksh has basically the same commands as the
3053     vi(1) editor with the following exceptions:
3054
3055     ·   You start out in insert mode.
3056
3057     ·   There are file name and command completion commands: =, \, *, ^X, ^E,
3058         ^F and, optionally, <tab> and <esc>.
3059
3060     ·   The _ command is different (in mksh, it is the last argument command;
3061         in vi(1) it goes to the start of the current line).
3062
3063     ·   The / and G commands move in the opposite direction to the j command.
3064
3065     ·   Commands which don't make sense in a single line editor are not
3066         available (e.g. screen movement commands and ex(1)-style colon (:)
3067         commands).
3068
3069     Like vi(1), there are two modes: “insert” mode and “command” mode.  In
3070     insert mode, most characters are simply put in the buffer at the current
3071     cursor position as they are typed; however, some characters are treated
3072     specially.  In particular, the following characters are taken from cur‐
3073     rent tty(4) settings (see stty(1)) and have their usual meaning (normal
3074     values are in parentheses): kill (^U), erase (^?), werase (^W), eof (^D),
3075     intr (^C) and quit (^\).  In addition to the above, the following charac‐
3076     ters are also treated specially in insert mode:
3077
3078     ^E       Command and file name enumeration (see below).
3079
3080     ^F       Command and file name completion (see below).  If used twice in
3081              a row, the list of possible completions is displayed; if used a
3082              third time, the completion is undone.
3083
3084     ^H       Erases previous character.
3085
3086     ^J | ^M  End of line.  The current line is read, parsed and executed by
3087              the shell.
3088
3089     ^V       Literal next.  The next character typed is not treated specially
3090              (can be used to insert the characters being described here).
3091
3092     ^X       Command and file name expansion (see below).
3093
3094     <esc>    Puts the editor in command mode (see below).
3095
3096     <tab>    Optional file name and command completion (see ^F above),
3097              enabled with set -o vi-tabcomplete.
3098
3099     In command mode, each character is interpreted as a command.  Characters
3100     that don't correspond to commands, are illegal combinations of commands,
3101     or are commands that can't be carried out, all cause beeps.  In the fol‐
3102     lowing command descriptions, an [n] indicates the command may be prefixed
3103     by a number (e.g. 10l moves right 10 characters); if no number prefix is
3104     used, n is assumed to be 1 unless otherwise specified.  The term “current
3105     position” refers to the position between the cursor and the character
3106     preceding the cursor.  A “word” is a sequence of letters, digits and
3107     underscore characters or a sequence of non-letter, non-digit, non-under‐
3108     score and non-whitespace characters (e.g. “ab2*&^” contains two words)
3109     and a “big-word” is a sequence of non-whitespace characters.
3110
3111     Special mksh vi commands:
3112
3113     The following commands are not in, or are different from, the normal vi
3114     file editor:
3115
3116     [n]_        Insert a space followed by the nth big-word from the last
3117                 command in the history at the current position and enter
3118                 insert mode; if n is not specified, the last word is
3119                 inserted.
3120
3121     #           Insert the comment character (‘#’) at the start of the cur‐
3122                 rent line and return the line to the shell (equivalent to
3123                 I#^J).
3124
3125     [n]g        Like G, except if n is not specified, it goes to the most
3126                 recent remembered line.
3127
3128     [n]v        Edit line n using the vi(1) editor; if n is not specified,
3129                 the current line is edited.  The actual command executed is
3130                 fc -e ${VISUAL:-${EDITOR:-vi}} n.
3131
3132     * and ^X    Command or file name expansion is applied to the current big-
3133                 word (with an appended ‘*’ if the word contains no file glob‐
3134                 bing characters) – the big-word is replaced with the result‐
3135                 ing words.  If the current big-word is the first on the line
3136                 or follows one of the characters ‘;’, ‘|’, ‘&’, ‘(’ or ‘)’
3137                 and does not contain a slash (‘/’), then command expansion is
3138                 done; otherwise file name expansion is done.  Command expan‐
3139                 sion will match the big-word against all aliases, functions
3140                 and built-in commands as well as any executable files found
3141                 by searching the directories in the PATH parameter.  File
3142                 name expansion matches the big-word against the files in the
3143                 current directory.  After expansion, the cursor is placed
3144                 just past the last word and the editor is in insert mode.
3145
3146     [n]\, [n]^F, [n]<tab>, and [n]<esc>
3147                 Command/file name completion.  Replace the current big-word
3148                 with the longest unique match obtained after performing com‐
3149                 mand and file name expansion.  <tab> is only recognised if
3150                 the vi-tabcomplete option is set, while <esc> is only recog‐
3151                 nised if the vi-esccomplete option is set (see set -o).  If n
3152                 is specified, the nth possible completion is selected (as
3153                 reported by the command/file name enumeration command).
3154
3155     = and ^E    Command/file name enumeration.  List all the commands or
3156                 files that match the current big-word.
3157
3158     ^V          Display the version of mksh.  The current edit buffer is
3159                 restored as soon as a key is pressed.  The restoring keypress
3160                 is ignored.
3161
3162     @c          Macro expansion.  Execute the commands found in the alias c.
3163
3164     Intra-line movement commands:
3165
3166     [n]h and [n]^H
3167             Move left n characters.
3168
3169     [n]l and [n]<space>
3170             Move right n characters.
3171
3172     0       Move to column 0.
3173
3174     ^       Move to the first non-whitespace character.
3175
3176     [n]|    Move to column n.
3177
3178     $       Move to the last character.
3179
3180     [n]b    Move back n words.
3181
3182     [n]B    Move back n big-words.
3183
3184     [n]e    Move forward to the end of the word, n times.
3185
3186     [n]E    Move forward to the end of the big-word, n times.
3187
3188     [n]w    Move forward n words.
3189
3190     [n]W    Move forward n big-words.
3191
3192     %       Find match.  The editor looks forward for the nearest parenthe‐
3193             sis, bracket or brace and then moves the cursor to the matching
3194             parenthesis, bracket or brace.
3195
3196     [n]fc   Move forward to the nth occurrence of the character c.
3197
3198     [n]Fc   Move backward to the nth occurrence of the character c.
3199
3200     [n]tc   Move forward to just before the nth occurrence of the character
3201             c.
3202
3203     [n]Tc   Move backward to just before the nth occurrence of the character
3204             c.
3205
3206     [n];    Repeats the last f, F, t or T command.
3207
3208     [n],    Repeats the last f, F, t or T command, but moves in the opposite
3209             direction.
3210
3211     Inter-line movement commands:
3212
3213     [n]j, [n]+, and [n]^N
3214             Move to the nth next line in the history.
3215
3216     [n]k, [n]-, and [n]^P
3217             Move to the nth previous line in the history.
3218
3219     [n]G    Move to line n in the history; if n is not specified, the number
3220             of the first remembered line is used.
3221
3222     [n]g    Like G, except if n is not specified, it goes to the most recent
3223             remembered line.
3224
3225     [n]/string
3226             Search backward through the history for the nth line containing
3227             string; if string starts with ‘^’, the remainder of the string
3228             must appear at the start of the history line for it to match.
3229
3230     [n]?string
3231             Same as /, except it searches forward through the history.
3232
3233     [n]n    Search for the nth occurrence of the last search string; the
3234             direction of the search is the same as the last search.
3235
3236     [n]N    Search for the nth occurrence of the last search string; the
3237             direction of the search is the opposite of the last search.
3238
3239     ANSI-CurUp, PC-PgUp
3240             Take the characters from the beginning of the line to the current
3241             cursor position as search string and do a backwards history
3242             search for lines beginning with this string; keep the cursor
3243             position.  This works only in insert mode and keeps it enabled.
3244
3245     Edit commands
3246
3247     [n]a    Append text n times; goes into insert mode just after the current
3248             position.  The append is only replicated if command mode is re-
3249             entered i.e. <esc> is used.
3250
3251     [n]A    Same as a, except it appends at the end of the line.
3252
3253     [n]i    Insert text n times; goes into insert mode at the current posi‐
3254             tion.  The insertion is only replicated if command mode is re-
3255             entered i.e. <esc> is used.
3256
3257     [n]I    Same as i, except the insertion is done just before the first
3258             non-blank character.
3259
3260     [n]s    Substitute the next n characters (i.e. delete the characters and
3261             go into insert mode).
3262
3263     S       Substitute whole line.  All characters from the first non-blank
3264             character to the end of the line are deleted and insert mode is
3265             entered.
3266
3267     [n]cmove-cmd
3268             Change from the current position to the position resulting from n
3269             move-cmds (i.e. delete the indicated region and go into insert
3270             mode); if move-cmd is c, the line starting from the first non-
3271             blank character is changed.
3272
3273     C       Change from the current position to the end of the line (i.e.
3274             delete to the end of the line and go into insert mode).
3275
3276     [n]x    Delete the next n characters.
3277
3278     [n]X    Delete the previous n characters.
3279
3280     D       Delete to the end of the line.
3281
3282     [n]dmove-cmd
3283             Delete from the current position to the position resulting from n
3284             move-cmds; move-cmd is a movement command (see above) or d, in
3285             which case the current line is deleted.
3286
3287     [n]rc   Replace the next n characters with the character c.
3288
3289     [n]R    Replace.  Enter insert mode but overwrite existing characters
3290             instead of inserting before existing characters.  The replacement
3291             is repeated n times.
3292
3293     [n]~    Change the case of the next n characters.
3294
3295     [n]ymove-cmd
3296             Yank from the current position to the position resulting from n
3297             move-cmds into the yank buffer; if move-cmd is y, the whole line
3298             is yanked.
3299
3300     Y       Yank from the current position to the end of the line.
3301
3302     [n]p    Paste the contents of the yank buffer just after the current
3303             position, n times.
3304
3305     [n]P    Same as p, except the buffer is pasted at the current position.
3306
3307     Miscellaneous vi commands
3308
3309     ^J and ^M
3310             The current line is read, parsed and executed by the shell.
3311
3312     ^L and ^R
3313             Redraw the current line.
3314
3315     [n].    Redo the last edit command n times.
3316
3317     u       Undo the last edit command.
3318
3319     U       Undo all changes that have been made to the current line.
3320
3321     PC Home, End, Del and cursor keys
3322             They move as expected, both in insert and command mode.
3323
3324     intr and quit
3325             The interrupt and quit terminal characters cause the current line
3326             to be removed to the history and a new prompt to be printed.
3327

FILES

3329     ~/.mkshrc          User mkshrc profile (non-privileged interactive
3330                        shells); see Startup files. The location can be
3331                        changed at compile time (for embedded systems); AOSP
3332                        Android builds use /system/etc/mkshrc.
3333     ~/.profile         User profile (non-privileged login shells); see
3334                        Startup files near the top of this manual.
3335     /etc/profile       System profile (login shells); see Startup files.
3336     /etc/shells        Shell database.
3337     /etc/suid_profile  Suid profile (privileged shells); see Startup files.
3338
3339     Note: On Android, /system/etc/ contains the system and suid profile.
3340

SEE ALSO

3342     awk(1), cat(1), ed(1), getopt(1), lksh(1), sed(1), sh(1), stty(1),
3343     dup(2), execve(2), getgid(2), getuid(2), mknod(2), mkfifo(2), open(2),
3344     pipe(2), rename(2), wait(2), getopt(3), nl_langinfo(3), setlocale(3),
3345     signal(3), system(3), tty(4), shells(5), environ(7), script(7), utf-8(7),
3346     mknod(8)
3347
3348     http://www.mirbsd.org/ksh-chan.htm
3349
3350     Morris Bolsky, The KornShell Command and Programming Language, Prentice
3351     Hall PTR, xvi + 356 pages, 1989, ISBN 978-0-13-516972-8 (0-13-516972-0).
3352
3353     Morris I. Bolsky and David G. Korn, The New KornShell Command and
3354     Programming Language (2nd Edition), Prentice Hall PTR, xvi + 400 pages,
3355     1995, ISBN 978-0-13-182700-4 (0-13-182700-6).
3356
3357     Stephen G. Kochan and Patrick H. Wood, UNIX Shell Programming, Sams, 3rd
3358     Edition, xiii + 437 pages, 2003, ISBN 978-0-672-32490-1 (0-672-32490-3).
3359
3360     IEEE Inc., IEEE Standard for Information Technology  Portable Operating
3361     System Interface (POSIX), IEEE Press, Part 2: Shell and Utilities,
3362     xvii + 1195 pages, 1993, ISBN 978-1-55937-255-8 (1-55937-255-9).
3363
3364     Bill Rosenblatt, Learning the Korn Shell, O'Reilly, 360 pages, 1993, ISBN
3365     978-1-56592-054-5 (1-56592-054-6).
3366
3367     Bill Rosenblatt and Arnold Robbins, Learning the Korn Shell, Second
3368     Edition, O'Reilly, 432 pages, 2002, ISBN 978-0-596-00195-7
3369     (0-596-00195-9).
3370
3371     Barry Rosenberg, KornShell Programming Tutorial, Addison-Wesley
3372     Professional, xxi + 324 pages, 1991, ISBN 978-0-201-56324-5
3373     (0-201-56324-X).
3374

AUTHORS

3376     The MirBSD Korn Shell is developed by mirabilos <m@mirbsd.org> as part of
3377     The MirOS Project.  This shell is based on the public domain 7th edition
3378     Bourne shell clone by Charles Forsyth, who kindly agreed to, in countries
3379     where the Public Domain status of the work may not be valid, grant a
3380     copyright licence to the general public to deal in the work without
3381     restriction and permission to sublicence derivatives under the terms of
3382     any (OSI approved) Open Source licence, and parts of the BRL shell by
3383     Doug A. Gwyn, Doug Kingston, Ron Natalie, Arnold Robbins, Lou Salkind and
3384     others.  The first release of pdksh was created by Eric Gisin, and it was
3385     subsequently maintained by John R. MacMillan, Simon J. Gerraty and
3386     Michael Rendell.  The effort of several projects, such as Debian and
3387     OpenBSD, and other contributors including our users, to improve the shell
3388     is appreciated.  See the documentation, website and source code (CVS) for
3389     details.
3390
3391     mksh-os2 is developed by KO Myung-Hun <komh@chollian.net>.
3392
3393     mksh-w32 is developed by Michael Langguth <lan@scalaris.com>.
3394
3395     mksh/z/OS is contributed by Daniel Richard G. <skunk@iSKUNK.ORG>.
3396
3397     The BSD daemon is Copyright © Marshall Kirk McKusick.  The complete
3398     legalese is at: http://www.mirbsd.org/TaC-mksh.txt
3399

CAVEATS

3401     mksh provides a consistent 32-bit integer arithmetic implementation, both
3402     signed and unsigned, with sign of the result of a remainder operation and
3403     wraparound defined, even (defying POSIX) on 36-bit and 64-bit systems.
3404
3405     mksh provides a consistent, clear interface normally.  This may deviate
3406     from POSIX in historic or opinionated places.  set -o posix (see POSIX
3407     mode for details) will cause the shell to behave more conformant.
3408
3409     For the purpose of POSIX, mksh supports only the “C” locale.  mksh's
3410     utf8-mode must be disabled in POSIX mode, and it only supports the Uni‐
3411     code BMP (Basic Multilingual Plane) and maps raw octets into the
3412     U+EF80..U+EFFF wide character range; compare Arithmetic expressions.  The
3413     following POSIX sh-compatible code toggles the utf8-mode option dependent
3414     on the current POSIX locale for mksh to allow using the UTF-8 mode,
3415     within the constraints outlined above, in code portable across various
3416     shell implementations:
3417
3418           case ${KSH_VERSION:-} in
3419           *MIRBSD KSH*|*LEGACY KSH*)
3420                   case ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} in
3421                   *[Uu][Tt][Ff]8*|*[Uu][Tt][Ff]-8*) set -U ;;
3422                   *) set +U ;;
3423                   esac ;;
3424           esac
3425     In near future, (Unicode) locale tracking will be implemented though.
3426
3427     See also the FAQ below.
3428

BUGS

3430     Suspending (using ^Z) pipelines like the one below will only suspend the
3431     currently running part of the pipeline; in this example, “fubar” is imme‐
3432     diately printed on suspension (but not later after an fg).
3433
3434           $ /bin/sleep 666 && echo fubar
3435
3436     The truncation process involved when changing HISTFILE does not free old
3437     history entries (leaks memory) and leaks old entries into the new history
3438     if their line numbers are not overwritten by same-number entries from the
3439     persistent history file; truncating the on-disc file to HISTSIZE lines
3440     has always been broken and prone to history file corruption when multiple
3441     shells are accessing the file; the rollover process for the in-memory
3442     portion of the history is slow, should use memmove(3).
3443
3444     This document attempts to describe mksh R56 and up, compiled without any
3445     options impacting functionality, such as MKSH_SMALL, when not called as
3446     /bin/sh which, on some systems only, enables set -o posix or set -o sh
3447     automatically (whose behaviour differs across targets), for an operating
3448     environment supporting all of its advanced needs.
3449
3450     Please report bugs in mksh to the <miros-mksh@mirbsd.org> mailing list or
3451     in the #!/bin/mksh (or #ksh) IRC channel at irc.freenode.net (Port 6697
3452     SSL, 6667 unencrypted), or at: https://launchpad.net/mksh
3453

FREQUENTLY ASKED QUESTIONS

3455     This FAQ attempts to document some of the questions users of mksh or
3456     readers of this manual page may encounter.
3457
3458   I'm an Android user, so what's mksh?
3459     mksh is a UNIX shell / command interpreter, similar to COMMAND.COM or
3460     CMD.EXE, which has been included with Android Open Source Project for a
3461     while now.  Basically, it's a program that runs in a terminal (console
3462     window), takes user input and runs commands or scripts, which it can also
3463     be asked to do by other programs, even in the background.  Any privilege
3464     pop-ups you might be encountering are thus not mksh issues but questions
3465     by some other program utilising it.
3466
3467   I'm an OS/2 user, what do I need to know?
3468     Unlike the native command prompt, the current working directory is, for
3469     security reasons common on Unix systems which the shell is designed for,
3470     not in the search path at all; if you really need this, run the command
3471     PATH=.$PATHSEP$PATH or add that to a suitable initialisation file.
3472
3473     There are two different newline modes for mksh-os2: standard (Unix) mode,
3474     in which only LF (0A hex) is supported as line separator, and "textmode",
3475     which also accepts ASCII newlines (CR+LF), like most other tools on OS/2,
3476     but creating an incompatibility with standard mksh.  If you compiled mksh
3477     from source, you will get the standard Unix mode unless -T is added dur‐
3478     ing compilation; you will most likely have gotten this shell through
3479     komh's port on Hobbes, or from his OS/2 Factory on eComStation Korea,
3480     which uses "textmode", though.  Most OS/2 users will want to use
3481     "textmode" unless they need absolute compatibility with Unix mksh.
3482
3483   How do I start mksh on a specific terminal?
3484     Normally:
3485           mksh -T/dev/tty2
3486
3487     However, if you want for it to return (e.g. for an embedded system rescue
3488     shell), use this on your real console device instead:
3489           mksh -T!/dev/ttyACM0
3490
3491     mksh can also daemonise (send to the background):
3492           mksh -T- -c 'exec cdio lock'
3493
3494   POSIX says...
3495     Run the shell in POSIX mode (and possibly lksh instead of mksh):
3496           set -o posix
3497
3498   My prompt from <some other shell> does not work!
3499     Contact us on the mailing list or on IRC, we'll convert it for you.
3500
3501   Something is going wrong with my while...read loop
3502     Most likely, you've encountered the problem in which the shell runs all
3503     parts of a pipeline as subshell.  The inner loop will be executed in a
3504     subshell and variable changes cannot be propagated if run in a pipeline:
3505
3506           bar | baz | while read foo; do ...; done
3507
3508     Note that exit in the inner loop will only exit the subshell and not the
3509     original shell.  Likewise, if the code is inside a function, return in
3510     the inner loop will only exit the subshell and won't terminate the func‐
3511     tion.
3512
3513     Use co-processes instead:
3514
3515           bar | baz |&
3516           while read -p foo; do ...; done
3517           exec 3>&p; exec 3>&-
3518
3519     If read is run in a loop such as while read foo; do ...; done then lead‐
3520     ing whitespace will be removed (IFS) and backslashes processed.  You
3521     might want to use while IFS= read -r foo; do ...; done for pristine I/O.
3522     Similarly, when using the -a option, use of the -r option might be pru‐
3523     dent (“read -raN-1 arr <file”); the same applies for NUL-terminated
3524     lines:
3525
3526           find . -type f -print0 |& \
3527               while IFS= read -d '' -pr filename; do
3528                   print -r -- "found <${filename#./}>"
3529           done
3530
3531   What differences in function-local scopes are there?
3532     mksh has a different scope model from AT&T UNIX ksh, which leads to sub‐
3533     tle differences in semantics for identical builtins.  This can cause
3534     issues with a nameref to suddenly point to a local variable by accident.
3535
3536     GNU bash allows unsetting local variables; in mksh, doing so in a func‐
3537     tion allows back access to the global variable (actually the one in the
3538     next scope up) with the same name.  The following code, when run before
3539     the function definitions, changes the behaviour of unset to behave like
3540     other shells (the alias can be removed after the definitions):
3541
3542           case ${KSH_VERSION:-} in
3543           *MIRBSD KSH*|*LEGACY KSH*)
3544                   function unset_compat {
3545                           \\builtin typeset unset_compat_x
3546
3547                           for unset_compat_x in "$@"; do
3548                                   eval "\\\\builtin unset $unset_compat_x[*]"
3549                           done
3550                   }
3551                   \\builtin alias unset=unset_compat
3552                   ;;
3553           esac
3554
3555     When a local variable is created (e.g. using local, typeset, integer,
3556     \\builtin typeset) it does not, like in other shells, inherit the value
3557     from the global (next scope up) variable with the same name; it is rather
3558     created without any value (unset but defined).
3559
3560   I get an error in this regex comparison
3561     Use extglobs instead of regexes:
3562           [[ foo =~ (foo|bar).*baz ]]   # becomes
3563           [[ foo = *@(foo|bar)*baz* ]]  # instead
3564
3565   Are there any extensions to avoid?
3566     GNU bash supports “&>” (and “|&”) to redirect both stdout and stderr in
3567     one go, but this breaks POSIX and Korn Shell syntax; use POSIX redirec‐
3568     tions instead:
3569           foo |& bar |& baz &>log                 # GNU bash
3570           foo 2>&1 | bar 2>&1 | baz >log 2>&1     # POSIX
3571
3572   ^L (Ctrl-L) does not clear the screen
3573     Use ^[^L (Escape+Ctrl-L) or rebind it:
3574           bind '^L=clear-screen'
3575
3576   ^U (Ctrl-U) clears the entire line
3577     If it should only delete the line up to the cursor, use:
3578           bind -m ^U='^[0^K'
3579
3580   Cursor Up behaves differently from zsh
3581     Some shells make Cursor Up search in the history only for commands start‐
3582     ing with what was already entered.  mksh separates the shortcuts: Cursor
3583     Up goes up one command and PgUp searches the history as described above.
3584
3585   My question is not answered here!
3586     Check http://www.mirbsd.org/mksh-faq.htm which contains a collection of
3587     frequently asked questions about mksh in general, for packagers, etc.
3588     while these above are in user scope.
3589
3590MirBSD                          August 16, 2017                         MirBSD
Impressum