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