1MKSH(1) BSD General Commands Manual MKSH(1)
2
4 mksh, sh — MirBSD Korn shell
5
7 mksh [-+abCefhiklmnprUuvXx] [-T [!]tty | -] [-+o option] [-c string | -s
8 | file [argument ...]]
9 builtin-name [argument ...]
10
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 Universal Coded Character Set
389 codepoint to UTF-8. Furthermore, “\E” and “\e” expand to the escape
390 character.
391
392 In the print builtin mode, “\"”, “\'” and “\?” are explicitly excluded;
393 octal sequences must have the none up to three octal digits “#” prefixed
394 with the digit zero (“\0###”); hexadecimal sequences “\x##” are limited
395 to none up to two hexadecimal digits “#”; both octal and hexadecimal
396 sequences convert to raw octets; “\#”, where # is none of the above,
397 translates to \# (backslashes are retained).
398
399 Backslash expansion in the C style mode slightly differs: octal sequences
400 “\###” must have no digit zero prefixing the one up to three octal digits
401 “#” and yield raw octets; hexadecimal sequences “\x#*” greedily eat up as
402 many hexadecimal digits “#” as they can and terminate with the first non-
403 hexadecimal digit; these translate a Universal Coded Character Set code‐
404 point to UTF-8. The sequence “\c#”, where “#” is any octet, translates
405 to Ctrl-# (which basically means, “\c?” becomes DEL, everything else is
406 bitwise ANDed with 0x1F). Finally, “\#”, where # is none of the above,
407 translates to # (has the backslash trimmed), even if it is a newline.
408
409 Aliases
410 There are two types of aliases: normal command aliases and tracked
411 aliases. Command aliases are normally used as a short hand for a long or
412 often used command. The shell expands command aliases (i.e. substitutes
413 the alias name for its value) when it reads the first word of a command.
414 An expanded alias is re-processed to check for more aliases. If a com‐
415 mand alias ends in a space or tab, the following word is also checked for
416 alias expansion. The alias expansion process stops when a word that is
417 not an alias is found, when a quoted word is found, or when an alias word
418 that is currently being expanded is found. Aliases are specifically an
419 interactive feature: while they do happen to work in scripts and on the
420 command line in some cases, aliases are expanded during lexing, so their
421 use must be in a separate command tree from their definition; otherwise,
422 the alias will not be found. Noticeably, command lists (separated by
423 semicolon, in command substitutions also by newline) may be one same
424 parse tree.
425
426 The following command aliases are defined automatically by the shell:
427
428 autoload='\\builtin typeset -fu'
429 functions='\\builtin typeset -f'
430 hash='\\builtin alias -t'
431 history='\\builtin fc -l'
432 integer='\\builtin typeset -i'
433 local='\\builtin typeset'
434 login='\\builtin exec login'
435 nameref='\\builtin typeset -n'
436 nohup='nohup '
437 r='\\builtin fc -e -'
438 type='\\builtin whence -v'
439
440 Tracked aliases allow the shell to remember where it found a particular
441 command. The first time the shell does a path search for a command that
442 is marked as a tracked alias, it saves the full path of the command. The
443 next time the command is executed, the shell checks the saved path to see
444 that it is still valid, and if so, avoids repeating the path search.
445 Tracked aliases can be listed and created using alias -t. Note that
446 changing the PATH parameter clears the saved paths for all tracked
447 aliases. If the trackall option is set (i.e. set -o trackall or set -h),
448 the shell tracks all commands. This option is set automatically for non-
449 interactive shells. For interactive shells, only the following commands
450 are automatically tracked: cat(1), cc(1), chmod(1), cp(1), date(1),
451 ed(1), emacs(1), grep(1), ls(1), make(1), mv(1), pr(1), rm(1), sed(1),
452 sh(1), vi(1) and who(1).
453
454 Substitution
455 The first step the shell takes in executing a simple-command is to per‐
456 form substitutions on the words of the command. There are three kinds of
457 substitution: parameter, command and arithmetic. Parameter substitu‐
458 tions, which are described in detail in the next section, take the form
459 $name or ${...}; command substitutions take the form $(command) or (dep‐
460 recated) `command` or (executed in the current environment) ${ command;}
461 and strip trailing newlines; and arithmetic substitutions take the form
462 $((expression)). Parsing the current-environment command substitution
463 requires a space, tab or newline after the opening brace and that the
464 closing brace be recognised as a keyword (i.e. is preceded by a newline
465 or semicolon). They are also called funsubs (function substitutions) and
466 behave like functions in that local and return work, and in that exit
467 terminates the parent shell; shell options are shared.
468
469 Another variant of substitution are the valsubs (value substitutions)
470 ${|command;} which are also executed in the current environment, like
471 funsubs, but share their I/O with the parent; instead, they evaluate to
472 whatever the, initially empty, expression-local variable REPLY is set to
473 within the commands.
474
475 If a substitution appears outside of double quotes, the results of the
476 substitution are generally subject to word or field splitting according
477 to the current value of the IFS parameter. The IFS parameter specifies a
478 list of octets which are used to break a string up into several words;
479 any octets from the set space, tab and newline that appear in the IFS
480 octets are called “IFS whitespace”. Sequences of one or more IFS white‐
481 space octets, in combination with zero or one non-IFS whitespace octets,
482 delimit a field. As a special case, leading and trailing IFS whitespace
483 is stripped (i.e. no leading or trailing empty field is created by it);
484 leading or trailing non-IFS whitespace does create an empty field.
485
486 Example: If IFS is set to “<space>:” and VAR is set to
487 “<space>A<space>:<space><space>B::D”, the substitution for $VAR results
488 in four fields: “A”, “B”, “” (an empty field) and “D”. Note that if the
489 IFS parameter is set to the empty string, no field splitting is done; if
490 it is unset, the default value of space, tab and newline is used.
491
492 Also, note that the field splitting applies only to the immediate result
493 of the substitution. Using the previous example, the substitution for
494 $VAR:E results in the fields: “A”, “B”, “” and “D:E”, not “A”, “B”, “”,
495 “D” and “E”. This behavior is POSIX compliant, but incompatible with
496 some other shell implementations which do field splitting on the word
497 which contained the substitution or use IFS as a general whitespace
498 delimiter.
499
500 The results of substitution are, unless otherwise specified, also subject
501 to brace expansion and file name expansion (see the relevant sections
502 below).
503
504 A command substitution is replaced by the output generated by the speci‐
505 fied command which is run in a subshell. For $(command) and ${|command;}
506 and ${ command;} substitutions, normal quoting rules are used when
507 command is parsed; however, for the deprecated `command` form, a ‘\’ fol‐
508 lowed by any of ‘$’, ‘`’ or ‘\’ is stripped (as is ‘"’ when the substitu‐
509 tion is part of a double-quoted string); a backslash ‘\’ followed by any
510 other character is unchanged. As a special case in command substitu‐
511 tions, a command of the form <file is interpreted to mean substitute the
512 contents of file. Note that $(<foo) has the same effect as $(cat foo).
513
514 Note that some shells do not use a recursive parser for command substitu‐
515 tions, leading to failure for certain constructs; to be portable, use as
516 workaround “x=$(cat) <<\EOF” (or the newline-keeping “x=<<\EOF” exten‐
517 sion) instead to merely slurp the string. IEEE Std 1003.1 (“POSIX.1”)
518 recommends using case statements of the form x=$(case $foo in (bar) echo
519 $bar ;; (*) echo $baz ;; esac) instead, which would work but not serve as
520 example for this portability issue.
521
522 x=$(case $foo in bar) echo $bar ;; *) echo $baz ;; esac)
523 # above fails to parse on old shells; below is the workaround
524 x=$(eval $(cat)) <<\EOF
525 case $foo in bar) echo $bar ;; *) echo $baz ;; esac
526 EOF
527
528 Arithmetic substitutions are replaced by the value of the specified
529 expression. For example, the command print $((2+3*4)) displays 14. See
530 Arithmetic expressions for a description of an expression.
531
532 Parameters
533 Parameters are shell variables; they can be assigned values and their
534 values can be accessed using a parameter substitution. A parameter name
535 is either one of the special single punctuation or digit character param‐
536 eters described below, or a letter followed by zero or more letters or
537 digits (‘_’ counts as a letter). The latter form can be treated as
538 arrays by appending an array index of the form [expr] where expr is an
539 arithmetic expression. Array indices in mksh are limited to the range 0
540 through 4294967295, inclusive. That is, they are a 32-bit unsigned inte‐
541 ger.
542
543 Parameter substitutions take the form $name, ${name} or ${name[expr]}
544 where name is a parameter name. Substitutions of an an array in scalar
545 context, i.e. without an expr in the latter form mentioned above, expand
546 the element with the key “0”. Substitution of all array elements with
547 ${name[*]} and ${name[@]} works equivalent to $* and $@ for positional
548 parameters. If substitution is performed on a parameter (or an array
549 parameter element) that is not set, an empty string is substituted unless
550 the nounset option (set -u) is set, in which case an error occurs.
551
552 Parameters can be assigned values in a number of ways. First, the shell
553 implicitly sets some parameters like “#”, “PWD” and “$”; this is the only
554 way the special single character parameters are set. Second, parameters
555 are imported from the shell's environment at startup. Third, parameters
556 can be assigned values on the command line: for example, FOO=bar sets the
557 parameter “FOO” to “bar”; multiple parameter assignments can be given on
558 a single command line and they can be followed by a simple-command, in
559 which case the assignments are in effect only for the duration of the
560 command (such assignments are also exported; see below for the implica‐
561 tions of this). Note that both the parameter name and the ‘=’ must be
562 unquoted for the shell to recognise a parameter assignment. The con‐
563 struct FOO+=baz is also recognised; the old and new values are immedi‐
564 ately concatenated. The fourth way of setting a parameter is with the
565 export, global, readonly and typeset commands; see their descriptions in
566 the Command execution section. Fifth, for and select loops set parame‐
567 ters as well as the getopts, read and set -A commands. Lastly, parame‐
568 ters can be assigned values using assignment operators inside arithmetic
569 expressions (see Arithmetic expressions below) or using the ${name=value}
570 form of the parameter substitution (see below).
571
572 Parameters with the export attribute (set using the export or typeset -x
573 commands, or by parameter assignments followed by simple commands) are
574 put in the environment (see environ(7)) of commands run by the shell as
575 name=value pairs. The order in which parameters appear in the environ‐
576 ment of a command is unspecified. When the shell starts up, it extracts
577 parameters and their values from its environment and automatically sets
578 the export attribute for those parameters.
579
580 Modifiers can be applied to the ${name} form of parameter substitution:
581
582 ${name:-word}
583 If name is set and not empty, it is substituted; otherwise, word
584 is substituted.
585
586 ${name:+word}
587 If name is set and not empty, word is substituted; otherwise,
588 nothing is substituted.
589
590 ${name:=word}
591 If name is set and not empty, it is substituted; otherwise, it is
592 assigned word and the resulting value of name is substituted.
593
594 ${name:?word}
595 If name is set and not empty, it is substituted; otherwise, word
596 is printed on standard error (preceded by name:) and an error
597 occurs (normally causing termination of a shell script, function,
598 or a script sourced using the “.” built-in). If word is omitted,
599 the string “parameter null or not set” is used instead.
600
601 Note that, for all of the above, word is actually considered quoted, and
602 special parsing rules apply. The parsing rules also differ on whether
603 the expression is double-quoted: word then uses double-quoting rules,
604 except for the double quote itself (‘"’) and the closing brace, which, if
605 backslash escaped, gets quote removal applied.
606
607 In the above modifiers, the ‘:’ can be omitted, in which case the condi‐
608 tions only depend on name being set (as opposed to set and not empty).
609 If word is needed, parameter, command, arithmetic and tilde substitution
610 are performed on it; if word is not needed, it is not evaluated.
611
612 The following forms of parameter substitution can also be used:
613
614 ${#name}
615 The number of positional parameters if name is “*”, “@” or not
616 specified; otherwise the length (in characters) of the string
617 value of parameter name.
618
619 ${#name[*]}
620 ${#name[@]}
621 The number of elements in the array name.
622
623 ${%name}
624 The width (in screen columns) of the string value of parameter
625 name, or -1 if ${name} contains a control character.
626
627 ${!name}
628 The name of the variable referred to by name. This will be name
629 except when name is a name reference (bound variable), created by
630 the nameref command (which is an alias for typeset -n). name
631 cannot be one of most special parameters (see below).
632
633 ${!name[*]}
634 ${!name[@]}
635 The names of indices (keys) in the array name.
636
637 ${name#pattern}
638 ${name##pattern}
639 If pattern matches the beginning of the value of parameter name,
640 the matched text is deleted from the result of substitution. A
641 single ‘#’ results in the shortest match, and two of them result
642 in the longest match. Cannot be applied to a vector (${*} or
643 ${@} or ${array[*]} or ${array[@]}).
644
645 ${name%pattern}
646 ${name%%pattern}
647 Like ${...#...} substitution, but it deletes from the end of the
648 value. Cannot be applied to a vector.
649
650 ${name/pattern/string}
651 ${name/#pattern/string}
652 ${name/%pattern/string}
653 ${name//pattern/string}
654 The longest match of pattern in the value of parameter name is
655 replaced with string (deleted if string is empty; the trailing
656 slash (‘/’) may be omitted in that case). A leading slash fol‐
657 lowed by ‘#’ or ‘%’ causes the pattern to be anchored at the
658 beginning or end of the value, respectively; empty unanchored
659 patterns cause no replacement; a single leading slash or use of a
660 pattern that matches the empty string causes the replacement to
661 happen only once; two leading slashes cause all occurrences of
662 matches in the value to be replaced. Cannot be applied to a vec‐
663 tor. Inefficiently implemented, may be slow.
664
665 ${name@/pattern/string}
666 The same as ${name//pattern/string}, except that both pattern and
667 string are expanded anew for each iteration.
668
669 ${name:pos:len}
670 The first len characters of name, starting at position pos, are
671 substituted. Both pos and :len are optional. If pos is nega‐
672 tive, counting starts at the end of the string; if it is omitted,
673 it defaults to 0. If len is omitted or greater than the length
674 of the remaining string, all of it is substituted. Both pos and
675 len are evaluated as arithmetic expressions. Currently, pos must
676 start with a space, opening parenthesis or digit to be recog‐
677 nised. Cannot be applied to a vector.
678
679 ${name@#}
680 The hash (using the BAFH algorithm) of the expansion of name.
681 This is also used internally for the shell's hashtables.
682
683 ${name@Q}
684 A quoted expression safe for re-entry, whose value is the value
685 of the name parameter, is substituted.
686
687 Note that pattern may need extended globbing pattern (@(...)), single
688 ('...') or double ("...") quote escaping unless -o sh is set.
689
690 The following special parameters are implicitly set by the shell and can‐
691 not be set directly using assignments:
692
693 ! Process ID of the last background process started. If no back‐
694 ground processes have been started, the parameter is not set.
695
696 # The number of positional parameters ($1, $2, etc.).
697
698 $ The PID of the shell or, if it is a subshell, the PID of the
699 original shell. Do NOT use this mechanism for generating tempo‐
700 rary file names; see mktemp(1) instead.
701
702 - The concatenation of the current single letter options (see the
703 set command below for a list of options).
704
705 ? The exit status of the last non-asynchronous command executed.
706 If the last command was killed by a signal, $? is set to 128 plus
707 the signal number, but at most 255.
708
709 0 The name of the shell, determined as follows: the first argument
710 to mksh if it was invoked with the -c option and arguments were
711 given; otherwise the file argument, if it was supplied; or else
712 the basename the shell was invoked with (i.e. argv[0]). $0 is
713 also set to the name of the current script or the name of the
714 current function, if it was defined with the function keyword
715 (i.e. a Korn shell style function).
716
717 1 .. 9 The first nine positional parameters that were supplied to the
718 shell, function, or script sourced using the “.” built-in. Fur‐
719 ther positional parameters may be accessed using ${number}.
720
721 * All positional parameters (except 0), i.e. $1, $2, $3, ...
722 If used outside of double quotes, parameters are separate words
723 (which are subjected to word splitting); if used within double
724 quotes, parameters are separated by the first character of the
725 IFS parameter (or the empty string if IFS is unset.
726
727 @ Same as $*, unless it is used inside double quotes, in which case
728 a separate word is generated for each positional parameter. If
729 there are no positional parameters, no word is generated. "$@"
730 can be used to access arguments, verbatim, without losing empty
731 arguments or splitting arguments with spaces (IFS, actually).
732
733 The following parameters are set and/or used by the shell:
734
735 _ (underscore) When an external command is executed by the
736 shell, this parameter is set in the environment of the new
737 process to the path of the executed command. In interactive
738 use, this parameter is also set in the parent shell to the
739 last word of the previous command.
740
741 BASHPID The PID of the shell or subshell.
742
743 CDPATH Like PATH, but used to resolve the argument to the cd built-
744 in command. Note that if CDPATH is set and does not contain
745 “.” or an empty string element, the current directory is not
746 searched. Also, the cd built-in command will display the
747 resulting directory when a match is found in any search path
748 other than the empty path.
749
750 COLUMNS Set to the number of columns on the terminal or window. If
751 never unset and not imported, always set dynamically; unless
752 the value as reported by stty(1) is non-zero and sane enough
753 (minimum is 12x3), defaults to 80; similar for LINES. This
754 parameter is used by the interactive line editing modes and
755 by the select, set -o and kill -l commands to format infor‐
756 mation columns. Importing from the environment or unsetting
757 this parameter removes the binding to the actual terminal
758 size in favour of the provided value.
759
760 ENV If this parameter is found to be set after any profile files
761 are executed, the expanded value is used as a shell startup
762 file. It typically contains function and alias definitions.
763
764 EPOCHREALTIME
765 Time since the epoch, as returned by gettimeofday(2), for‐
766 matted as decimal tv_sec followed by a dot (‘.’) and tv_usec
767 padded to exactly six decimal digits.
768
769 EXECSHELL If set, this parameter is assumed to contain the shell that
770 is to be used to execute commands that execve(2) fails to
771 execute and which do not start with a “#!shell” sequence.
772
773 FCEDIT The editor used by the fc command (see below).
774
775 FPATH Like PATH, but used when an undefined function is executed
776 to locate the file defining the function. It is also
777 searched when a command can't be found using PATH. See
778 Functions below for more information.
779
780 HISTFILE The name of the file used to store command history. When
781 assigned to or unset, the file is opened, history is trun‐
782 cated then loaded from the file; subsequent new commands
783 (possibly consisting of several lines) are appended once
784 they successfully compiled. Also, several invocations of
785 the shell will share history if their HISTFILE parameters
786 all point to the same file.
787
788 Note: If HISTFILE is unset or empty, no history file is
789 used. This is different from AT&T UNIX ksh.
790
791 HISTSIZE The number of commands normally stored for history. The
792 default is 2047. Do not set this value to insanely high
793 values such as 1000000000 because mksh can then not allocate
794 enough memory for the history and will not start.
795
796 HOME The default directory for the cd command and the value sub‐
797 stituted for an unqualified ~ (see Tilde expansion below).
798
799 IFS Internal field separator, used during substitution and by
800 the read command, to split values into distinct arguments;
801 normally set to space, tab and newline. See Substitution
802 above for details.
803
804 Note: This parameter is not imported from the environment
805 when the shell is started.
806
807 KSHEGID The effective group id of the shell.
808
809 KSHGID The real group id of the shell.
810
811 KSHUID The real user id of the shell.
812
813 KSH_MATCH The last matched string. In a future version, this will be
814 an indexed array, with indexes 1 and up capturing matching
815 groups. Set by string comparisons (== and !=) in double-
816 bracket test expressions when a match is found (when !=
817 returns false), by case when a match is encountered, and by
818 the substitution operations ${x#pat}, ${x##pat}, ${x%pat},
819 ${x%%pat}, ${x/pat/rpl}, ${x/#pat/rpl}, ${x/%pat/rpl},
820 ${x//pat/rpl}, and ${x@/pat/rpl}. See the end of the Emacs
821 editing mode documentation for an example.
822
823 KSH_VERSION The name and version of the shell (read-only). See also the
824 version commands in Emacs editing mode and Vi editing mode
825 sections, below.
826
827 LINENO The line number of the function or shell script that is cur‐
828 rently being executed.
829
830 LINES Set to the number of lines on the terminal or window.
831 Defaults to 24; always set, unless imported or unset. See
832 COLUMNS.
833
834 OLDPWD The previous working directory. Unset if cd has not suc‐
835 cessfully changed directories since the shell started or if
836 the shell doesn't know where it is.
837
838 OPTARG When using getopts, it contains the argument for a parsed
839 option, if it requires one.
840
841 OPTIND The index of the next argument to be processed when using
842 getopts. Assigning 1 to this parameter causes getopts to
843 process arguments from the beginning the next time it is
844 invoked.
845
846 PATH A colon (semicolon on OS/2) separated list of directories
847 that are searched when looking for commands and files
848 sourced using the “.” command (see below). An empty string
849 resulting from a leading or trailing (semi)colon, or two
850 adjacent ones, is treated as a “.” (the current directory).
851
852 PATHSEP A colon (semicolon on OS/2), for the user's convenience.
853
854 PGRP The process ID of the shell's process group leader.
855
856 PIPESTATUS An array containing the errorlevel (exit status) codes, one
857 by one, of the last pipeline run in the foreground.
858
859 PPID The process ID of the shell's parent.
860
861 PS1 The primary prompt for interactive shells. Parameter, com‐
862 mand and arithmetic substitutions are performed, and ‘!’ is
863 replaced with the current command number (see the fc command
864 below). A literal ‘!’ can be put in the prompt by placing
865 “!!” in PS1.
866
867 The default prompt is “$ ” for non-root users, “# ” for
868 root. If mksh is invoked by root and PS1 does not contain a
869 ‘#’ character, the default value will be used even if PS1
870 already exists in the environment.
871
872 The mksh distribution comes with a sample dot.mkshrc con‐
873 taining a sophisticated example, but you might like the fol‐
874 lowing one (note that ${HOSTNAME:=$(hostname)} and the root-
875 vs-user distinguishing clause are (in this example) executed
876 at PS1 assignment time, while the $USER and $PWD are escaped
877 and thus will be evaluated each time a prompt is displayed):
878
879 PS1='${USER:=$(id -un)}'"@${HOSTNAME:=$(hostname)}:\$PWD $(
880 if (( USER_ID )); then print \$; else print \#; fi) "
881
882 Note that since the command-line editors try to figure out
883 how long the prompt is (so they know how far it is to the
884 edge of the screen), escape codes in the prompt tend to mess
885 things up. You can tell the shell not to count certain
886 sequences (such as escape codes) by prefixing your prompt
887 with a character (such as Ctrl-A) followed by a carriage
888 return and then delimiting the escape codes with this char‐
889 acter. Any occurrences of that character in the prompt are
890 not printed. By the way, don't blame me for this hack; it's
891 derived from the original ksh88(1), which did print the
892 delimiter character so you were out of luck if you did not
893 have any non-printing characters.
894
895 Since backslashes and other special characters may be inter‐
896 preted by the shell, to set PS1 either escape the backslash
897 itself or use double quotes. The latter is more practical.
898 This is a more complex example, avoiding to directly enter
899 special characters (for example with ^V in the emacs editing
900 mode), which embeds the current working directory, in
901 reverse video (colour would work, too), in the prompt
902 string:
903
904 x=$(print \\001) # otherwise unused char
905 PS1="$x$(print \\r)$x$(tput so)$x\$PWD$x$(tput se)$x> "
906
907 Due to a strong suggestion from David G. Korn, mksh now also
908 supports the following form:
909
910 PS1=$'\1\r\1\e[7m\1$PWD\1\e[0m\1> '
911
912 PS2 Secondary prompt string, by default “> ”, used when more
913 input is needed to complete a command.
914
915 PS3 Prompt used by the select statement when reading a menu
916 selection. The default is “#? ”.
917
918 PS4 Used to prefix commands that are printed during execution
919 tracing (see the set -x command below). Parameter, command
920 and arithmetic substitutions are performed before it is
921 printed. The default is “+ ”. You may want to set it to
922 “[$EPOCHREALTIME] ” instead, to include timestamps.
923
924 PWD The current working directory. May be unset or empty if the
925 shell doesn't know where it is.
926
927 RANDOM Each time RANDOM is referenced, it is assigned a number
928 between 0 and 32767 from a Linear Congruential PRNG first.
929
930 REPLY Default parameter for the read command if no names are
931 given. Also used in select loops to store the value that is
932 read from standard input.
933
934 SECONDS The number of seconds since the shell started or, if the
935 parameter has been assigned an integer value, the number of
936 seconds since the assignment plus the value that was
937 assigned.
938
939 TMOUT If set to a positive integer in an interactive shell, it
940 specifies the maximum number of seconds the shell will wait
941 for input after printing the primary prompt (PS1). If the
942 time is exceeded, the shell exits.
943
944 TMPDIR The directory temporary shell files are created in. If this
945 parameter is not set or does not contain the absolute path
946 of a writable directory, temporary files are created in
947 /tmp.
948
949 USER_ID The effective user id of the shell.
950
951 Tilde expansion
952 Tilde expansion, which is done in parallel with parameter substitution,
953 is applied to words starting with an unquoted ‘~’. In parameter assign‐
954 ments (such as those preceding a simple-command or those occurring in the
955 arguments of a declaration utility), tilde expansion is done after any
956 assignment (i.e. after the equals sign) or after an unquoted colon (‘:’);
957 login names are also delimited by colons. The Korn shell, except in
958 POSIX mode, always expands tildes after unquoted equals signs, not just
959 in assignment context (see below), and enables tab completion for tildes
960 after all unquoted colons during command line editing.
961
962 The characters following the tilde, up to the first ‘/’, if any, are
963 assumed to be a login name. If the login name is empty, ‘+’ or ‘-’, the
964 simplified value of the HOME, PWD or OLDPWD parameter is substituted,
965 respectively. Otherwise, the password file is searched for the login
966 name, and the tilde expression is substituted with the user's home direc‐
967 tory. If the login name is not found in the password file or if any
968 quoting or parameter substitution occurs in the login name, no substitu‐
969 tion is performed.
970
971 The home directory of previously expanded login names are cached and re-
972 used. The alias -d command may be used to list, change and add to this
973 cache (e.g. alias -d fac=/usr/local/facilities; cd ~fac/bin).
974
975 Brace expansion (alternation)
976 Brace expressions take the following form:
977
978 prefix{str1,...,strN}suffix
979
980 The expressions are expanded to N words, each of which is the concatena‐
981 tion of prefix, stri and suffix (e.g. “a{c,b{X,Y},d}e” expands to four
982 words: “ace”, “abXe”, “abYe” and “ade”). As noted in the example, brace
983 expressions can be nested and the resulting words are not sorted. Brace
984 expressions must contain an unquoted comma (‘,’) for expansion to occur
985 (e.g. {} and {foo} are not expanded). Brace expansion is carried out
986 after parameter substitution and before file name generation.
987
988 File name patterns
989 A file name pattern is a word containing one or more unquoted ‘?’, ‘*’,
990 ‘+’, ‘@’ or ‘!’ characters or “[...]” sequences. Once brace expansion
991 has been performed, the shell replaces file name patterns with the sorted
992 names of all the files that match the pattern (if no files match, the
993 word is left unchanged). The pattern elements have the following mean‐
994 ing:
995
996 ? Matches any single character.
997
998 * Matches any sequence of octets.
999
1000 [...] Matches any of the octets inside the brackets. Ranges of octets
1001 can be specified by separating two octets by a ‘-’ (e.g. “[a0-9]”
1002 matches the letter ‘a’ or any digit). In order to represent
1003 itself, a ‘-’ must either be quoted or the first or last octet in
1004 the octet list. Similarly, a ‘]’ must be quoted or the first
1005 octet in the list if it is to represent itself instead of the end
1006 of the list. Also, a ‘!’ appearing at the start of the list has
1007 special meaning (see below), so to represent itself it must be
1008 quoted or appear later in the list.
1009
1010 [!...] Like [...], except it matches any octet not inside the brackets.
1011
1012 *(pattern|...|pattern)
1013 Matches any string of octets that matches zero or more occur‐
1014 rences of the specified patterns. Example: The pattern
1015 *(foo|bar) matches the strings “”, “foo”, “bar”, “foobarfoo”,
1016 etc.
1017
1018 +(pattern|...|pattern)
1019 Matches any string of octets that matches one or more occurrences
1020 of the specified patterns. Example: The pattern +(foo|bar)
1021 matches the strings “foo”, “bar”, “foobar”, etc.
1022
1023 ?(pattern|...|pattern)
1024 Matches the empty string or a string that matches one of the
1025 specified patterns. Example: The pattern ?(foo|bar) only matches
1026 the strings “”, “foo” and “bar”.
1027
1028 @(pattern|...|pattern)
1029 Matches a string that matches one of the specified patterns.
1030 Example: The pattern @(foo|bar) only matches the strings “foo”
1031 and “bar”.
1032
1033 !(pattern|...|pattern)
1034 Matches any string that does not match one of the specified pat‐
1035 terns. Examples: The pattern !(foo|bar) matches all strings
1036 except “foo” and “bar”; the pattern !(*) matches no strings; the
1037 pattern !(?)* matches all strings (think about it).
1038
1039 Note that complicated globbing, especially with alternatives, is slow;
1040 using separate comparisons may (or may not) be faster.
1041
1042 Note that mksh (and pdksh) never matches “.” and “..”, but AT&T UNIX ksh,
1043 Bourne sh and GNU bash do.
1044
1045 Note that none of the above pattern elements match either a period (‘.’)
1046 at the start of a file name or a slash (‘/’), even if they are explicitly
1047 used in a [...] sequence; also, the names “.” and “..” are never matched,
1048 even by the pattern “.*”.
1049
1050 If the markdirs option is set, any directories that result from file name
1051 generation are marked with a trailing ‘/’.
1052
1053 Input/output redirection
1054 When a command is executed, its standard input, standard output and stan‐
1055 dard error (file descriptors 0, 1 and 2, respectively) are normally
1056 inherited from the shell. Three exceptions to this are commands in pipe‐
1057 lines, for which standard input and/or standard output are those set up
1058 by the pipeline, asynchronous commands created when job control is dis‐
1059 abled, for which standard input is initially set to /dev/null, and com‐
1060 mands for which any of the following redirections have been specified:
1061
1062 >file Standard output is redirected to file. If file does not
1063 exist, it is created; if it does exist, is a regular file,
1064 and the noclobber option is set, an error occurs; otherwise,
1065 the file is truncated. Note that this means the command cmd
1066 <foo >foo will open foo for reading and then truncate it when
1067 it opens it for writing, before cmd gets a chance to actually
1068 read foo.
1069
1070 >|file Same as >, except the file is truncated, even if the
1071 noclobber option is set.
1072
1073 >>file Same as >, except if file exists it is appended to instead of
1074 being truncated. Also, the file is opened in append mode, so
1075 writes always go to the end of the file (see open(2)).
1076
1077 <file Standard input is redirected from file, which is opened for
1078 reading.
1079
1080 <>file Same as <, except the file is opened for reading and writing.
1081
1082 <<marker After reading the command line containing this kind of redi‐
1083 rection (called a “here document”), the shell copies lines
1084 from the command source into a temporary file until a line
1085 matching marker is read. When the command is executed, stan‐
1086 dard input is redirected from the temporary file. If marker
1087 contains no quoted characters, the contents of the temporary
1088 file are processed as if enclosed in double quotes each time
1089 the command is executed, so parameter, command and arithmetic
1090 substitutions are performed, along with backslash (‘\’)
1091 escapes for ‘$’, ‘`’, ‘\’ and “\newline”, but not for ‘"’.
1092 If multiple here documents are used on the same command line,
1093 they are saved in order.
1094
1095 If no marker is given, the here document ends at the next <<
1096 and substitution will be performed. If marker is only a set
1097 of either single “''” or double ‘""’ quotes with nothing in
1098 between, the here document ends at the next empty line and
1099 substitution will not be performed.
1100
1101 <<-marker Same as <<, except leading tabs are stripped from lines in
1102 the here document.
1103
1104 <<<word Same as <<, except that word is the here document. This is
1105 called a here string.
1106
1107 <&fd Standard input is duplicated from file descriptor fd. fd can
1108 be a single digit, indicating the number of an existing file
1109 descriptor; the letter ‘p’, indicating the file descriptor
1110 associated with the output of the current co-process; or the
1111 character ‘-’, indicating standard input is to be closed.
1112
1113 >&fd Same as <&, except the operation is done on standard output.
1114
1115 &>file Same as >file 2>&1. This is a deprecated (legacy) GNU bash
1116 extension supported by mksh which also supports the preceding
1117 explicit fd digit, for example, 3&>file is the same as 3>file
1118 2>&3 in mksh but a syntax error in GNU bash.
1119
1120 &>|file, &>>file, &>&fd
1121 Same as >|file, >>file or >&fd, followed by 2>&1, as above.
1122 These are mksh extensions.
1123
1124 In any of the above redirections, the file descriptor that is redirected
1125 (i.e. standard input or standard output) can be explicitly given by pre‐
1126 ceding the redirection with a single digit. Parameter, command and
1127 arithmetic substitutions, tilde substitutions, and, if the shell is
1128 interactive, file name generation are all performed on the file, marker
1129 and fd arguments of redirections. Note, however, that the results of any
1130 file name generation are only used if a single file is matched; if multi‐
1131 ple files match, the word with the expanded file name generation charac‐
1132 ters is used. Note that in restricted shells, redirections which can
1133 create files cannot be used.
1134
1135 For simple-commands, redirections may appear anywhere in the command; for
1136 compound-commands (if statements, etc.), any redirections must appear at
1137 the end. Redirections are processed after pipelines are created and in
1138 the order they are given, so the following will print an error with a
1139 line number prepended to it:
1140
1141 $ cat /foo/bar 2>&1 >/dev/null | pr -n -t
1142
1143 File descriptors created by I/O redirections are private to the shell.
1144
1145 Arithmetic expressions
1146 Integer arithmetic expressions can be used with the let command, inside
1147 $((...)) expressions, inside array references (e.g. name[expr]), as
1148 numeric arguments to the test command, and as the value of an assignment
1149 to an integer parameter. Warning: This also affects implicit conversion
1150 to integer, for example as done by the let command. Never use unchecked
1151 user input, e.g. from the environment, in an arithmetic context!
1152
1153 Expressions are calculated using signed arithmetic and the mksh_ari_t
1154 type (a 32-bit signed integer), unless they begin with a sole ‘#’ charac‐
1155 ter, in which case they use mksh_uari_t (a 32-bit unsigned integer).
1156
1157 Expressions may contain alpha-numeric parameter identifiers, array refer‐
1158 ences and integer constants and may be combined with the following C
1159 operators (listed and grouped in increasing order of precedence):
1160
1161 Unary operators:
1162
1163 + - ! ~ ++ --
1164
1165 Binary operators:
1166
1167 ,
1168 = += -= *= /= %= <<= >>= ^<= ^>= &= ^= |=
1169 ||
1170 &&
1171 |
1172 ^
1173 &
1174 == !=
1175 < <= > >=
1176 << >> ^< ^>
1177 + -
1178 * / %
1179
1180 Ternary operators:
1181
1182 ?: (precedence is immediately higher than assignment)
1183
1184 Grouping operators:
1185
1186 ( )
1187
1188 Integer constants and expressions are calculated using an exactly 32-bit
1189 wide, signed or unsigned, type with silent wraparound on integer over‐
1190 flow. Integer constants may be specified with arbitrary bases using the
1191 notation base#number, where base is a decimal integer specifying the base
1192 (up to 36), and number is a number in the specified base. Additionally,
1193 base-16 integers may be specified by prefixing them with “0x”
1194 (case-insensitive) in all forms of arithmetic expressions, except as
1195 numeric arguments to the test built-in utility. Prefixing numbers with a
1196 sole digit zero (“0”) does not cause interpretation as octal (except in
1197 POSIX mode, as required by the standard), as that's unsafe to do.
1198
1199 As a special mksh extension, numbers to the base of one are treated as
1200 either (8-bit transparent) ASCII or Universal Coded Character Set code‐
1201 points, depending on the shell's utf8-mode flag (current setting). The
1202 AT&T UNIX ksh93 syntax of “'x'” instead of “1#x” is also supported. Note
1203 that NUL bytes (integral value of zero) cannot be used. An unset or
1204 empty parameter evaluates to 0 in integer context. In UTF-8 mode, raw
1205 octets are mapped into the range EF80..EFFF as in OPTU-8, which is in the
1206 PUA and has been assigned by CSUR for this use. If more than one octet
1207 in ASCII mode, or a sequence of more than one octet not forming a valid
1208 and minimal CESU-8 sequence is passed, the behaviour is undefined (usu‐
1209 ally, the shell aborts with a parse error, but rarely, it succeeds, e.g.
1210 on the sequence C2 20). That's why you should always use ASCII mode
1211 unless you know that the input is well-formed UTF-8 in the range of
1212 0000..FFFD if you use this feature, as opposed to read -a.
1213
1214 The operators are evaluated as follows:
1215
1216 unary +
1217 Result is the argument (included for completeness).
1218
1219 unary -
1220 Negation.
1221
1222 ! Logical NOT; the result is 1 if argument is zero, 0 if not.
1223
1224 ~ Arithmetic (bit-wise) NOT.
1225
1226 ++ Increment; must be applied to a parameter (not a literal or
1227 other expression). The parameter is incremented by 1.
1228 When used as a prefix operator, the result is the incre‐
1229 mented value of the parameter; when used as a postfix oper‐
1230 ator, the result is the original value of the parameter.
1231
1232 -- Similar to ++, except the parameter is decremented by 1.
1233
1234 , Separates two arithmetic expressions; the left-hand side is
1235 evaluated first, then the right. The result is the value
1236 of the expression on the right-hand side.
1237
1238 = Assignment; the variable on the left is set to the value on
1239 the right.
1240
1241 += -= *= /= %= <<= >>= ^<= ^>= &= ^= |=
1242 Assignment operators. <var><op>=<expr> is the same as
1243 <var>=<var><op><expr>, with any operator precedence in
1244 <expr> preserved. For example, “var1 *= 5 + 3” is the same
1245 as specifying “var1 = var1 * (5 + 3)”.
1246
1247 || Logical OR; the result is 1 if either argument is non-zero,
1248 0 if not. The right argument is evaluated only if the left
1249 argument is zero.
1250
1251 && Logical AND; the result is 1 if both arguments are non-
1252 zero, 0 if not. The right argument is evaluated only if
1253 the left argument is non-zero.
1254
1255 | Arithmetic (bit-wise) OR.
1256
1257 ^ Arithmetic (bit-wise) XOR (exclusive-OR).
1258
1259 & Arithmetic (bit-wise) AND.
1260
1261 == Equal; the result is 1 if both arguments are equal, 0 if
1262 not.
1263
1264 != Not equal; the result is 0 if both arguments are equal, 1
1265 if not.
1266
1267 < Less than; the result is 1 if the left argument is less
1268 than the right, 0 if not.
1269
1270 <= > >=
1271 Less than or equal, greater than, greater than or equal.
1272 See <.
1273
1274 << >> Shift left (right); the result is the left argument with
1275 its bits arithmetically (signed operation) or logically
1276 (unsigned expression) shifted left (right) by the amount
1277 given in the right argument.
1278
1279 ^< ^> Rotate left (right); the result is similar to shift, except
1280 that the bits shifted out at one end are shifted in at the
1281 other end, instead of zero or sign bits.
1282
1283 + - * /
1284 Addition, subtraction, multiplication and division.
1285
1286 % Remainder; the result is the symmetric remainder of the
1287 division of the left argument by the right. To get the
1288 mathematical modulus of “a mod b”, use the formula “(a % b
1289 + b) % b”.
1290
1291 <arg1>?<arg2>:<arg3>
1292 If <arg1> is non-zero, the result is <arg2>; otherwise the
1293 result is <arg3>. The non-result argument is not evalu‐
1294 ated.
1295
1296 Co-processes
1297 A co-process (which is a pipeline created with the “|&” operator) is an
1298 asynchronous process that the shell can both write to (using print -p)
1299 and read from (using read -p). The input and output of the co-process
1300 can also be manipulated using >&p and <&p redirections, respectively.
1301 Once a co-process has been started, another can't be started until the
1302 co-process exits, or until the co-process's input has been redirected
1303 using an exec n>&p redirection. If a co-process's input is redirected in
1304 this way, the next co-process to be started will share the output with
1305 the first co-process, unless the output of the initial co-process has
1306 been redirected using an exec n<&p redirection.
1307
1308 Some notes concerning co-processes:
1309
1310 · The only way to close the co-process's input (so the co-process reads
1311 an end-of-file) is to redirect the input to a numbered file descrip‐
1312 tor and then close that file descriptor: exec 3>&p; exec 3>&-
1313
1314 · In order for co-processes to share a common output, the shell must
1315 keep the write portion of the output pipe open. This means that end-
1316 of-file will not be detected until all co-processes sharing the co-
1317 process's output have exited (when they all exit, the shell closes
1318 its copy of the pipe). This can be avoided by redirecting the output
1319 to a numbered file descriptor (as this also causes the shell to close
1320 its copy). Note that this behaviour is slightly different from the
1321 original Korn shell which closes its copy of the write portion of the
1322 co-process output when the most recently started co-process (instead
1323 of when all sharing co-processes) exits.
1324
1325 · print -p will ignore SIGPIPE signals during writes if the signal is
1326 not being trapped or ignored; the same is true if the co-process
1327 input has been duplicated to another file descriptor and print -un is
1328 used.
1329
1330 Functions
1331 Functions are defined using either Korn shell function function-name syn‐
1332 tax or the Bourne/POSIX shell function-name() syntax (see below for the
1333 difference between the two forms). Functions are like .‐scripts (i.e.
1334 scripts sourced using the “.” built-in) in that they are executed in the
1335 current environment. However, unlike .‐scripts, shell arguments (i.e.
1336 positional parameters $1, $2, etc.) are never visible inside them. When
1337 the shell is determining the location of a command, functions are
1338 searched after special built-in commands, before builtins and the PATH is
1339 searched.
1340
1341 An existing function may be deleted using unset -f function-name. A list
1342 of functions can be obtained using typeset +f and the function defini‐
1343 tions can be listed using typeset -f. The autoload command (which is an
1344 alias for typeset -fu) may be used to create undefined functions: when an
1345 undefined function is executed, the shell searches the path specified in
1346 the FPATH parameter for a file with the same name as the function which,
1347 if found, is read and executed. If after executing the file the named
1348 function is found to be defined, the function is executed; otherwise, the
1349 normal command search is continued (i.e. the shell searches the regular
1350 built-in command table and PATH). Note that if a command is not found
1351 using PATH, an attempt is made to autoload a function using FPATH (this
1352 is an undocumented feature of the original Korn shell).
1353
1354 Functions can have two attributes, “trace” and “export”, which can be set
1355 with typeset -ft and typeset -fx, respectively. When a traced function
1356 is executed, the shell's xtrace option is turned on for the function's
1357 duration. The “export” attribute of functions is currently not used.
1358
1359 Since functions are executed in the current shell environment, parameter
1360 assignments made inside functions are visible after the function com‐
1361 pletes. If this is not the desired effect, the typeset command can be
1362 used inside a function to create a local parameter. Note that AT&T UNIX
1363 ksh93 uses static scoping (one global scope, one local scope per func‐
1364 tion) and allows local variables only on Korn style functions, whereas
1365 mksh uses dynamic scoping (nested scopes of varying locality). Note that
1366 special parameters (e.g. $$, $!) can't be scoped in this way.
1367
1368 The exit status of a function is that of the last command executed in the
1369 function. A function can be made to finish immediately using the return
1370 command; this may also be used to explicitly specify the exit status.
1371 Note that when called in a subshell, return will only exit that subshell
1372 and will not cause the original shell to exit a running function (see the
1373 while...read loop FAQ below).
1374
1375 Functions defined with the function reserved word are treated differently
1376 in the following ways from functions defined with the () notation:
1377
1378 · The $0 parameter is set to the name of the function (Bourne-style
1379 functions leave $0 untouched).
1380
1381 · Parameter assignments preceding function calls are not kept in the
1382 shell environment (executing Bourne-style functions will keep assign‐
1383 ments).
1384
1385 · OPTIND is saved/reset and restored on entry and exit from the func‐
1386 tion so getopts can be used properly both inside and outside the
1387 function (Bourne-style functions leave OPTIND untouched, so using
1388 getopts inside a function interferes with using getopts outside the
1389 function).
1390
1391 · Shell options (set -o) have local scope, i.e. changes inside a func‐
1392 tion are reset upon its exit.
1393
1394 In the future, the following differences may also be added:
1395
1396 · A separate trap/signal environment will be used during the execution
1397 of functions. This will mean that traps set inside a function will
1398 not affect the shell's traps and signals that are not ignored in the
1399 shell (but may be trapped) will have their default effect in a func‐
1400 tion.
1401
1402 · The EXIT trap, if set in a function, will be executed after the func‐
1403 tion returns.
1404
1405 Command execution
1406 After evaluation of command-line arguments, redirections and parameter
1407 assignments, the type of command is determined: a special built-in com‐
1408 mand, a function, a normal builtin or the name of a file to execute found
1409 using the PATH parameter. The checks are made in the above order. Spe‐
1410 cial built-in commands differ from other commands in that the PATH param‐
1411 eter is not used to find them, an error during their execution can cause
1412 a non-interactive shell to exit, and parameter assignments that are spec‐
1413 ified before the command are kept after the command completes. Regular
1414 built-in commands are different only in that the PATH parameter is not
1415 used to find them.
1416
1417 The original ksh and POSIX differ somewhat in which commands are consid‐
1418 ered special or regular.
1419
1420 POSIX special built-in utilities:
1421
1422 ., :, break, continue, eval, exec, exit, export, readonly, return, set,
1423 shift, times, trap, unset
1424
1425 Additional mksh commands keeping assignments:
1426
1427 global, source, typeset
1428
1429 Builtins that are not special:
1430
1431 [, alias, bg, bind, builtin, cat, cd, command, echo, false, fc, fg,
1432 getopts, jobs, kill, let, print, pwd, read, realpath, rename, sleep,
1433 suspend, test, true, ulimit, umask, unalias, wait, whence
1434
1435 Once the type of command has been determined, any command-line parameter
1436 assignments are performed and exported for the duration of the command.
1437
1438 The following describes the special and regular built-in commands and
1439 builtin-like reserved words:
1440
1441 . file [arg ...]
1442 This is called the “dot” command. Execute the commands in file in
1443 the current environment. The file is searched for in the directo‐
1444 ries of PATH. If arguments are given, the positional parameters
1445 may be used to access them while file is being executed. If no
1446 arguments are given, the positional parameters are those of the
1447 environment the command is used in.
1448
1449 : [...]
1450 The null command. Exit status is set to zero.
1451
1452 [ expression ]
1453 See test.
1454
1455 alias [-d | -t [-r] | +-x] [-p] [+] [name [=value] ...]
1456 Without arguments, alias lists all aliases. For any name without
1457 a value, the existing alias is listed. Any name with a value
1458 defines an alias; see Aliases above. [][A-Za-z0-9_!%,.@:-] are
1459 valid in names, except they may not begin with a hyphen-minus, and
1460 [[ is not a valid alias name.
1461
1462 When listing aliases, one of two formats is used. Normally,
1463 aliases are listed as name=value, where value is quoted. If
1464 options were preceded with ‘+’, or a lone ‘+’ is given on the com‐
1465 mand line, only name is printed.
1466
1467 The -d option causes directory aliases which are used in tilde
1468 expansion to be listed or set (see Tilde expansion above).
1469
1470 If the -p option is used, each alias is prefixed with the string
1471 “alias ”.
1472
1473 The -t option indicates that tracked aliases are to be listed/set
1474 (values specified on the command line are ignored for tracked
1475 aliases). The -r option indicates that all tracked aliases are to
1476 be reset.
1477
1478 The -x option sets (+x clears) the export attribute of an alias,
1479 or, if no names are given, lists the aliases with the export
1480 attribute (exporting an alias has no effect).
1481
1482 bg [job ...]
1483 Resume the specified stopped job(s) in the background. If no jobs
1484 are specified, %+ is assumed. See Job control below for more
1485 information.
1486
1487 bind [-l]
1488 The current bindings are listed. If the -l flag is given, bind
1489 instead lists the names of the functions to which keys may be
1490 bound. See Emacs editing mode for more information.
1491
1492 bind [-m] string=[substitute] ...
1493 bind string=[editing-command] ...
1494 The specified editing command is bound to the given string, which
1495 should consist of a control character optionally preceded by one
1496 of the two prefix characters and optionally succeeded by a tilde
1497 character. Future input of the string will cause the editing com‐
1498 mand to be immediately invoked. If the -m flag is given, the
1499 specified input string will afterwards be immediately replaced by
1500 the given substitute string which may contain editing commands but
1501 not other macros. If a tilde postfix is given, a tilde trailing
1502 the one or two prefices and the control character is ignored, any
1503 other trailing character will be processed afterwards.
1504
1505 Control characters may be written using caret notation i.e. ^X
1506 represents Ctrl-X. The caret itself can be escaped by a back‐
1507 slash, which also escapes itself. Note that although only three
1508 prefix characters (usually ESC, ^X and NUL) are supported, some
1509 multi-character sequences can be supported.
1510
1511 The following default bindings show how the arrow keys, the home,
1512 end and delete key on a BSD wsvt25, xterm-xfree86 or GNU screen
1513 terminal are bound (of course some escape sequences won't work out
1514 quite this nicely):
1515
1516 bind '^X'=prefix-2
1517 bind '^[['=prefix-2
1518 bind '^XA'=up-history
1519 bind '^XB'=down-history
1520 bind '^XC'=forward-char
1521 bind '^XD'=backward-char
1522 bind '^X1~'=beginning-of-line
1523 bind '^X7~'=beginning-of-line
1524 bind '^XH'=beginning-of-line
1525 bind '^X4~'=end-of-line
1526 bind '^X8~'=end-of-line
1527 bind '^XF'=end-of-line
1528 bind '^X3~'=delete-char-forward
1529
1530 break [level]
1531 Exit the levelth inner-most for, select, until or while loop.
1532 level defaults to 1.
1533
1534 builtin [--] command [arg ...]
1535 Execute the built-in command command.
1536
1537 \builtin command [arg ...]
1538 Same as builtin. Additionally acts as declaration utility for‐
1539 warder, i.e. this is a declaration utility (see Tilde expansion)
1540 iff command is a declaration utility.
1541
1542 cat [-u] [file ...]
1543 Read files sequentially, in command line order, and write them to
1544 standard output. If a file is a single dash (“-”) or absent, read
1545 from standard input. For direct builtin calls, the POSIX -u
1546 option is supported as a no-op. For calls from shell, if any
1547 options are given, an external cat(1) utility is preferred over
1548 the builtin.
1549
1550 cd [-L] [dir]
1551 cd -P [-e] [dir]
1552 chdir [-eLP] [dir]
1553 Set the working directory to dir. If the parameter CDPATH is set,
1554 it lists the search path for the directory containing dir. An
1555 unset or empty path means the current directory. If dir is found
1556 in any component of the CDPATH search path other than an unset or
1557 empty path, the name of the new working directory will be written
1558 to standard output. If dir is missing, the home directory HOME is
1559 used. If dir is “-”, the previous working directory is used (see
1560 the OLDPWD parameter).
1561
1562 If the -L option (logical path) is used or if the physical option
1563 isn't set (see the set command below), references to “..” in dir
1564 are relative to the path used to get to the directory. If the -P
1565 option (physical path) is used or if the physical option is set,
1566 “..” is relative to the filesystem directory tree. The PWD and
1567 OLDPWD parameters are updated to reflect the current and old work‐
1568 ing directory, respectively. If the -e option is set for physical
1569 filesystem traversal and PWD could not be set, the exit code is 1;
1570 greater than 1 if an error occurred, 0 otherwise.
1571
1572 cd [-eLP] old new
1573 chdir [-eLP] old new
1574 The string new is substituted for old in the current directory,
1575 and the shell attempts to change to the new directory.
1576
1577 command [-pVv] cmd [arg ...]
1578 If neither the -v nor -V option is given, cmd is executed exactly
1579 as if command had not been specified, with two exceptions:
1580 firstly, cmd cannot be a shell function; and secondly, special
1581 built-in commands lose their specialness (i.e. redirection and
1582 utility errors do not cause the shell to exit, and command assign‐
1583 ments are not permanent). The declaration utility property is not
1584 reset.
1585
1586 If the -p option is given, a default search path is used instead
1587 of the current value of PATH, the actual value of which is system
1588 dependent.
1589
1590 If the -v option is given, instead of executing cmd, information
1591 about what would be executed is given (and the same is done for
1592 arg ...). For builtins, functions and keywords, their names are
1593 simply printed; for aliases, a command that defines them is
1594 printed; for utilities found by searching the PATH parameter, the
1595 full path of the command is printed. If no command is found (i.e.
1596 the path search fails), nothing is printed and command exits with
1597 a non-zero status. The -V option is like the -v option, except it
1598 is more verbose.
1599
1600 continue [level]
1601 Jumps to the beginning of the levelth inner-most for, select,
1602 until or while loop. level defaults to 1.
1603
1604 echo [-Een] [arg ...]
1605 Warning: this utility is not portable; use the Korn shell builtin
1606 print instead.
1607
1608 Prints its arguments (separated by spaces) followed by a newline,
1609 to the standard output. The newline is suppressed if any of the
1610 arguments contain the backslash sequence “\c”. See the print com‐
1611 mand below for a list of other backslash sequences that are recog‐
1612 nised.
1613
1614 The options are provided for compatibility with BSD shell scripts.
1615 The -n option suppresses the trailing newline, -e enables back‐
1616 slash interpretation (a no-op, since this is normally done), and
1617 -E suppresses backslash interpretation.
1618
1619 If the posix or sh option is set or this is a direct builtin call
1620 or print -R, only the first argument is treated as an option, and
1621 only if it is exactly “-n”. Backslash interpretation is disabled.
1622
1623 eval command ...
1624 The arguments are concatenated (with spaces between them) to form
1625 a single string which the shell then parses and executes in the
1626 current environment.
1627
1628 exec [-a argv0] [-c] [command [arg ...]]
1629 The command is executed without forking, replacing the shell
1630 process. This is currently absolute, i.e. exec never returns,
1631 even if the command is not found. The -a option permits setting a
1632 different argv[0] value, and -c clears the environment before exe‐
1633 cuting the child process, except for the _ variable and direct
1634 assignments.
1635
1636 If no command is given except for I/O redirection, the I/O redi‐
1637 rection is permanent and the shell is not replaced. Any file
1638 descriptors greater than 2 which are opened or dup(2)'d in this
1639 way are not made available to other executed commands (i.e. com‐
1640 mands that are not built-in to the shell). Note that the Bourne
1641 shell differs here; it does pass these file descriptors on.
1642
1643 exit [status]
1644 The shell or subshell exits with the specified exit status. If
1645 status is not specified, the exit status is the current value of
1646 the $? parameter.
1647
1648 export [-p] [parameter[=value]]
1649 Sets the export attribute of the named parameters. Exported
1650 parameters are passed in the environment to executed commands. If
1651 values are specified, the named parameters are also assigned.
1652 This is a declaration utility.
1653
1654 If no parameters are specified, all parameters with the export
1655 attribute set are printed one per line; either their names, or, if
1656 a “-” with no option letter is specified, name=value pairs, or,
1657 with -p, export commands suitable for re-entry.
1658
1659 false A command that exits with a non-zero status.
1660
1661 fc [-e editor | -l [-n]] [-r] [first [last]]
1662 first and last select commands from the history. Commands can be
1663 selected by history number (negative numbers go backwards from the
1664 current, most recent, line) or a string specifying the most recent
1665 command starting with that string. The -l option lists the com‐
1666 mand on standard output, and -n inhibits the default command num‐
1667 bers. The -r option reverses the order of the list. Without -l,
1668 the selected commands are edited by the editor specified with the
1669 -e option or, if no -e is specified, the editor specified by the
1670 FCEDIT parameter (if this parameter is not set, /bin/ed is used),
1671 and then executed by the shell.
1672
1673 fc -e - | -s [-g] [old=new] [prefix]
1674 Re-execute the selected command (the previous command by default)
1675 after performing the optional substitution of old with new. If -g
1676 is specified, all occurrences of old are replaced with new. The
1677 meaning of -e - and -s is identical: re-execute the selected com‐
1678 mand without invoking an editor. This command is usually accessed
1679 with the predefined: alias r='fc -e -'
1680
1681 fg [job ...]
1682 Resume the specified job(s) in the foreground. If no jobs are
1683 specified, %+ is assumed. See Job control below for more informa‐
1684 tion.
1685
1686 getopts optstring name [arg ...]
1687 Used by shell procedures to parse the specified arguments (or
1688 positional parameters, if no arguments are given) and to check for
1689 legal options. optstring contains the option letters that getopts
1690 is to recognise. If a letter is followed by a colon, the option
1691 is expected to have an argument. Options that do not take argu‐
1692 ments may be grouped in a single argument. If an option takes an
1693 argument and the option character is not the last character of the
1694 argument it is found in, the remainder of the argument is taken to
1695 be the option's argument; otherwise, the next argument is the
1696 option's argument.
1697
1698 Each time getopts is invoked, it places the next option in the
1699 shell parameter name and the index of the argument to be processed
1700 by the next call to getopts in the shell parameter OPTIND. If the
1701 option was introduced with a ‘+’, the option placed in name is
1702 prefixed with a ‘+’. When an option requires an argument, getopts
1703 places it in the shell parameter OPTARG.
1704
1705 When an illegal option or a missing option argument is encoun‐
1706 tered, a question mark or a colon is placed in name (indicating an
1707 illegal option or missing argument, respectively) and OPTARG is
1708 set to the option character that caused the problem. Furthermore,
1709 if optstring does not begin with a colon, a question mark is
1710 placed in name, OPTARG is unset, and an error message is printed
1711 to standard error.
1712
1713 When the end of the options is encountered, getopts exits with a
1714 non-zero exit status. Options end at the first (non-option argu‐
1715 ment) argument that does not start with a ‘-’, or when a “--”
1716 argument is encountered.
1717
1718 Option parsing can be reset by setting OPTIND to 1 (this is done
1719 automatically whenever the shell or a shell procedure is invoked).
1720
1721 Warning: Changing the value of the shell parameter OPTIND to a
1722 value other than 1 or parsing different sets of arguments without
1723 resetting OPTIND may lead to unexpected results.
1724
1725 global [+-aglpnrtUux] [-L[n] | -R[n] | -Z[n]] [-i[n]] [name [=value] ...]
1726 See typeset -g. Deprecated, will be removed from a future version
1727 of mksh.
1728
1729 hash [-r] [name ...]
1730 Without arguments, any hashed executable command pathnames are
1731 listed. The -r option causes all hashed commands to be removed
1732 from the hash table. Each name is searched as if it were a com‐
1733 mand name and added to the hash table if it is an executable com‐
1734 mand.
1735
1736 jobs [-lnp] [job ...]
1737 Display information about the specified job(s); if no jobs are
1738 specified, all jobs are displayed. The -n option causes informa‐
1739 tion to be displayed only for jobs that have changed state since
1740 the last notification. If the -l option is used, the process ID
1741 of each process in a job is also listed. The -p option causes
1742 only the process group of each job to be printed. See Job control
1743 below for the format of job and the displayed job.
1744
1745 kill [-s signame | -signum | -signame] { job | pid | pgrp } ...
1746 Send the specified signal to the specified jobs, process IDs or
1747 process groups. If no signal is specified, the TERM signal is
1748 sent. If a job is specified, the signal is sent to the job's
1749 process group. See Job control below for the format of job.
1750
1751 kill -l [exit-status ...]
1752 Print the signal name corresponding to exit-status. If no argu‐
1753 ments are specified, a list of all the signals with their numbers
1754 and a short description of each are printed.
1755
1756 let [expression ...]
1757 Each expression is evaluated (see Arithmetic expressions above).
1758 If all expressions are successfully evaluated, the exit status is
1759 0 (1) if the last expression evaluated to non-zero (zero). If an
1760 error occurs during the parsing or evaluation of an expression,
1761 the exit status is greater than 1. Since expressions may need to
1762 be quoted, (( expr )) is syntactic sugar for:
1763 { \\builtin let 'expr'; }
1764
1765 mknod [-m mode] name b|c major minor
1766 mknod [-m mode] name p
1767 Create a device special file. The file type may be b (block type
1768 device), c (character type device) or p (named pipe, FIFO). The
1769 file created may be modified according to its mode (via the -m
1770 option), major (major device number), and minor (minor device num‐
1771 ber). This is not normally part of mksh; however, distributors
1772 may have added this as builtin as a speed hack.
1773
1774 print [-AcelNnprsu[n] | -R [-n]] [argument ...]
1775 Print the specified argument(s) on the standard output, separated
1776 by spaces, terminated with a newline. The escapes mentioned in
1777 Backslash expansion above, as well as “\c”, which is equivalent to
1778 using the -n option, are interpreted.
1779
1780 The options are as follows:
1781
1782 -A Each argument is arithmetically evaluated; the character
1783 corresponding to the resulting value is printed. Empty
1784 arguments separate input words.
1785
1786 -c The output is printed columnised, line by line, similar to
1787 how the rs(1) utility, tab completion, the kill -l built-
1788 in utility and the select statement do.
1789
1790 -e Restore backslash expansion after a previous -r.
1791
1792 -l Change the output word separator to newline.
1793
1794 -N Change the output word and line separator to ASCII NUL.
1795
1796 -n Do not print the trailing line separator.
1797
1798 -p Print to the co-process (see Co-processes above).
1799
1800 -r Inhibit backslash expansion.
1801
1802 -s Print to the history file instead of standard output.
1803
1804 -u[n] Print to the file descriptor n (defaults to 1 if omitted)
1805 instead of standard output.
1806
1807 The -R option mostly emulates the BSD echo(1) command which does
1808 not expand backslashes and interprets its first argument as option
1809 only if it is exactly “-n” (to suppress the trailing newline).
1810
1811 pwd [-LP]
1812 Print the present working directory. If the -L option is used or
1813 if the physical option isn't set (see the set command below), the
1814 logical path is printed (i.e. the path used to cd to the current
1815 directory). If the -P option (physical path) is used or if the
1816 physical option is set, the path determined from the filesystem
1817 (by following “..” directories to the root directory) is printed.
1818
1819 read [-A | -a] [-d x] [-N z | -n z] [-p | -u[n]] [-t n] [-rs] [p ...]
1820 Reads a line of input, separates the input into fields using the
1821 IFS parameter (see Substitution above), and assigns each field to
1822 the specified parameters p. If no parameters are specified, the
1823 REPLY parameter is used to store the result. With the -A and -a
1824 options, only no or one parameter is accepted. If there are more
1825 parameters than fields, the extra parameters are set to the empty
1826 string or 0; if there are more fields than parameters, the last
1827 parameter is assigned the remaining fields (including the word
1828 separators).
1829
1830 The options are as follows:
1831
1832 -A Store the result into the parameter p (or REPLY) as array
1833 of words.
1834
1835 -a Store the result without word splitting into the parameter
1836 p (or REPLY) as array of characters (wide characters if the
1837 utf8-mode option is enacted, octets otherwise); the code‐
1838 points are encoded as decimal numbers by default.
1839
1840 -d x Use the first byte of x, NUL if empty, instead of the ASCII
1841 newline character as input line delimiter.
1842
1843 -N z Instead of reading till end-of-line, read exactly z bytes.
1844 Upon EOF, a partial read is returned with exit status 1.
1845 After timeout, a partial read is returned with an exit sta‐
1846 tus as if SIGALRM were caught.
1847
1848 -n z Instead of reading till end-of-line, read up to z bytes but
1849 return as soon as any bytes are read, e.g. from a slow ter‐
1850 minal device, or if EOF or a timeout occurs.
1851
1852 -p Read from the currently active co-process, see Co-processes
1853 above for details on this.
1854
1855 -u[n] Read from the file descriptor n (defaults to 0, i.e. stan‐
1856 dard input). The argument must immediately follow the
1857 option character.
1858
1859 -t n Interrupt reading after n seconds (specified as positive
1860 decimal value with an optional fractional part). The exit
1861 status of read is the same as if SIGALRM were caught if the
1862 timeout occurred, but partial reads may still be returned.
1863
1864 -r Normally, the ASCII backslash character escapes the special
1865 meaning of the following character and is stripped from the
1866 input; read does not stop when encountering a backslash-
1867 newline sequence and does not store that newline in the
1868 result. This option enables raw mode, in which backslashes
1869 are not processed.
1870
1871 -s The input line is saved to the history.
1872
1873 If the input is a terminal, both the -N and -n options set it into
1874 raw mode; they read an entire file if -1 is passed as z argument.
1875
1876 The first parameter may have a question mark and a string appended
1877 to it, in which case the string is used as a prompt (printed to
1878 standard error before any input is read) if the input is a tty(4)
1879 (e.g. read nfoo?'number of foos: ').
1880
1881 If no input is read or a timeout occurred, read exits with a non-
1882 zero status.
1883
1884 readonly [-p] [parameter [=value] ...]
1885 Sets the read-only attribute of the named parameters. This is a
1886 declaration utility. If values are given, parameters are set to
1887 them before setting the attribute. Once a parameter is made read-
1888 only, it cannot be unset and its value cannot be changed.
1889
1890 If no parameters are specified, the names of all parameters with
1891 the read-only attribute are printed one per line, unless the -p
1892 option is used, in which case readonly commands defining all read-
1893 only parameters, including their values, are printed.
1894
1895 realpath [--] name
1896 Prints the resolved absolute pathname corresponding to name. If
1897 name ends with a slash (‘/’), it's also checked for existence and
1898 whether it is a directory; otherwise, realpath returns 0 if the
1899 pathname either exists or can be created immediately, i.e. all but
1900 the last component exist and are directories. For calls from the
1901 shell, if any options are given, an external realpath(1) utility
1902 is preferred over the builtin.
1903
1904 rename [--] from to
1905 Renames the file from to to. Both must be complete pathnames and
1906 on the same device. An external utility is preferred over this
1907 builtin, which is intended for emergency situations (where /bin/mv
1908 becomes unusable) and directly calls rename(2).
1909
1910 return [status]
1911 Returns from a function or . script, with exit status status. If
1912 no status is given, the exit status of the last executed command
1913 is used. If used outside of a function or . script, it has the
1914 same effect as exit. Note that mksh treats both profile and ENV
1915 files as . scripts, while the original Korn shell only treats pro‐
1916 files as . scripts.
1917
1918 set [+-abCefhiklmnprsUuvXx] [+-o option] [+-A name] [--] [arg ...]
1919 The set command can be used to set (-) or clear (+) shell options,
1920 set the positional parameters, or set an array parameter. Options
1921 can be changed using the +-o option syntax, where option is the
1922 long name of an option, or using the +-letter syntax, where letter
1923 is the option's single letter name (not all options have a single
1924 letter name). The following table lists both option letters (if
1925 they exist) and long names along with a description of what the
1926 option does:
1927
1928 -A name
1929 Sets the elements of the array parameter name to arg ... If
1930 -A is used, the array is reset (i.e. emptied) first; if +A is
1931 used, the first N elements are set (where N is the number of
1932 arguments); the rest are left untouched.
1933
1934 An alternative syntax for the command set -A foo -- a b c
1935 which is compatible to GNU bash and also supported by AT&T
1936 UNIX ksh93 is: foo=(a b c); foo+=(d e)
1937
1938 -a | -o allexport
1939 All new parameters are created with the export attribute.
1940
1941 -b | -o notify
1942 Print job notification messages asynchronously, instead of
1943 just before the prompt. Only used if job control is enabled
1944 (-m).
1945
1946 -C | -o noclobber
1947 Prevent > redirection from overwriting existing files.
1948 Instead, >| must be used to force an overwrite. Note that
1949 this is not safe to use for creation of temporary files or
1950 lockfiles due to a TOCTOU in a check allowing one to redirect
1951 output to /dev/null or other device files even in noclobber
1952 mode.
1953
1954 -e | -o errexit
1955 Exit (after executing the ERR trap) as soon as an error
1956 occurs or a command fails (i.e. exits with a non-zero sta‐
1957 tus). This does not apply to commands whose exit status is
1958 explicitly tested by a shell construct such as if, until,
1959 while or ! statements. For && or ||, only the status of the
1960 last command is tested.
1961
1962 -f | -o noglob
1963 Do not expand file name patterns.
1964
1965 -h | -o trackall
1966 Create tracked aliases for all executed commands (see Aliases
1967 above). Enabled by default for non-interactive shells.
1968
1969 -i | -o interactive
1970 The shell is an interactive shell. This option can only be
1971 used when the shell is invoked. See above for a description
1972 of what this means.
1973
1974 -k | -o keyword
1975 Parameter assignments are recognised anywhere in a command.
1976
1977 -l | -o login
1978 The shell is a login shell. This option can only be used
1979 when the shell is invoked. See above for a description of
1980 what this means.
1981
1982 -m | -o monitor
1983 Enable job control (default for interactive shells).
1984
1985 -n | -o noexec
1986 Do not execute any commands. Useful for checking the syntax
1987 of scripts (ignored if interactive).
1988
1989 -p | -o privileged
1990 The shell is a privileged shell. It is set automatically if,
1991 when the shell starts, the real UID or GID does not match the
1992 effective UID (EUID) or GID (EGID), respectively. See above
1993 for a description of what this means.
1994
1995 -r | -o restricted
1996 The shell is a restricted shell. This option can only be
1997 used when the shell is invoked. See above for a description
1998 of what this means.
1999
2000 -s | -o stdin
2001 If used when the shell is invoked, commands are read from
2002 standard input. Set automatically if the shell is invoked
2003 with no arguments.
2004
2005 When -s is used with the set command it causes the specified
2006 arguments to be sorted before assigning them to the posi‐
2007 tional parameters (or to array name, if -A is used).
2008
2009 -U | -o utf8-mode
2010 Enable UTF-8 support in the Emacs editing mode and internal
2011 string handling functions. This flag is disabled by default,
2012 but can be enabled by setting it on the shell command line;
2013 is enabled automatically for interactive shells if requested
2014 at compile time, your system supports setlocale(LC_CTYPE, "")
2015 and optionally nl_langinfo(CODESET), or the LC_ALL, LC_CTYPE
2016 or LANG environment variables, and at least one of these
2017 returns something that matches “UTF-8” or “utf8” case-insen‐
2018 sitively; for direct builtin calls depending on the aforemen‐
2019 tioned environment variables; or for stdin or scripts, if the
2020 input begins with a UTF-8 Byte Order Mark.
2021
2022 In near future, locale tracking will be implemented, which
2023 means that set -+U is changed whenever one of the POSIX
2024 locale-related environment variables changes.
2025
2026 -u | -o nounset
2027 Referencing of an unset parameter, other than “$@” or “$*”,
2028 is treated as an error, unless one of the ‘-’, ‘+’ or ‘=’
2029 modifiers is used.
2030
2031 -v | -o verbose
2032 Write shell input to standard error as it is read.
2033
2034 -X | -o markdirs
2035 Mark directories with a trailing ‘/’ during file name genera‐
2036 tion.
2037
2038 -x | -o xtrace
2039 Print command trees when they are executed, preceded by the
2040 value of PS4.
2041
2042 -o bgnice
2043 Background jobs are run with lower priority.
2044
2045 -o braceexpand
2046 Enable brace expansion (a.k.a. alternation). This is enabled
2047 by default.
2048
2049 -o emacs
2050 Enable BRL emacs-like command-line editing (interactive
2051 shells only); see Emacs editing mode.
2052
2053 -o gmacs
2054 Enable gmacs-like command-line editing (interactive shells
2055 only). Currently identical to emacs editing except that
2056 transpose-chars (^T) acts slightly differently.
2057
2058 -o ignoreeof
2059 The shell will not (easily) exit when end-of-file is read;
2060 exit must be used. To avoid infinite loops, the shell will
2061 exit if EOF is read 13 times in a row.
2062
2063 -o inherit-xtrace
2064 Do not reset -o xtrace upon entering functions. This is
2065 enabled by default.
2066
2067 -o nohup
2068 Do not kill running jobs with a SIGHUP signal when a login
2069 shell exits. Currently set by default, but this may change
2070 in the future to be compatible with AT&T UNIX ksh, which
2071 doesn't have this option, but does send the SIGHUP signal.
2072
2073 -o nolog
2074 No effect. In the original Korn shell, this prevents func‐
2075 tion definitions from being stored in the history file.
2076
2077 -o physical
2078 Causes the cd and pwd commands to use “physical” (i.e. the
2079 filesystem's) “..” directories instead of “logical” directo‐
2080 ries (i.e. the shell handles “..”, which allows the user to
2081 be oblivious of symbolic links to directories). Clear by
2082 default. Note that setting this option does not affect the
2083 current value of the PWD parameter; only the cd command
2084 changes PWD. See the cd and pwd commands above for more
2085 details.
2086
2087 -o pipefail
2088 Make the exit status of a pipeline (before logically comple‐
2089 menting) the rightmost non-zero errorlevel, or zero if all
2090 commands exited with zero.
2091
2092 -o posix
2093 Behave closer to the standards (see POSIX mode for details).
2094 Automatically enabled if the basename of the shell invocation
2095 begins with “sh” and this autodetection feature is compiled
2096 in (not in MirBSD). As a side effect, setting this flag
2097 turns off the braceexpand and utf8-mode flags, which can be
2098 turned back on manually, and sh mode (unless both are enabled
2099 at the same time).
2100
2101 -o sh
2102 Enable /bin/sh (kludge) mode (see SH mode). Automatically
2103 enabled if the basename of the shell invocation begins with
2104 “sh” and this autodetection feature is compiled in (not in
2105 MirBSD). As a side effect, setting this flag turns off
2106 braceexpand mode, which can be turned back on manually, and
2107 posix mode (unless both are enabled at the same time).
2108
2109 -o vi
2110 Enable vi(1)-like command-line editing (interactive shells
2111 only). See Vi editing mode for documentation and limita‐
2112 tions.
2113
2114 -o vi-esccomplete
2115 In vi command-line editing, do command and file name comple‐
2116 tion when escape (^[) is entered in command mode.
2117
2118 -o vi-tabcomplete
2119 In vi command-line editing, do command and file name comple‐
2120 tion when tab (^I) is entered in insert mode. This is the
2121 default.
2122
2123 -o viraw
2124 No effect. In the original Korn shell, unless viraw was set,
2125 the vi command-line mode would let the tty(4) driver do the
2126 work until ESC (^[) was entered. mksh is always in viraw
2127 mode.
2128
2129 These options can also be used upon invocation of the shell. The
2130 current set of options (with single letter names) can be found in
2131 the parameter “$-”. set -o with no option name will list all the
2132 options and whether each is on or off; set +o will print the long
2133 names of all options that are currently on. In a future version,
2134 set +o will behave POSIX compliant and print commands to restore
2135 the current options instead.
2136
2137 Remaining arguments, if any, are positional parameters and are
2138 assigned, in order, to the positional parameters (i.e. $1, $2,
2139 etc.). If options end with “--” and there are no remaining argu‐
2140 ments, all positional parameters are cleared. If no options or
2141 arguments are given, the values of all names are printed. For
2142 unknown historical reasons, a lone “-” option is treated specially
2143 – it clears both the -v and -x options.
2144
2145 shift [number]
2146 The positional parameters number+1, number+2, etc. are renamed to
2147 1, 2, etc. number defaults to 1.
2148
2149 sleep seconds
2150 Suspends execution for a minimum of the seconds specified as posi‐
2151 tive decimal value with an optional fractional part. Signal
2152 delivery may continue execution earlier.
2153
2154 source file [arg ...]
2155 Like . (“dot”), except that the current working directory is
2156 appended to the search path (GNU bash extension).
2157
2158 suspend
2159 Stops the shell as if it had received the suspend character from
2160 the terminal. It is not possible to suspend a login shell unless
2161 the parent process is a member of the same terminal session but is
2162 a member of a different process group. As a general rule, if the
2163 shell was started by another shell or via su(1), it can be sus‐
2164 pended.
2165
2166 test expression
2167 [ expression ]
2168 test evaluates the expression and returns zero status if true, 1
2169 if false, or greater than 1 if there was an error. It is normally
2170 used as the condition command of if and while statements. Sym‐
2171 bolic links are followed for all file expressions except -h and
2172 -L.
2173
2174 The following basic expressions are available:
2175
2176 -a file file exists.
2177
2178 -b file file is a block special device.
2179
2180 -c file file is a character special device.
2181
2182 -d file file is a directory.
2183
2184 -e file file exists.
2185
2186 -f file file is a regular file.
2187
2188 -G file file's group is the shell's effective group ID.
2189
2190 -g file file's mode has the setgid bit set.
2191
2192 -H file file is a context dependent directory (only
2193 useful on HP-UX).
2194
2195 -h file file is a symbolic link.
2196
2197 -k file file's mode has the sticky(8) bit set.
2198
2199 -L file file is a symbolic link.
2200
2201 -O file file's owner is the shell's effective user ID.
2202
2203 -p file file is a named pipe (FIFO).
2204
2205 -r file file exists and is readable.
2206
2207 -S file file is a unix(4)-domain socket.
2208
2209 -s file file is not empty.
2210
2211 -t fd File descriptor fd is a tty(4) device.
2212
2213 -u file file's mode has the setuid bit set.
2214
2215 -w file file exists and is writable.
2216
2217 -x file file exists and is executable.
2218
2219 file1 -nt file2 file1 is newer than file2 or file1 exists and
2220 file2 does not.
2221
2222 file1 -ot file2 file1 is older than file2 or file2 exists and
2223 file1 does not.
2224
2225 file1 -ef file2 file1 is the same file as file2.
2226
2227 string string has non-zero length.
2228
2229 -n string string is not empty.
2230
2231 -z string string is empty.
2232
2233 -v name The shell parameter name is set.
2234
2235 -o option Shell option is set (see the set command above
2236 for a list of options). As a non-standard
2237 extension, if the option starts with a ‘!’, the
2238 test is negated; the test always fails if
2239 option doesn't exist (so [ -o foo -o -o !foo ]
2240 returns true if and only if option foo exists).
2241 The same can be achieved with [ -o ?foo ] like
2242 in AT&T UNIX ksh93. option can also be the
2243 short flag led by either ‘-’ or ‘+’ (no logical
2244 negation), for example “-x” or “+x” instead of
2245 “xtrace”.
2246
2247 string = string Strings are equal.
2248
2249 string == string Strings are equal.
2250
2251 string > string First string operand is greater than second
2252 string operand.
2253
2254 string < string First string operand is less than second string
2255 operand.
2256
2257 string != string Strings are not equal.
2258
2259 number -eq number Numbers compare equal.
2260
2261 number -ne number Numbers compare not equal.
2262
2263 number -ge number Numbers compare greater than or equal.
2264
2265 number -gt number Numbers compare greater than.
2266
2267 number -le number Numbers compare less than or equal.
2268
2269 number -lt number Numbers compare less than.
2270
2271 The above basic expressions, in which unary operators have prece‐
2272 dence over binary operators, may be combined with the following
2273 operators (listed in increasing order of precedence):
2274
2275 expr -o expr Logical OR.
2276 expr -a expr Logical AND.
2277 ! expr Logical NOT.
2278 ( expr ) Grouping.
2279
2280 Note that a number actually may be an arithmetic expression, such
2281 as a mathematical term or the name of an integer variable:
2282
2283 x=1; [ "x" -eq 1 ] evaluates to true
2284
2285 Note that some special rules are applied (courtesy of POSIX) if
2286 the number of arguments to test or inside the brackets [ ... ] is
2287 less than five: if leading “!” arguments can be stripped such that
2288 only one to three arguments remain, then the lowered comparison is
2289 executed; (thanks to XSI) parentheses \( ... \) lower four- and
2290 three-argument forms to two- and one-argument forms, respectively;
2291 three-argument forms ultimately prefer binary operations, followed
2292 by negation and parenthesis lowering; two- and four-argument forms
2293 prefer negation followed by parenthesis; the one-argument form
2294 always implies -n.
2295
2296 Note: A common mistake is to use “if [ $foo = bar ]” which fails
2297 if parameter “foo” is empty or unset, if it has embedded spaces
2298 (i.e. IFS octets) or if it is a unary operator like “!” or “-n”.
2299 Use tests like “if [ x"$foo" = x"bar" ]” instead, or the double-
2300 bracket operator “if [[ $foo = bar ]]” or, to avoid pattern match‐
2301 ing (see [[ above): “if [[ $foo = "$bar" ]]”
2302
2303 The [[ ... ]] construct is not only more secure to use but also
2304 often faster.
2305
2306 time [-p] [pipeline]
2307 If a pipeline is given, the times used to execute the pipeline are
2308 reported. If no pipeline is given, then the user and system time
2309 used by the shell itself, and all the commands it has run since it
2310 was started, are reported. The times reported are the real time
2311 (elapsed time from start to finish), the user CPU time (time spent
2312 running in user mode), and the system CPU time (time spent running
2313 in kernel mode). Times are reported to standard error; the format
2314 of the output is:
2315
2316 0m0.03s real 0m0.02s user 0m0.01s system
2317
2318 If the -p option is given the output is slightly longer:
2319
2320 real 0.03
2321 user 0.02
2322 sys 0.01
2323
2324 It is an error to specify the -p option unless pipeline is a sim‐
2325 ple command.
2326
2327 Simple redirections of standard error do not affect the output of
2328 the time command:
2329
2330 $ time sleep 1 2>afile
2331 $ { time sleep 1; } 2>afile
2332
2333 Times for the first command do not go to “afile”, but those of the
2334 second command do.
2335
2336 times Print the accumulated user and system times used both by the shell
2337 and by processes that the shell started which have exited. The
2338 format of the output is:
2339
2340 0m0.01s 0m0.00s
2341 0m0.04s 0m0.02s
2342
2343 trap n [signal ...]
2344 If the first operand is a decimal unsigned integer, this resets
2345 all specified signals to the default action, i.e. is the same as
2346 calling trap with a dash (“-”) as handler, followed by the argu‐
2347 ments (n [signal ...]), all of which are treated as signals.
2348
2349 trap [handler signal ...]
2350 Sets a trap handler that is to be executed when any of the speci‐
2351 fied signals are received. handler is either an empty string,
2352 indicating the signals are to be ignored, a dash (“-”), indicating
2353 that the default action is to be taken for the signals (see
2354 signal(3)), or a string containing shell commands to be executed
2355 at the first opportunity (i.e. when the current command completes
2356 or before printing the next PS1 prompt) after receipt of one of
2357 the signals. signal is the name of a signal (e.g. PIPE or ALRM)
2358 or the number of the signal (see the kill -l command above).
2359
2360 There are two special signals: EXIT (also known as 0), which is
2361 executed when the shell is about to exit, and ERR, which is exe‐
2362 cuted after an error occurs; an error is something that would
2363 cause the shell to exit if the set -e or set -o errexit option
2364 were set. EXIT handlers are executed in the environment of the
2365 last executed command.
2366
2367 Note that, for non-interactive shells, the trap handler cannot be
2368 changed for signals that were ignored when the shell started.
2369
2370 With no arguments, the current state of the traps that have been
2371 set since the shell started is shown as a series of trap commands.
2372 Note that the output of trap cannot be usefully piped to another
2373 process (an artifact of the fact that traps are cleared when sub‐
2374 processes are created).
2375
2376 The original Korn shell's DEBUG trap and the handling of ERR and
2377 EXIT traps in functions are not yet implemented.
2378
2379 true A command that exits with a zero value.
2380
2381 typeset [+-aglpnrtUux] [-L[n] | -R[n] | -Z[n]] [-i[n]] [name [=value]
2382 ...]
2383 typeset -f [-tux] [name ...]
2384 Display or set parameter attributes. This is a declaration util‐
2385 ity. With no name arguments, parameter attributes are displayed;
2386 if no options are used, the current attributes of all parameters
2387 are printed as typeset commands; if an option is given (or “-”
2388 with no option letter), all parameters and their values with the
2389 specified attributes are printed; if options are introduced with
2390 ‘+’, parameter values are not printed.
2391
2392 If name arguments are given, the attributes of the named parame‐
2393 ters are set (-) or cleared (+); inside a function, this will
2394 cause the parameters to be created (with no value) in the local
2395 scope (but see -g). Values for parameters may optionally be spec‐
2396 ified. For name[*], the change affects all elements of the array,
2397 and no value may be specified.
2398
2399 When -f is used, typeset operates on the attributes of functions.
2400 As with parameters, if no name arguments are given, functions are
2401 listed with their values (i.e. definitions) unless options are
2402 introduced with ‘+’, in which case only the function names are
2403 reported.
2404
2405 -a Indexed array attribute.
2406
2407 -f Function mode. Display or set functions and their
2408 attributes, instead of parameters.
2409
2410 -g Do not cause named parameters to be created in the local
2411 scope when called inside a function.
2412
2413 -i[n] Integer attribute. n specifies the base to use when dis‐
2414 playing the integer (if not specified, the base given in
2415 the first assignment is used). Parameters with this
2416 attribute may be assigned values containing arithmetic
2417 expressions.
2418
2419 -L[n] Left justify attribute. n specifies the field width. If
2420 n is not specified, the current width of a parameter (or
2421 the width of its first assigned value) is used. Leading
2422 whitespace (and zeros, if used with the -Z option) is
2423 stripped. If necessary, values are either truncated or
2424 space padded to fit the field width.
2425
2426 -l Lower case attribute. All upper case ASCII characters in
2427 values are converted to lower case. (In the original Korn
2428 shell, this parameter meant “long integer” when used with
2429 the -i option.)
2430
2431 -n Create a bound variable (name reference): any access to
2432 the variable name will access the variable value in the
2433 current scope (this is different from AT&T UNIX ksh93!)
2434 instead. Also different from AT&T UNIX ksh93 is that
2435 value is lazily evaluated at the time name is accessed.
2436 This can be used by functions to access variables whose
2437 names are passed as parameters, instead of using eval.
2438
2439 -p Print complete typeset commands that can be used to re-
2440 create the attributes and values of parameters.
2441
2442 -R[n] Right justify attribute. n specifies the field width. If
2443 n is not specified, the current width of a parameter (or
2444 the width of its first assigned value) is used. Trailing
2445 whitespace is stripped. If necessary, values are either
2446 stripped of leading characters or space padded to make
2447 them fit the field width.
2448
2449 -r Read-only attribute. Parameters with this attribute may
2450 not be assigned to or unset. Once this attribute is set,
2451 it cannot be turned off.
2452
2453 -t Tag attribute. Has no meaning to the shell; provided for
2454 application use.
2455
2456 For functions, -t is the trace attribute. When functions
2457 with the trace attribute are executed, the xtrace (-x)
2458 shell option is temporarily turned on.
2459
2460 -U Unsigned integer attribute. Integers are printed as
2461 unsigned values (combine with the -i option). This option
2462 is not in the original Korn shell.
2463
2464 -u Upper case attribute. All lower case ASCII characters in
2465 values are converted to upper case. (In the original Korn
2466 shell, this parameter meant “unsigned integer” when used
2467 with the -i option which meant upper case letters would
2468 never be used for bases greater than 10. See -U above.)
2469
2470 For functions, -u is the undefined attribute. See
2471 Functions above for the implications of this.
2472
2473 -x Export attribute. Parameters are placed in the environ‐
2474 ment of any executed commands. Functions cannot be
2475 exported for security reasons (“shellshock”).
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 is padded, not the
2480 base.
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 commands fg and bg.
2621
2622 Note that only commands that create processes (e.g. asynchronous com‐
2623 mands, subshell commands and non-built-in, non-function commands) can be
2624 stopped; commands like read cannot be.
2625
2626 When a job is created, it is assigned a job number. For interactive
2627 shells, this number is printed inside “[...]”, followed by the process
2628 IDs of the processes in the job when an asynchronous command is run. A
2629 job may be referred to in the bg, fg, jobs, kill and wait commands either
2630 by the process ID of the last process in the command pipeline (as stored
2631 in the $! parameter) or by prefixing the job number with a percent sign
2632 (‘%’). Other percent sequences can also be used to refer to jobs:
2633
2634 %+ | %% | % The most recently stopped job or, if there are no stopped
2635 jobs, the oldest running job.
2636
2637 %- The job that would be the %+ job if the latter did not
2638 exist.
2639
2640 %n The job with job number n.
2641
2642 %?string The job with its command containing the string string (an
2643 error occurs if multiple jobs are matched).
2644
2645 %string The job with its command starting with the string string
2646 (an error occurs if multiple jobs are matched).
2647
2648 When a job changes state (e.g. a background job finishes or foreground
2649 job is stopped), the shell prints the following status information:
2650
2651 [number] flag status command
2652
2653 where...
2654
2655 number is the job number of the job;
2656
2657 flag is the ‘+’ or ‘-’ character if the job is the %+ or %- job,
2658 respectively, or space if it is neither;
2659
2660 status indicates the current state of the job and can be:
2661
2662 Done [number]
2663 The job exited. number is the exit status of the job
2664 which is omitted if the status is zero.
2665
2666 Running The job has neither stopped nor exited (note that
2667 running does not necessarily mean consuming CPU time
2668 – the process could be blocked waiting for some
2669 event).
2670
2671 Stopped [signal]
2672 The job was stopped by the indicated signal (if no
2673 signal is given, the job was stopped by SIGTSTP).
2674
2675 signal-description [“core dumped”]
2676 The job was killed by a signal (e.g. memory fault,
2677 hangup); use kill -l for a list of signal descrip‐
2678 tions. The “core dumped” message indicates the
2679 process created a core file.
2680
2681 command is the command that created the process. If there are multiple
2682 processes in the job, each process will have a line showing its
2683 command and possibly its status, if it is different from the
2684 status of the previous process.
2685
2686 When an attempt is made to exit the shell while there are jobs in the
2687 stopped state, the shell warns the user that there are stopped jobs and
2688 does not exit. If another attempt is immediately made to exit the shell,
2689 the stopped jobs are sent a SIGHUP signal and the shell exits. Simi‐
2690 larly, if the nohup option is not set and there are running jobs when an
2691 attempt is made to exit a login shell, the shell warns the user and does
2692 not exit. If another attempt is immediately made to exit the shell, the
2693 running jobs are sent a SIGHUP signal and the shell exits.
2694
2695 Terminal state
2696 The state of the controlling terminal can be modified by a command exe‐
2697 cuted in the foreground, whether or not job control is enabled, but the
2698 modified terminal state is only kept past the job's lifetime and used for
2699 later command invocations if the command exits successfully (i.e. with an
2700 exit status of 0). When such a job is momentarily stopped or restarted,
2701 the terminal state is saved and restored, respectively, but it will not
2702 be kept afterwards. In interactive mode, when line editing is enabled,
2703 the terminal state is saved before being reconfigured by the shell for
2704 the line editor, then restored before running a command.
2705
2706 POSIX mode
2707 Entering set -o posix mode will cause mksh to behave even more POSIX com‐
2708 pliant in places where the defaults or opinions differ. Note that mksh
2709 will still operate with unsigned 32-bit arithmetic; use lksh if arith‐
2710 metic on the host long data type, complete with ISO C Undefined Behav‐
2711 iour, is required; refer to the lksh(1) manual page for details. Most
2712 other historic, AT&T UNIX ksh-compatible or opinionated differences can
2713 be disabled by using this mode; these are:
2714
2715 · The incompatible GNU bash I/O redirection &>file is not supported.
2716
2717 · File descriptors created by I/O redirections are inherited by child
2718 processes.
2719
2720 · Numbers with a leading digit zero are interpreted as octal.
2721
2722 · The echo builtin does not interpret backslashes and only supports the
2723 exact option -n.
2724
2725 · Alias expansion with a trailing space only reruns on command words.
2726
2727 · Tilde expansion follows POSIX instead of Korn shell rules.
2728
2729 · The exit status of fg is always 0.
2730
2731 · kill -l only lists signal names, all in one line.
2732
2733 · getopts does not accept options with a leading ‘+’.
2734
2735 · exec skips builtins, functions and other commands and uses a PATH
2736 search to determine the utility to execute.
2737
2738 SH mode
2739 Compatibility mode; intended for use with legacy scripts that cannot eas‐
2740 ily be fixed; the changes are as follows:
2741
2742 · The incompatible GNU bash I/O redirection &>file is not supported.
2743
2744 · File descriptors created by I/O redirections are inherited by child
2745 processes.
2746
2747 · The echo builtin does not interpret backslashes and only supports the
2748 exact option -n, unless built with -DMKSH_MIDNIGHTBSD01ASH_COMPAT.
2749
2750 · The substitution operations ${x#pat}, ${x##pat}, ${x%pat}, and
2751 ${x%%pat} wrongly do not require a parenthesis to be escaped and do
2752 not parse extglobs.
2753
2754 · The getopt construct from lksh(1) passes through the errorlevel.
2755
2756 · sh -c eats a leading -- if built with -DMKSH_MIDNIGHTBSD01ASH_COMPAT.
2757
2758 Interactive input line editing
2759 The shell supports three modes of reading command lines from a tty(4) in
2760 an interactive session, controlled by the emacs, gmacs and vi options (at
2761 most one of these can be set at once). The default is emacs. Editing
2762 modes can be set explicitly using the set built-in. If none of these
2763 options are enabled, the shell simply reads lines using the normal tty(4)
2764 driver. If the emacs or gmacs option is set, the shell allows emacs-like
2765 editing of the command; similarly, if the vi option is set, the shell
2766 allows vi-like editing of the command. These modes are described in
2767 detail in the following sections.
2768
2769 In these editing modes, if a line is longer than the screen width (see
2770 the COLUMNS parameter), a ‘>’, ‘+’ or ‘<’ character is displayed in the
2771 last column indicating that there are more characters after, before and
2772 after, or before the current position, respectively. The line is
2773 scrolled horizontally as necessary.
2774
2775 Completed lines are pushed into the history, unless they begin with an
2776 IFS octet or IFS white space or are the same as the previous line.
2777
2778 Emacs editing mode
2779 When the emacs option is set, interactive input line editing is enabled.
2780 Warning: This mode is slightly different from the emacs mode in the orig‐
2781 inal Korn shell. In this mode, various editing commands (typically bound
2782 to one or more control characters) cause immediate actions without wait‐
2783 ing for a newline. Several editing commands are bound to particular con‐
2784 trol characters when the shell is invoked; these bindings can be changed
2785 using the bind command.
2786
2787 The following is a list of available editing commands. Each description
2788 starts with the name of the command, suffixed with a colon; an [n] (if
2789 the command can be prefixed with a count); and any keys the command is
2790 bound to by default, written using caret notation e.g. the ASCII ESC
2791 character is written as ^[. These control sequences are not case sensi‐
2792 tive. A count prefix for a command is entered using the sequence ^[n,
2793 where n is a sequence of 1 or more digits. Unless otherwise specified,
2794 if a count is omitted, it defaults to 1.
2795
2796 Note that editing command names are used only with the bind command.
2797 Furthermore, many editing commands are useful only on terminals with a
2798 visible cursor. The user's tty(4) characters (e.g. ERASE) are bound to
2799 reasonable substitutes and override the default bindings; their customary
2800 values are shown in parentheses below. The default bindings were chosen
2801 to resemble corresponding Emacs key bindings:
2802
2803 abort: INTR (^C), ^G
2804 Abort the current command, save it to the history, empty the line
2805 buffer and set the exit state to interrupted.
2806
2807 auto-insert: [n]
2808 Simply causes the character to appear as literal input. Most
2809 ordinary characters are bound to this.
2810
2811 backward-char: [n] ^B, ^XD, ANSI-CurLeft, PC-CurLeft
2812 Moves the cursor backward n characters.
2813
2814 backward-word: [n] ^[b, ANSI-Ctrl-CurLeft, ANSI-Alt-CurLeft
2815 Moves the cursor backward to the beginning of the word; words
2816 consist of alphanumerics, underscore (‘_’) and dollar sign (‘$’)
2817 characters.
2818
2819 beginning-of-history: ^[<
2820 Moves to the beginning of the history.
2821
2822 beginning-of-line: ^A, ANSI-Home, PC-Home
2823 Moves the cursor to the beginning of the edited input line.
2824
2825 capitalise-word: [n] ^[C, ^[c
2826 Uppercase the first ASCII character in the next n words, leaving
2827 the cursor past the end of the last word.
2828
2829 clear-screen: ^[^L
2830 Prints a compile-time configurable sequence to clear the screen
2831 and home the cursor, redraws the last line of the prompt string
2832 and the currently edited input line. The default sequence works
2833 for almost all standard terminals.
2834
2835 comment: ^[#
2836 If the current line does not begin with a comment character, one
2837 is added at the beginning of the line and the line is entered (as
2838 if return had been pressed); otherwise, the existing comment
2839 characters are removed and the cursor is placed at the beginning
2840 of the line.
2841
2842 complete: ^[^[
2843 Automatically completes as much as is unique of the command name
2844 or the file name containing the cursor. If the entire remaining
2845 command or file name is unique, a space is printed after its com‐
2846 pletion, unless it is a directory name in which case ‘/’ is
2847 appended. If there is no command or file name with the current
2848 partial word as its prefix, a bell character is output (usually
2849 causing a beep to be sounded).
2850
2851 complete-command: ^X^[
2852 Automatically completes as much as is unique of the command name
2853 having the partial word up to the cursor as its prefix, as in the
2854 complete command above.
2855
2856 complete-file: ^[^X
2857 Automatically completes as much as is unique of the file name
2858 having the partial word up to the cursor as its prefix, as in the
2859 complete command described above.
2860
2861 complete-list: ^I, ^[=
2862 Complete as much as is possible of the current word and list the
2863 possible completions for it. If only one completion is possible,
2864 match as in the complete command above. Note that ^I is usually
2865 generated by the TAB (tabulator) key.
2866
2867 delete-char-backward: [n] ERASE (^H), ^?, ^H
2868 Deletes n characters before the cursor.
2869
2870 delete-char-forward: [n] ANSI-Del, PC-Del
2871 Deletes n characters after the cursor.
2872
2873 delete-word-backward: [n] Pfx1+ERASE (^[^H), WERASE (^W), ^[^?, ^[^H, ^[h
2874 Deletes n words before the cursor.
2875
2876 delete-word-forward: [n] ^[d
2877 Deletes characters after the cursor up to the end of n words.
2878
2879 down-history: [n] ^N, ^XB, ANSI-CurDown, PC-CurDown
2880 Scrolls the history buffer forward n lines (later). Each input
2881 line originally starts just after the last entry in the history
2882 buffer, so down-history is not useful until either
2883 search-history, search-history-up or up-history has been per‐
2884 formed.
2885
2886 downcase-word: [n] ^[L, ^[l
2887 Lowercases the next n words.
2888
2889 edit-line: [n] ^Xe
2890 Edit line n or the current line, if not specified, interactively.
2891 The actual command executed is fc -e ${VISUAL:-${EDITOR:-vi}} n.
2892
2893 end-of-history: ^[>
2894 Moves to the end of the history.
2895
2896 end-of-line: ^E, ANSI-End, PC-End
2897 Moves the cursor to the end of the input line.
2898
2899 eot: ^_
2900 Acts as an end-of-file; this is useful because edit-mode input
2901 disables normal terminal input canonicalisation.
2902
2903 eot-or-delete: [n] EOF (^D)
2904 If alone on a line, same as eot, otherwise, delete-char-forward.
2905
2906 error: (not bound)
2907 Error (ring the bell).
2908
2909 evaluate-region: ^[^E
2910 Evaluates the text between the mark and the cursor position (the
2911 entire line if no mark is set) as function substitution (if it
2912 cannot be parsed, the editing state is unchanged and the bell is
2913 rung to signal an error); $? is updated accordingly.
2914
2915 exchange-point-and-mark: ^X^X
2916 Places the cursor where the mark is and sets the mark to where
2917 the cursor was.
2918
2919 expand-file: ^[*
2920 Appends a ‘*’ to the current word and replaces the word with the
2921 result of performing file globbing on the word. If no files
2922 match the pattern, the bell is rung.
2923
2924 forward-char: [n] ^F, ^XC, ANSI-CurRight, PC-CurRight
2925 Moves the cursor forward n characters.
2926
2927 forward-word: [n] ^[f, ANSI-Ctrl-CurRight, ANSI-Alt-CurRight
2928 Moves the cursor forward to the end of the nth word.
2929
2930 goto-history: [n] ^[g
2931 Goes to history number n.
2932
2933 kill-line: KILL (^U)
2934 Deletes the entire input line.
2935
2936 kill-region: ^W
2937 Deletes the input between the cursor and the mark.
2938
2939 kill-to-eol: [n] ^K
2940 Deletes the input from the cursor to the end of the line if n is
2941 not specified; otherwise deletes characters between the cursor
2942 and column n.
2943
2944 list: ^[?
2945 Prints a sorted, columnated list of command names or file names
2946 (if any) that can complete the partial word containing the cur‐
2947 sor. Directory names have ‘/’ appended to them.
2948
2949 list-command: ^X?
2950 Prints a sorted, columnated list of command names (if any) that
2951 can complete the partial word containing the cursor.
2952
2953 list-file: ^X^Y
2954 Prints a sorted, columnated list of file names (if any) that can
2955 complete the partial word containing the cursor. File type indi‐
2956 cators are appended as described under list above.
2957
2958 newline: ^J, ^M
2959 Causes the current input line to be processed by the shell. The
2960 current cursor position may be anywhere on the line.
2961
2962 newline-and-next: ^O
2963 Causes the current input line to be processed by the shell, and
2964 the next line from history becomes the current line. This is
2965 only useful after an up-history, search-history or
2966 search-history-up.
2967
2968 no-op: QUIT (^\)
2969 This does nothing.
2970
2971 prefix-1: ^[
2972 Introduces a 2-character command sequence.
2973
2974 prefix-2: ^X, ^[[, ^[O
2975 Introduces a multi-character command sequence.
2976
2977 prev-hist-word: [n] ^[., ^[_
2978 The last word or, if given, the nth word (zero-based) of the pre‐
2979 vious (on repeated execution, second-last, third-last, etc.) com‐
2980 mand is inserted at the cursor. Use of this editing command
2981 trashes the mark.
2982
2983 quote: ^^, ^V
2984 The following character is taken literally rather than as an
2985 editing command.
2986
2987 redraw: ^L
2988 Reprints the last line of the prompt string and the current input
2989 line on a new line.
2990
2991 search-character-backward: [n] ^[^]
2992 Search backward in the current line for the nth occurrence of the
2993 next character typed.
2994
2995 search-character-forward: [n] ^]
2996 Search forward in the current line for the nth occurrence of the
2997 next character typed.
2998
2999 search-history: ^R
3000 Enter incremental search mode. The internal history list is
3001 searched backwards for commands matching the input. An initial
3002 ‘^’ in the search string anchors the search. The escape key will
3003 leave search mode. Other commands, including sequences of escape
3004 as prefix-1 followed by a prefix-1 or prefix-2 key will be exe‐
3005 cuted after leaving search mode. The abort (^G) command will
3006 restore the input line before search started. Successive
3007 search-history commands continue searching backward to the next
3008 previous occurrence of the pattern. The history buffer retains
3009 only a finite number of lines; the oldest are discarded as neces‐
3010 sary.
3011
3012 search-history-up: ANSI-PgUp, PC-PgUp
3013 Search backwards through the history buffer for commands whose
3014 beginning match the portion of the input line before the cursor.
3015 When used on an empty line, this has the same effect as
3016 up-history.
3017
3018 search-history-down: ANSI-PgDn, PC-PgDn
3019 Search forwards through the history buffer for commands whose
3020 beginning match the portion of the input line before the cursor.
3021 When used on an empty line, this has the same effect as
3022 down-history. This is only useful after an up-history,
3023 search-history or search-history-up.
3024
3025 set-mark-command: ^[<space>
3026 Set the mark at the cursor position.
3027
3028 transpose-chars: ^T
3029 If at the end of line or, if the gmacs option is set, this
3030 exchanges the two previous characters; otherwise, it exchanges
3031 the previous and current characters and moves the cursor one
3032 character to the right.
3033
3034 up-history: [n] ^P, ^XA, ANSI-CurUp, PC-CurUp
3035 Scrolls the history buffer backward n lines (earlier).
3036
3037 upcase-word: [n] ^[U, ^[u
3038 Uppercase the next n words.
3039
3040 version: ^[^V
3041 Display the version of mksh. The current edit buffer is restored
3042 as soon as a key is pressed. The restoring keypress is pro‐
3043 cessed, unless it is a space.
3044
3045 yank: ^Y
3046 Inserts the most recently killed text string at the current cur‐
3047 sor position.
3048
3049 yank-pop: ^[y
3050 Immediately after a yank, replaces the inserted text string with
3051 the next previously killed text string.
3052
3053 The tab completion escapes characters the same way as the following code:
3054
3055 print -nr -- "${x@/[\"-\$\&-*:-?[\\\`{-\}${IFS-$' \t\n'}]/\\$KSH_MATCH}"
3056
3057 Vi editing mode
3058 Note: The vi command-line editing mode is orphaned, yet still functional.
3059 It is 8-bit clean but specifically does not support UTF-8 or MBCS.
3060
3061 The vi command-line editor in mksh has basically the same commands as the
3062 vi(1) editor with the following exceptions:
3063
3064 · You start out in insert mode.
3065
3066 · There are file name and command completion commands: =, \, *, ^X, ^E,
3067 ^F and, optionally, <tab> and <esc>.
3068
3069 · The _ command is different (in mksh, it is the last argument command;
3070 in vi(1) it goes to the start of the current line).
3071
3072 · The / and G commands move in the opposite direction to the j command.
3073
3074 · Commands which don't make sense in a single line editor are not
3075 available (e.g. screen movement commands and ex(1)-style colon (:)
3076 commands).
3077
3078 Like vi(1), there are two modes: “insert” mode and “command” mode. In
3079 insert mode, most characters are simply put in the buffer at the current
3080 cursor position as they are typed; however, some characters are treated
3081 specially. In particular, the following characters are taken from cur‐
3082 rent tty(4) settings (see stty(1)) and have their usual meaning (normal
3083 values are in parentheses): kill (^U), erase (^?), werase (^W), eof (^D),
3084 intr (^C) and quit (^\). In addition to the above, the following charac‐
3085 ters are also treated specially in insert mode:
3086
3087 ^E Command and file name enumeration (see below).
3088
3089 ^F Command and file name completion (see below). If used twice in
3090 a row, the list of possible completions is displayed; if used a
3091 third time, the completion is undone.
3092
3093 ^H Erases previous character.
3094
3095 ^J | ^M End of line. The current line is read, parsed and executed by
3096 the shell.
3097
3098 ^V Literal next. The next character typed is not treated specially
3099 (can be used to insert the characters being described here).
3100
3101 ^X Command and file name expansion (see below).
3102
3103 <esc> Puts the editor in command mode (see below).
3104
3105 <tab> Optional file name and command completion (see ^F above),
3106 enabled with set -o vi-tabcomplete.
3107
3108 In command mode, each character is interpreted as a command. Characters
3109 that don't correspond to commands, are illegal combinations of commands,
3110 or are commands that can't be carried out, all cause beeps. In the fol‐
3111 lowing command descriptions, an [n] indicates the command may be prefixed
3112 by a number (e.g. 10l moves right 10 characters); if no number prefix is
3113 used, n is assumed to be 1 unless otherwise specified. The term “current
3114 position” refers to the position between the cursor and the character
3115 preceding the cursor. A “word” is a sequence of letters, digits and
3116 underscore characters or a sequence of non-letter, non-digit, non-under‐
3117 score and non-whitespace characters (e.g. “ab2*&^” contains two words)
3118 and a “big-word” is a sequence of non-whitespace characters.
3119
3120 Special mksh vi commands:
3121
3122 The following commands are not in, or are different from, the normal vi
3123 file editor:
3124
3125 [n]_ Insert a space followed by the nth big-word from the last
3126 command in the history at the current position and enter
3127 insert mode; if n is not specified, the last word is
3128 inserted.
3129
3130 # Insert the comment character (‘#’) at the start of the cur‐
3131 rent line and return the line to the shell (equivalent to
3132 I#^J).
3133
3134 [n]g Like G, except if n is not specified, it goes to the most
3135 recent remembered line.
3136
3137 [n]v Edit line n using the vi(1) editor; if n is not specified,
3138 the current line is edited. The actual command executed is
3139 fc -e ${VISUAL:-${EDITOR:-vi}} n.
3140
3141 * and ^X Command or file name expansion is applied to the current big-
3142 word (with an appended ‘*’ if the word contains no file glob‐
3143 bing characters) – the big-word is replaced with the result‐
3144 ing words. If the current big-word is the first on the line
3145 or follows one of the characters ‘;’, ‘|’, ‘&’, ‘(’ or ‘)’
3146 and does not contain a slash (‘/’), then command expansion is
3147 done; otherwise file name expansion is done. Command expan‐
3148 sion will match the big-word against all aliases, functions
3149 and built-in commands as well as any executable files found
3150 by searching the directories in the PATH parameter. File
3151 name expansion matches the big-word against the files in the
3152 current directory. After expansion, the cursor is placed
3153 just past the last word and the editor is in insert mode.
3154
3155 [n]\, [n]^F, [n]<tab>, and [n]<esc>
3156 Command/file name completion. Replace the current big-word
3157 with the longest unique match obtained after performing com‐
3158 mand and file name expansion. <tab> is only recognised if
3159 the vi-tabcomplete option is set, while <esc> is only recog‐
3160 nised if the vi-esccomplete option is set (see set -o). If n
3161 is specified, the nth possible completion is selected (as
3162 reported by the command/file name enumeration command).
3163
3164 = and ^E Command/file name enumeration. List all the commands or
3165 files that match the current big-word.
3166
3167 ^V Display the version of mksh. The current edit buffer is
3168 restored as soon as a key is pressed. The restoring keypress
3169 is ignored.
3170
3171 @c Macro expansion. Execute the commands found in the alias c.
3172
3173 Intra-line movement commands:
3174
3175 [n]h and [n]^H
3176 Move left n characters.
3177
3178 [n]l and [n]<space>
3179 Move right n characters.
3180
3181 0 Move to column 0.
3182
3183 ^ Move to the first non-whitespace character.
3184
3185 [n]| Move to column n.
3186
3187 $ Move to the last character.
3188
3189 [n]b Move back n words.
3190
3191 [n]B Move back n big-words.
3192
3193 [n]e Move forward to the end of the word, n times.
3194
3195 [n]E Move forward to the end of the big-word, n times.
3196
3197 [n]w Move forward n words.
3198
3199 [n]W Move forward n big-words.
3200
3201 % Find match. The editor looks forward for the nearest parenthe‐
3202 sis, bracket or brace and then moves the cursor to the matching
3203 parenthesis, bracket or brace.
3204
3205 [n]fc Move forward to the nth occurrence of the character c.
3206
3207 [n]Fc Move backward to the nth occurrence of the character c.
3208
3209 [n]tc Move forward to just before the nth occurrence of the character
3210 c.
3211
3212 [n]Tc Move backward to just before the nth occurrence of the character
3213 c.
3214
3215 [n]; Repeats the last f, F, t or T command.
3216
3217 [n], Repeats the last f, F, t or T command, but moves in the opposite
3218 direction.
3219
3220 Inter-line movement commands:
3221
3222 [n]j, [n]+, and [n]^N
3223 Move to the nth next line in the history.
3224
3225 [n]k, [n]-, and [n]^P
3226 Move to the nth previous line in the history.
3227
3228 [n]G Move to line n in the history; if n is not specified, the number
3229 of the first remembered line is used.
3230
3231 [n]g Like G, except if n is not specified, it goes to the most recent
3232 remembered line.
3233
3234 [n]/string
3235 Search backward through the history for the nth line containing
3236 string; if string starts with ‘^’, the remainder of the string
3237 must appear at the start of the history line for it to match.
3238
3239 [n]?string
3240 Same as /, except it searches forward through the history.
3241
3242 [n]n Search for the nth occurrence of the last search string; the
3243 direction of the search is the same as the last search.
3244
3245 [n]N Search for the nth occurrence of the last search string; the
3246 direction of the search is the opposite of the last search.
3247
3248 ANSI-CurUp, PC-PgUp
3249 Take the characters from the beginning of the line to the current
3250 cursor position as search string and do a backwards history
3251 search for lines beginning with this string; keep the cursor
3252 position. This works only in insert mode and keeps it enabled.
3253
3254 Edit commands
3255
3256 [n]a Append text n times; goes into insert mode just after the current
3257 position. The append is only replicated if command mode is re-
3258 entered i.e. <esc> is used.
3259
3260 [n]A Same as a, except it appends at the end of the line.
3261
3262 [n]i Insert text n times; goes into insert mode at the current posi‐
3263 tion. The insertion is only replicated if command mode is re-
3264 entered i.e. <esc> is used.
3265
3266 [n]I Same as i, except the insertion is done just before the first
3267 non-blank character.
3268
3269 [n]s Substitute the next n characters (i.e. delete the characters and
3270 go into insert mode).
3271
3272 S Substitute whole line. All characters from the first non-blank
3273 character to the end of the line are deleted and insert mode is
3274 entered.
3275
3276 [n]cmove-cmd
3277 Change from the current position to the position resulting from n
3278 move-cmds (i.e. delete the indicated region and go into insert
3279 mode); if move-cmd is c, the line starting from the first non-
3280 blank character is changed.
3281
3282 C Change from the current position to the end of the line (i.e.
3283 delete to the end of the line and go into insert mode).
3284
3285 [n]x Delete the next n characters.
3286
3287 [n]X Delete the previous n characters.
3288
3289 D Delete to the end of the line.
3290
3291 [n]dmove-cmd
3292 Delete from the current position to the position resulting from n
3293 move-cmds; move-cmd is a movement command (see above) or d, in
3294 which case the current line is deleted.
3295
3296 [n]rc Replace the next n characters with the character c.
3297
3298 [n]R Replace. Enter insert mode but overwrite existing characters
3299 instead of inserting before existing characters. The replacement
3300 is repeated n times.
3301
3302 [n]~ Change the case of the next n characters.
3303
3304 [n]ymove-cmd
3305 Yank from the current position to the position resulting from n
3306 move-cmds into the yank buffer; if move-cmd is y, the whole line
3307 is yanked.
3308
3309 Y Yank from the current position to the end of the line.
3310
3311 [n]p Paste the contents of the yank buffer just after the current
3312 position, n times.
3313
3314 [n]P Same as p, except the buffer is pasted at the current position.
3315
3316 Miscellaneous vi commands
3317
3318 ^J and ^M
3319 The current line is read, parsed and executed by the shell.
3320
3321 ^L and ^R
3322 Redraw the current line.
3323
3324 [n]. Redo the last edit command n times.
3325
3326 u Undo the last edit command.
3327
3328 U Undo all changes that have been made to the current line.
3329
3330 PC Home, End, Del and cursor keys
3331 They move as expected, both in insert and command mode.
3332
3333 intr and quit
3334 The interrupt and quit terminal characters cause the current line
3335 to be removed to the history and a new prompt to be printed.
3336
3338 ~/.mkshrc User mkshrc profile (non-privileged interactive
3339 shells); see Startup files. The location can be
3340 changed at compile time (for embedded systems); AOSP
3341 Android builds use /system/etc/mkshrc.
3342 ~/.profile User profile (non-privileged login shells); see
3343 Startup files near the top of this manual.
3344 /etc/profile System profile (login shells); see Startup files.
3345 /etc/shells Shell database.
3346 /etc/suid_profile Suid profile (privileged shells); see Startup files.
3347
3348 Note: On Android, /system/etc/ contains the system and suid profile.
3349
3351 awk(1), cat(1), ed(1), getopt(1), lksh(1), sed(1), sh(1), stty(1),
3352 dup(2), execve(2), getgid(2), getuid(2), mknod(2), mkfifo(2), open(2),
3353 pipe(2), rename(2), wait(2), getopt(3), nl_langinfo(3), setlocale(3),
3354 signal(3), system(3), tty(4), shells(5), environ(7), script(7), utf-8(7),
3355 mknod(8)
3356
3357 http://www.mirbsd.org/ksh-chan.htm
3358
3359 Morris Bolsky, The KornShell Command and Programming Language, Prentice
3360 Hall PTR, xvi + 356 pages, 1989, ISBN 978-0-13-516972-8 (0-13-516972-0).
3361
3362 Morris I. Bolsky and David G. Korn, The New KornShell Command and
3363 Programming Language (2nd Edition), Prentice Hall PTR, xvi + 400 pages,
3364 1995, ISBN 978-0-13-182700-4 (0-13-182700-6).
3365
3366 Stephen G. Kochan and Patrick H. Wood, UNIX Shell Programming, Sams, 3rd
3367 Edition, xiii + 437 pages, 2003, ISBN 978-0-672-32490-1 (0-672-32490-3).
3368
3369 IEEE Inc., IEEE Standard for Information Technology – Portable Operating
3370 System Interface (POSIX), IEEE Press, Part 2: Shell and Utilities,
3371 xvii + 1195 pages, 1993, ISBN 978-1-55937-255-8 (1-55937-255-9).
3372
3373 Bill Rosenblatt, Learning the Korn Shell, O'Reilly, 360 pages, 1993, ISBN
3374 978-1-56592-054-5 (1-56592-054-6).
3375
3376 Bill Rosenblatt and Arnold Robbins, Learning the Korn Shell, Second
3377 Edition, O'Reilly, 432 pages, 2002, ISBN 978-0-596-00195-7
3378 (0-596-00195-9).
3379
3380 Barry Rosenberg, KornShell Programming Tutorial, Addison-Wesley
3381 Professional, xxi + 324 pages, 1991, ISBN 978-0-201-56324-5
3382 (0-201-56324-X).
3383
3385 The MirBSD Korn Shell is developed by mirabilos <m@mirbsd.org> as part of
3386 The MirOS Project. This shell is based on the public domain 7th edition
3387 Bourne shell clone by Charles Forsyth, who kindly agreed to, in countries
3388 where the Public Domain status of the work may not be valid, grant a
3389 copyright licence to the general public to deal in the work without
3390 restriction and permission to sublicence derivatives under the terms of
3391 any (OSI approved) Open Source licence, and parts of the BRL shell by
3392 Doug A. Gwyn, Doug Kingston, Ron Natalie, Arnold Robbins, Lou Salkind and
3393 others. The first release of pdksh was created by Eric Gisin, and it was
3394 subsequently maintained by John R. MacMillan, Simon J. Gerraty and
3395 Michael Rendell. The effort of several projects, such as Debian and
3396 OpenBSD, and other contributors including our users, to improve the shell
3397 is appreciated. See the documentation, website and source code (CVS) for
3398 details.
3399
3400 mksh-os2 is developed by KO Myung-Hun <komh@chollian.net>.
3401
3402 mksh-w32 is developed by Michael Langguth <lan@scalaris.com>.
3403
3404 mksh/z/OS is contributed by Daniel Richard G. <skunk@iSKUNK.ORG>.
3405
3406 The BSD daemon is Copyright © Marshall Kirk McKusick. The complete
3407 legalese is at: http://www.mirbsd.org/TaC-mksh.txt
3408
3410 mksh provides a consistent 32-bit integer arithmetic implementation, both
3411 signed and unsigned, with sign of the result of a remainder operation and
3412 wraparound defined, even (defying POSIX) on 36-bit and 64-bit systems.
3413
3414 mksh provides a consistent, clear interface normally. This may deviate
3415 from POSIX in historic or opinionated places. set -o posix (see POSIX
3416 mode for details) will cause the shell to behave more conformant.
3417
3418 For the purpose of POSIX, mksh supports only the “C” locale. mksh's
3419 utf8-mode must be disabled in POSIX mode, and it only supports the BMP
3420 (Basic Multilingual Plane) of UCS and maps raw octets into the
3421 U+EF80..U+EFFF wide character range; compare Arithmetic expressions. The
3422 following POSIX sh-compatible code toggles the utf8-mode option dependent
3423 on the current POSIX locale for mksh to allow using the UTF-8 mode,
3424 within the constraints outlined above, in code portable across various
3425 shell implementations:
3426
3427 case ${KSH_VERSION:-} in
3428 *MIRBSD KSH*|*LEGACY KSH*)
3429 case ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} in
3430 *[Uu][Tt][Ff]8*|*[Uu][Tt][Ff]-8*) set -U ;;
3431 *) set +U ;;
3432 esac ;;
3433 esac
3434 In near future, (UTF-8) locale tracking will be implemented though.
3435
3436 Using set -o pipefail makes the following construct error out:
3437
3438 set -e
3439 for x in 1 2; do
3440 false && echo $x
3441 done | cat
3442 This is because, while the “&&” ensures that the inner command's failure
3443 is not taken, it sets the entire for..done loop's errorlevel, which is
3444 passed on by -o pipefail. Invert the inner command: true || echo $x
3445
3446 See also the FAQ below.
3447
3449 Suspending (using ^Z) pipelines like the one below will only suspend the
3450 currently running part of the pipeline; in this example, “fubar” is imme‐
3451 diately printed on suspension (but not later after an fg).
3452
3453 $ /bin/sleep 666 && echo fubar
3454
3455 The truncation process involved when changing HISTFILE does not free old
3456 history entries (leaks memory) and leaks old entries into the new history
3457 if their line numbers are not overwritten by same-number entries from the
3458 persistent history file; truncating the on-disc file to HISTSIZE lines
3459 has always been broken and prone to history file corruption when multiple
3460 shells are accessing the file; the rollover process for the in-memory
3461 portion of the history is slow, should use memmove(3).
3462
3463 This document attempts to describe mksh R57 and up, compiled without any
3464 options impacting functionality, such as MKSH_SMALL, when not called as
3465 /bin/sh which, on some systems only, enables set -o posix or set -o sh
3466 automatically (whose behaviour differs across targets), for an operating
3467 environment supporting all of its advanced needs.
3468
3469 Please report bugs in mksh to the public development mailing list at
3470 <miros-mksh@mirbsd.org> (please note the EU-DSGVO/GDPR notice on
3471 http://www.mirbsd.org/rss.htm#lists and in the SMTP banner!) or in the
3472 #!/bin/mksh (or #ksh) IRC channel at irc.freenode.net (Port 6697 SSL,
3473 6667 unencrypted), or at: https://launchpad.net/mksh
3474
3476 This FAQ attempts to document some of the questions users of mksh or
3477 readers of this manual page may encounter.
3478
3479 I'm an Android user, so what's mksh?
3480 mksh is a UNIX shell / command interpreter, similar to COMMAND.COM or
3481 CMD.EXE, which has been included with Android Open Source Project for a
3482 while now. Basically, it's a program that runs in a terminal (console
3483 window), takes user input and runs commands or scripts, which it can also
3484 be asked to do by other programs, even in the background. Any privilege
3485 pop-ups you might be encountering are thus not mksh issues but questions
3486 by some other program utilising it.
3487
3488 I'm an OS/2 user, what do I need to know?
3489 Unlike the native command prompt, the current working directory is, for
3490 security reasons common on Unix systems which the shell is designed for,
3491 not in the search path at all; if you really need this, run the command
3492 PATH=.$PATHSEP$PATH or add that to a suitable initialisation file.
3493
3494 There are two different newline modes for mksh-os2: standard (Unix) mode,
3495 in which only LF (0A hex) is supported as line separator, and "textmode",
3496 which also accepts ASCII newlines (CR+LF), like most other tools on OS/2,
3497 but creating an incompatibility with standard mksh. If you compiled mksh
3498 from source, you will get the standard Unix mode unless -T is added dur‐
3499 ing compilation; you will most likely have gotten this shell through
3500 komh's port on Hobbes, or from his OS/2 Factory on eComStation Korea,
3501 which uses "textmode", though. Most OS/2 users will want to use
3502 "textmode" unless they need absolute compatibility with Unix mksh.
3503
3504 How do I start mksh on a specific terminal?
3505 Normally:
3506 mksh -T/dev/tty2
3507
3508 However, if you want for it to return (e.g. for an embedded system rescue
3509 shell), use this on your real console device instead:
3510 mksh -T!/dev/ttyACM0
3511
3512 mksh can also daemonise (send to the background):
3513 mksh -T- -c 'exec cdio lock'
3514
3515 POSIX says...
3516 Run the shell in POSIX mode (and possibly lksh instead of mksh):
3517 set -o posix
3518
3519 I forbid stat(2) in my SELinux policy, and some things do not work!
3520 Don't break Unix. Read up on the GIGO principle. Duh.
3521
3522 My prompt from <some other shell> does not work!
3523 Contact us on the mailing list or on IRC, we'll convert it for you.
3524
3525 Something is going wrong with my while...read loop
3526 Most likely, you've encountered the problem in which the shell runs all
3527 parts of a pipeline as subshell. The inner loop will be executed in a
3528 subshell and variable changes cannot be propagated if run in a pipeline:
3529
3530 bar | baz | while read foo; do ...; done
3531
3532 Note that exit in the inner loop will only exit the subshell and not the
3533 original shell. Likewise, if the code is inside a function, return in
3534 the inner loop will only exit the subshell and won't terminate the func‐
3535 tion.
3536
3537 Use co-processes instead:
3538
3539 bar | baz |&
3540 while read -p foo; do ...; done
3541 exec 3>&p; exec 3>&-
3542
3543 If read is run in a loop such as while read foo; do ...; done then lead‐
3544 ing whitespace will be removed (IFS) and backslashes processed. You
3545 might want to use while IFS= read -r foo; do ...; done for pristine I/O.
3546 Similarly, when using the -a option, use of the -r option might be pru‐
3547 dent (“read -raN-1 arr <file”); the same applies for NUL-terminated
3548 lines:
3549
3550 find . -type f -print0 |& \
3551 while IFS= read -d '' -pr filename; do
3552 print -r -- "found <${filename#./}>"
3553 done
3554
3555 What differences in function-local scopes are there?
3556 mksh has a different scope model from AT&T UNIX ksh, which leads to sub‐
3557 tle differences in semantics for identical builtins. This can cause
3558 issues with a nameref to suddenly point to a local variable by accident.
3559
3560 GNU bash allows unsetting local variables; in mksh, doing so in a func‐
3561 tion allows back access to the global variable (actually the one in the
3562 next scope up) with the same name. The following code, when run before
3563 the function definitions, changes the behaviour of unset to behave like
3564 other shells (the alias can be removed after the definitions):
3565
3566 case ${KSH_VERSION:-} in
3567 *MIRBSD KSH*|*LEGACY KSH*)
3568 function unset_compat {
3569 \\builtin typeset unset_compat_x
3570
3571 for unset_compat_x in "$@"; do
3572 eval "\\\\builtin unset $unset_compat_x[*]"
3573 done
3574 }
3575 \\builtin alias unset=unset_compat
3576 ;;
3577 esac
3578
3579 When a local variable is created (e.g. using local, typeset, integer,
3580 \\builtin typeset) it does not, like in other shells, inherit the value
3581 from the global (next scope up) variable with the same name; it is rather
3582 created without any value (unset but defined).
3583
3584 I get an error in this regex comparison
3585 Use extglobs instead of regexes:
3586 [[ foo =~ (foo|bar).*baz ]] # becomes
3587 [[ foo = *@(foo|bar)*baz* ]] # instead
3588
3589 Are there any extensions to avoid?
3590 GNU bash supports “&>” (and “|&”) to redirect both stdout and stderr in
3591 one go, but this breaks POSIX and Korn Shell syntax; use POSIX redirec‐
3592 tions instead:
3593 foo |& bar |& baz &>log # GNU bash
3594 foo 2>&1 | bar 2>&1 | baz >log 2>&1 # POSIX
3595
3596 ^L (Ctrl-L) does not clear the screen
3597 Use ^[^L (Escape+Ctrl-L) or rebind it:
3598 bind '^L=clear-screen'
3599
3600 ^U (Ctrl-U) clears the entire line
3601 If it should only delete the line up to the cursor, use:
3602 bind -m ^U='^[0^K'
3603
3604 Cursor Up behaves differently from zsh
3605 Some shells make Cursor Up search in the history only for commands start‐
3606 ing with what was already entered. mksh separates the shortcuts: Cursor
3607 Up goes up one command and PgUp searches the history as described above.
3608
3609 My question is not answered here!
3610 Check http://www.mirbsd.org/mksh-faq.htm which contains a collection of
3611 frequently asked questions about mksh in general, for packagers, etc.
3612 while these above are in user scope.
3613
3614MirBSD March 1, 2019 MirBSD