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