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