ksh
Public domain Korn shell command interpreter (UNIX)
Syntax:
ksh [+-abCefhikmnprsuvxX] [+-o option]
[ [ -c command-string [command-name]
| -s | file ] [argument…] ]
Runs on:
QNX OS, Linux, Microsoft Windows
Options:
You can specify the following options only on the command line:
- -c command-string
- Execute the command(s) contained in command-string.
- -i
- Use interactive mode.
- -l
- Login shell; also implies interactive mode.
- -s
- The shell reads commands from standard input; all non-option arguments are positional parameters.
- -r
- Use restricted mode.
In addition to the above, you can use the options described for the set builtin command on the command line.
Description:
The ksh is a public-domain version of the Korn shell. It's a command interpreter that's intended for both interactive and shell script use.
This description includes the following sections:
- Shell startup
- Command syntax
- Compound commands
- Quoting
- Aliases
- Substitution
- Parameters
- Tilde expansion
- Brace expansion (alternation)
- Filename patterns
- Input/output redirection
- Arithmetic expressions
- Coprocesses
- Functions
- POSIX mode
- Command execution and builtin commands
- Job control
- emacs interactive input-line editing
Shell startup
If neither the -c nor the -s option is specified, the first
non-option argument specifies the name of a file the shell reads commands from; if there are
no non-option arguments, the shell reads commands from standard input. The name of the shell
(i.e., the contents of the $0
parameter) is determined as follows: if the
-c option is used and there's a non-option argument, it's used as the
name; if commands are being read from a file, the file is used as the name; otherwise the
name the shell was called with (i.e., argv[0]) is used.
A shell is interactive if the -i option is used or if both standard input and standard error are attached to a tty. An interactive shell has job control enabled (if available), ignores the SIGINT, SIGQUIT and SIGTERM signals, and prints prompts before reading input (see PS1 and PS2 parameters). For noninteractive shells, the trackall option is on by default (see the set command below).
A shell is restricted if the -r option is used or if either the basename of the name the shell is invoked with or the SHELL parameter matches the pattern *r*sh (e.g., rsh, rksh, and so on). The following restrictions come into effect after the shell processes any profile and $ENV files:
- The cd builtin command is disabled.
- The SHELL, ENV and PATH environment variables can't be changed.
- Command names can't be specified with absolute or relative paths.
- You can't use the -p option of the command builtin command.
- Redirections that create files can't be used (i.e., >, >>|, >>, <>).
A shell is privileged if the -p option is used or if the real user ID or group ID doesn't match the effective user ID or group ID (see getuid(), and getgid()). A privileged shell doesn't process $HOME/.profile or the ENV environment variable (see below); instead it processes the /etc/suid_profile file. Clearing the privileged option causes the shell to set its effective user ID (group ID) to its real user ID (group ID).
If the basename of the name the shell is
called with (i.e., argv[0]) starts with -
or if the
-l option is used, the shell is assumed to be a login shell, and the
shell reads and executes the contents of /etc/profile and
$HOME/.profile if they exist and are readable.
If the ENV environment variable is set when the shell starts (or, in the case of login shells, after any profiles are processed), its value is subjected to parameter, command, arithmetic and tilde substitution and the resulting file (if any) is read and executed. If ENV isn't set (and not null) and ksh was compiled with the DEFAULT_ENV macro defined, the file named in that macro is included (after the above mentioned substitutions have been performed).
The exit status of the shell is 127 if the command file specified on the command line couldn't be opened, or nonzero if a fatal syntax error occurred during the execution of a script. In the absence of fatal errors, the exit status is that of the last command executed, or zero, if no command is executed.
Command syntax
The shell begins parsing its input by breaking it into words. Words, which are sequences
of characters, are delimited by unquoted whitespace characters (space, tab and newline) or
meta-characters (<
, >
, |
,
;
, &
, (
and )
).
Aside from delimiting words, spaces and tabs are ignored, while newlines usually delimit
commands. The meta-characters are used in building the following tokens:
<
,<&
,<<
,>
,>&
,>>
, and so on.- Specify redirections (see
Input/output redirection,
below). |
- Creates pipelines.
|&
- Creates coprocesses (see
Coprocesses,
below). ;
- Separates commands.
&
- Creates asynchronous pipelines.
&&
and||
- Specify conditional execution.
;;
- Used in case statements.
((
..))
- Used in arithmetic expressions.
(
..)
- Create subshells.
You can quote whitespace and meta-characters individually using backslash (\
),
or in groups using double ("
) or single ('
) quotes. Note
that the following characters are also treated specially by the shell and you must quote
them if they're to represent themselves:
\
,"
,'
- Quoting characters.
#
- If used at the beginning of a word, introduces a comment—everything after the
#
up to the nearest newline is ignored.An exception occurs when
#
is followed by!
shell. This allows you to run a script using an alternative shell interpreter. For example, if you have a C shell in /bin/csh, you can tell ksh to run your scripts using the C shell by starting the scripts with this:#!/bin/csh
$
- Introduces parameter, command and arithmetic substitutions (see
Substitution,
below). `
- Introduces an old-style command substitution (see
Substitution,
below). ~
- Begins a directory expansion (see
Tilde expansion,
below). {
and}
- Delimit csh-style alternations (see
Brace expansion,
below). *
,?
and[
- Used in filename generation (see
Filename patterns,
below).
As words and tokens are parsed, the shell builds commands, of which there are two basic types: simple commands, typically programs that are executed, and compound commands, such as for and if statements, grouping constructs and function definitions.
A simple command consists of some combination of parameter assignments (see Parameters,
below), input/output redirections (see
Input/output redirection,
below),
and command words; the only restriction is that parameter assignments come before any
command words. The command words, if any, define the command that's to be executed and its
arguments. The command may be a shell builtin command, a function or an external
command, i.e., a separate executable file that's located using the PATH
parameter (see Command execution and builtin
commands,
below). Note that all command constructs have an exit
status:
- For external commands, this is related to the status returned by wait() (if the command couldn't be found, the exit status is 127, if it couldn't be executed, the exit status is 126).
- The exit status of other command constructs (builtin commands, functions, compound commands, pipelines, lists, and so on) are all well defined and are described where the construct is described.
The exit status of a command consisting only of parameter assignments is that of the last command substitution performed during the parameter assignment, or zero if there were no command substitutions.
?
special parameter stores the exit status of the last nonasynchronous
command. For example, you can display the exit status by typing:echo $?
For more information, see Parameters,
below.
You can chain commands together using the |
token to form pipelines in
which the standard output of each command but the last is piped (see pipe()) to the standard input of the following command. The
exit status of a pipeline is that of its last command. You can prefix a pipeline with the
!
reserved word, which causes the exit status of the pipeline to be
logically complemented: if the original status is 0 the complemented status is 1, and if the
original status isn't 0, then the complemented status is 0.
You can create lists of commands by separating pipelines by any of the following tokens:
&&
,||
- Conditional execution: cmd1
&&
cmd2 executes cmd2 only if the exit status of cmd1 is zero;||
is the opposite—cmd2 is executed only if the exit status of cmd1 is nonzero.The
&&
and||
tokens have equal precedence, which is higher than that of&
,|&
and;
, which also have equal precedence. &
- Causes the preceding command to be executed asynchronously, that is, the shell starts the
command, but doesn't wait for it to complete (the shell does keep track of the status of
asynchronous commands—see
Job control,
below). When an asynchronous command is started when job control is disabled (i.e., in most scripts), the command is started with signals INT and QUIT ignored and with input redirected from /dev/null (however, redirections specified in the asynchronous command have precedence). |&
- Starts a coprocess, which is special kind of asynchronous process (see
Coprocesses,
below). ;
- Sequential execution: cmd1
;
cmd2 executes cmd1, and then executes cmd2 when the first command is done.
Note that a command must follow the &&
and ||
operators, while a command need not follow &
, |&
and ;
. The exit status of a list is that of the last command executed, with
the exception of asynchronous lists, for which the exit status is 0.
Compound commands
Compound commands are created using the following reserved words. These words are recognized only if they're unquoted and are used as the first word of a command (i.e., you can't put any parameter assignments or redirections before them):
case else function then !
do esac if time [[
done fi in until {
elif for select while }
{ echo foo; echo bar; }
{ echo foo; echo bar<newline>}
{ { echo foo; echo bar; } }
but this isn't:
{ echo foo; echo bar }
- ( list )
- Execute list in a subshell. There's no implicit way to pass environment changes from a subshell to its parent.
- { list }
- Compound construct; list is executed, but not in a subshell. Note that { and } are reserved words, not meta-characters.
- case word in [ [(] pattern [| pattern]…) list ;; ] … esac
The case statement attempts to match word against the specified patterns; the list associated with the first successfully matched pattern is executed.
Patterns used in case statements are the same as those used for filename patterns, except that the restrictions regarding
.
and/
are dropped. Note that any unquoted space before and after a pattern is stripped; you must quote any space within a pattern. Both the word and the patterns are subject to parameter, command, and arithmetic substitution as well as tilde substitution.For historical reasons, you can use open and close braces instead of in and esac (e.g., case $foo { *) echo bar; }).
The exit status of a case statement is that of the executed list; if no list is executed, the exit status is zero.
- for name [ in word … term ] do list done
- For each word in the specified word list (where term is
either a newline or a
;
), the parameter name is set to the word and list is executed. If in isn't used to specify a word list, the positional parameters ($1
,$2
, and so on) are used instead.For historical reasons, you can use open and close braces instead of do and done (e.g., for i; { echo $i; }).
The exit status of a for statement is the last exit status of list; if list is never executed, the exit status is zero.
- if list then list [elif list then list] … [else list] fi
- If the exit status of the first list is zero, the second
list is executed; otherwise the list following
the elif, if any, is executed with similar consequences. If all the
lists following the if and elif clauses fail
(i.e., exit with nonzero status), the list following the
else is executed.
The exit status of an if statement is that of the nonconditional list that's executed; if no nonconditional list is executed, the exit status is zero.
- select name [ in word … term ] do list done
- The select statement provides an automatic method of presenting the user with
a menu and selecting from it. An enumerated list of the specified
words (where term is either a newline or a
;
) is printed on standard error, followed by a prompt (PS3, normally"#? "
). A number corresponding to one of the enumerated words is then read from standard input, name is set to the selected word (or is unset if the selection isn't valid), REPLY is set to what was read (leading/trailing spaces are stripped), and list is executed.If you enter a blank line (i.e., zero or more
IFS
characters), the menu is reprinted without executing list. If REPLY is null when list completes, the enumerated list is printed, the prompt is printed and so on. This process is continues until an end-of-file is read, an interrupt is received or a break statement is executed inside the loop. If in word … is omitted, the positional parameters are used (i.e.,$1
,$2
, and so on).For historical reasons, you can use open and close braces instead of do and done (e.g., select i; { echo $i; }).
The exit status of a select statement is zero if a break statement is used to exit the loop, nonzero otherwise.
- until list do list done
- This works like while, except that the body is executed only while the exit status of the first list is nonzero.
- while list do list done
- A while is a prechecked loop. Its body is executed as often as the exit status of the first list is zero. The exit status of a while statement is the last exit status of the list in the body of the loop; if the body isn't executed, the exit status is zero.
- function name { list }
- Define the function name. See
Functions,
below. Note that redirections specified after a function definition are performed whenever the function is executed, not when the function definition is executed. - name () command
- Mostly the same as function. See
Functions,
below. - (( expression ))
- Evaluate the arithmetic expression expression; equivalent to let
"expression". See
Arithmetic expressions
and the let builtin command below. - [[ expression ]]
- Similar to the test and [ …
] builtin commands (described later), with the following exceptions:
- Field splitting and filename generation aren't performed on arguments.
- The
-a
(and) and-o
(or) operators are replaced with&&
and||
, respectively. - You must leave operators (e.g.,
-f
,=
,!
, and so on) unquoted. - The second operand of
!=
and=
expressions are patterns (e.g., the comparison in [[ foobar = f*r ]] succeeds). - There are two additional binary operators,
<
and>
that return true if their first string operand is less than or greater than their second string operand. - The single argument form of test, which tests if the argument
has nonzero length, isn't valid; you must always use explicit operators. For
example, instead of:
[ str ]
use:
[[ -n str ]]
- Parameter, command and arithmetic substitutions are performed as expressions are
evaluated and lazy expression evaluation is used for the
&&
and||
operators. This means that in the statement:[[ -r foo && $(< foo) = b*r ]]
the $(< foo) is evaluated if and only if the file foo exists and is readable.
Quoting
Quoting is used to prevent the shell from treating characters or words specially:
- A backslash (
\
) quotes the following character, unless it's at the end of a line, in which case both the backslash and the newline are stripped. - A single quote (
'
) quotes everything up to the next single quote (this may span lines). - A double quote (
"
) quotes all characters, except$
,`
and\
, up to the next unquoted double quote. The$
and`
characters inside double quotes have their usual meaning (i.e., parameter, command or arithmetic substitution), except no field splitting is carried out on the results of double-quoted substitutions.If a
\
inside a double-quoted string is followed by\
,$
,`
or"
, it's replaced by the second character; if it's followed by a newline, both the\
and the newline are stripped; otherwise, both the\
and the character following are unchanged.Note:SeePOSIX mode,
below, for a special rule regarding sequences of the form "…`…\"…`…".
Aliases
There are two types of aliases: normal command aliases and tracked aliases. Command aliases are normally used as shorthand for a long or often used command. The shell expands command aliases (i.e., substitutes the alias name for its value) when it reads the first word of a command. An expanded alias is reprocessed to check for more aliases. If a command alias ends in a space or tab, the following word is also checked for alias expansion. The alias expansion process stops when a word that isn't an alias is found, when a quoted word is found or when an alias word that's currently being expanded is found.
The shell automatically defines the following command aliases:
autoload='typeset -fu'
functions='typeset -f'
hash='alias -t'
history='fc -l'
integer='typeset -i'
local='typeset'
login='exec login'
newgrp='exec newgrp'
nohup='nohup '
r='fc -e -'
stop='kill -STOP'
suspend='kill -STOP $$'
type='whence -v'
Tracked aliases allow the shell to remember where it found a particular command. The first time the shell does a path search for a command that's marked as a tracked alias, it saves the full path of the command. The next time the command is executed, the shell checks the saved path to see that it's still valid, and if so, avoids repeating the path search. You can create and list tracked aliases by using alias -t.
If the trackall option is set (i.e., set -o trackall or set -h), the shell tracks all commands. This option is set automatically for noninteractive shells. For interactive shells, only the following commands are automatically tracked:
Substitution
The first step the shell takes in executing a simple command is to perform substitutions on the words of the command. There are three kinds of substitution:
This substitution: | Takes the form: |
---|---|
Parameter | $name or ${…}
(see Parameters,below) |
Command | $(command) or `command` |
Arithmetic | $((expression)) |
If a substitution appears outside of double quotes, the results of the substitution are generally subject to word or field splitting according to the current value of the IFS (internal field separators) parameter.
The IFS parameter specifies a list of characters that are used to break a string up into several words; any characters from the set space, tab and newline that appear in the IFS characters are called IFS whitespace. Sequences of one or more IFS whitespace characters, in combination with zero or one non-IFS whitespace characters delimit a field. As a special case, leading and trailing IFS whitespace is stripped (i.e., no leading or trailing empty field is created by it); leading or trailing non-IFS whitespace does create an empty field.
For example: if IFS is set to <space>:
, the sequence of
characters <space>A<space>:<space><space>B::D
contains four fields: A
, B
, an empty field, and
D
. Note that if the IFS parameter is set to the null
string, no field splitting is done; if the parameter is unset, the default value of space,
tab, and newline is used.
The results of substitution are, unless otherwise specified, also subject to brace expansion and filename expansion (see the relevant sections below).
A command substitution is replaced by the output generated by the specified command, which is run
in a subshell. For $(command)
substitutions, normal quoting rules are used when command is parsed,
however, for the `command` form, a
\
followed by any of $
, `
or
\
is stripped (a \
followed by any other character is
unchanged).
As a special case in command substitutions, a command of the form < file is interpreted to mean substitute the contents of file. For example, $(< foo) has the same effect as $(cat foo), but the former is carried out more efficiently because no process is started.
Arithmetic substitutions are replaced by the value of the specified expression.
For example, the command echo $((2+3*4)) prints 14.
See Arithmetic expressions
for a description of an expression.
Parameters
Parameters are shell variables; you can assign values to them and access their values using a
parameter substitution. A parameter name is either one of the special single punctuation or
digit character parameters described below, or a letter followed by zero or more letters or
digits (the underscore (_
) counts as a letter). Parameter substitutions
take the form $name or
${name}, where
name is a parameter name. If substitution is performed on a parameter
that isn't set, a null string is substituted unless the nounset option
(set -o nounset or set -u) is set, in which case an
error occurs.
You can assign values to parameters in a number of ways:
- The shell implicitly sets some parameters, such as #, PWD, and so on; this is the only way the special single character parameters are set.
- Parameters are imported from the shell's environment at startup.
- You can assign values to parameters on the command line. For example, FOO=bar
sets the parameter FOO to
bar
; you can do multiple parameter assignments on a single command line and follow them by a simple command, in which case the assignments are in effect only for the duration of the command (such assignments are also exported—see below for implications of this).Note:You must leave both the parameter name and the=
unquoted for the shell to recognize a parameter assignment. - You can set parameters with the export, readonly, and typeset commands; see their descriptions in
Command execution and builtin commands.
- The for and select loops set parameters as well as the getopts, read, and set -A commands.
- You can assign values to parameters using assignment operators inside arithmetic expressions
(see
Arithmetic expressions,
below) or using the ${name=value} form of parameter substitution (see below).
Parameters with the export attribute (set using the export or typeset
-x commands, or by parameter assignments followed by simple commands)
are put in the environment (see environ() in the C Library Reference) of
commands run by the shell as
name=
value pairs. The order in
which parameters appear in the environment of a command is arbitrary. When the shell starts
up, it extracts parameters and their values from its environment and automatically sets the
export attribute for those parameters.
You can apply modifiers to the ${name} form of parameter substitution:
- ${name:-word}
- If name is set and not null, it's substituted, otherwise word is substituted.
- ${name:+word}
- If name is set and not null, word is substituted, otherwise nothing is substituted.
- ${name:=word}
- If name is set and not null, it's substituted, otherwise it's assigned word and the resulting value of name is substituted.
- ${name:?word}
- If name is set and not null, it's substituted, otherwise
word is printed on standard error (preceded by
name:) and an error occurs (normally causing termination of a shell
script, function or .-script). If word is omitted, the string
parameter null or not set
is used instead.
In the above modifiers, you can omit the :
, in which case the conditions depend
only on name's being set (as opposed to set and not null). If
word is needed, parameter, command, arithmetic and tilde substitution
are performed on it; if word isn't needed, it isn't evaluated.
You can also use the following forms of parameter substitution:
- ${#name}
- The number of positional parameters if name is
*
,@
or isn't specified, or the length of the string value of parameter name. - ${#name[*]} or ${#name[@]}
- The number of elements in the array name.
- ${name#pattern} or ${name##pattern}
- If pattern matches the beginning of the value of parameter name,
the matched text is deleted from the result of substitution.
A single
#
results in the shortest match, two results in the longest match. - ${name%pattern} or ${name%%pattern}
- Like ${…#…} substitution, but it deletes from the end of the value.
The shell implicitly set the following special parameters; you can't set them directly using assignments:
!
- The process ID of the last background process started. If no background processes have been started, the parameter isn't set.
#
- The number of positional parameters (i.e., $1, $2, and so on).
$
- The process ID of the shell, or the PID of the original shell if it's a subshell.
-
- The concatenation of the current single letter options (see the set command below for a list of options).
?
- The exit status of the last nonasynchronous command executed. If the last command was killed by a signal, $? is set to 128 plus the signal number.
0
- The name the shell was invoked with (i.e., argv[0]), or the
command-name if it was invoked with the -c option
and the command-name was supplied, or the file
argument, if it was supplied. If the posix option isn't set,
$0
is the name of the current function or script. 1
…9
- The first nine positional parameters that were supplied to the shell, function or .-script. You can access further positional parameters by using ${number}.
*
- All positional parameters (except parameter 0), i.e., $1 $2 $3 and so on. If used outside of double quotes, parameters are separate words (which are subjected to word splitting); if used within double quotes, parameters are separated by the first character of the IFS parameter (or the empty string if IFS is null).
@
- Same as
$*
, unless it's used inside double quotes, in which case a separate word is generated for each positional parameter—if there are no positional parameters, no word is generated (you can use$@
to access arguments, verbatim, without losing null arguments or splitting arguments with spaces).
The shell sets and/or uses the following parameters:
_
(underscore)- When an external command is executed by the shell, this parameter is set in the environment of the new process to the path of the executed command. In interactive use, this parameter is also set in the parent shell to the last word of the previous command. When MAILPATH messages are evaluated, this parameter contains the name of the file that changed (see MAILPATH parameter below).
- CDPATH
- The search path for the cd builtin command. Works
the same way as PATH for those directories not beginning with
/
in cd commands. Note that if CDPATH is set and doesn't contain.
or an empty path, the current directory isn't searched. - COLUMNS
- Set to the number of columns in the terminal or window. Currently set to the cols value as reported by stty if that value is nonzero. This parameter is used by the interactive line editing modes, and by select, set -o, and kill -l commands to format information in columns.
- EDITOR
- If the VISUAL parameter isn't set, this parameter controls the command line editing mode for interactive shells. See VISUAL parameter below for how this works.
- ENV
- If this environment variable is found to be set after any profile files are executed, the expanded value is used as a shell start-up file. It typically contains function and alias definitions. People frequently call this file .kshrc, but you can give it whatever name you like.
- EXECSHELL
- If set, this parameter is assumed to contain the shell that's to be used to execute commands
that execve() fails to execute and that don't start with a
#!
shell sequence. - FCEDIT
- The editor used by the fc command (see below).
- FPATH
- Like PATH, but used when an undefined function is executed to locate the file
defining the function. It's also searched when a command can't be found using
PATH. For more information, see
Functions,
below. - HISTFILE
- The name of the file used to store history. When assigned to, history is loaded from the
specified file. Also, several invocations of the shell running on the same machine share
their history if their HISTFILE parameters all point at the same file.
Note:If HISTFILE isn't set, no history file is used. This is different from the original Korn shell, which uses $HOME/.sh_history; in the future, ksh may also use a default history file.
- HISTSIZE
- The number of commands normally stored for history, default 128.
- HOME
- The default directory for the cd command and the
value substituted for an unqualified
~
(seeTilde expansion,
below). - IFS
- Internal field separator, used during substitution and by the read command, to split values into distinct arguments;
normally set to space, tab and newline. See
Substitution,
above, for details.Note:This parameter isn't imported from the environment when the shell is started. - KSH_VERSION
- The version of shell and the date the version was created (readonly).
See also the version commands in
emacs interactive input-line editing
below. - If set, you're told of the arrival of mail in the named file. This parameter is ignored if the MAILPATH parameter is set.
- MAILCHECK
- How often, in seconds, the shell checks for mail in the file(s) specified by MAIL or MAILPATH. If 0, the shell checks before each prompt. The default is 600 (10 minutes).
- MAILPATH
- A list of files to be checked for mail. The list is separated by colons, and each file may be
followed by a
?
and a message to be printed if new mail has arrived. Command, parameter and arithmetic substitution is performed on the message, and, during substitution, the parameter $_ contains the name of the file. The default message isyou have mail in $_
. - OLDPWD
- The previous working directory. Unset if cd hasn't successfully changed directories since the shell started, or if the shell doesn't know where it is.
- OPTARG
- When using getopts, this parameter contains the argument for a parsed option, if it requires one.
- OPTIND
- The index of the last argument processed when using getopts. Assigning 1 to this parameter causes getopts to process arguments from the beginning the next time it's invoked.
- PATH
- A colon-separated list of directories that are searched when looking for commands and
.
'd files. An empty string resulting from a leading or trailing colon, or two adjacent colons is treated as a.
, the current directory. For more information on setting PATH, seeSetting PATH and LD_LIBRARY_PATH
in the Configuring Your Environment chapter of the QNX OS User's Guide. - POSIXLY_CORRECT
- If set, this parameter causes the posix option to be enabled. See
POSIX mode,
below. - PPID
- The process ID of the shell's parent (read only).
- PS1
- The primary prompt for interactive shells. Parameter, command, and arithmetic substitutions are
performed, and
!
is replaced with the current command number (see the fc command below). You can put a literal!
in the prompt by placing!!
in PS1.Note that since the command line editors try to figure out how long the prompt is (so they know how far it is to the edge of the screen), escape codes in the prompt tend to mess things up. You can tell the shell not to count certain sequences (such as escape codes) by prefixing your prompt with a nonprinting character (such as Ctrl A ) followed by a carriage return and then delimiting the escape codes with this nonprinting character. If you don't have any nonprinting characters, you're out of luck… BTW, don't blame me for this hack; it's in the original ksh. Default is
$
for non-root users,#
for root. - PS2
- Secondary prompt string, by default
"> "
, used when more input is needed to complete a command. - PS3
- Prompt used by the select statement when reading a menu selection. Default is
"#? "
. - PS4
- Used to prefix commands that are printed during execution tracing (see the set -x command below). Parameter, command and arithmetic
substitutions are performed before it's printed. Default is
"+ "
. - PWD
- The current working directory. May be unset or null if the shell doesn't know where it is.
- RANDOM
- A simple random number generator. Every time RANDOM is referenced, it's assigned the next number in a random number series. You can set the point in the series by assigning a number to RANDOM (see rand()).
- REPLY
- Default parameter for the read command if no names are given. Also used in select loops to store the value that's read from standard input.
- SECONDS
- The number of seconds since the shell started or, if the parameter has been assigned an integer value, the number of seconds since the assignment plus the value that was assigned.
- TMOUT
- If set to a positive integer in an interactive shell, it specifies the maximum number of seconds the shell waits for input after printing the primary prompt (PS1). If the time is exceeded, the shell exits.
- TMPDIR
- The directory in which to create shell temporary files. If this parameter isn't set, or doesn't contain the absolute path of a writable directory, temporary files are created in /tmp.
- VISUAL
- If set, this parameter controls the command-line editing mode for interactive shells. If the
last component of the path specified in this parameter contains the string
emacs
orgmacs
, the emacs or gmacs (Gosling emacs) editing mode is enabled, respectively.
Tilde expansion
Tilde expansion, which is done in parallel with
parameter substitution, is done on words starting with an unquoted ~
. The
characters following the tilde, up to the first slash (/
), if any, are
assumed to be a login name. If the login name is empty, +
or
-
, the value of the HOME, PWD, or
OLDPWD parameter is substituted, respectively. Otherwise, the password file
is searched for the login name, and the tilde expression is substituted with the user's home
directory. If the login name isn't found in the password file or if any quoting or parameter
substitution occurs in the login name, no substitution is performed.
In parameter assignments (those preceding a simple command or those occurring in the arguments of
alias, export, readonly, and typeset), tilde expansion is done after any unquoted colon
(:
), and login names are also delimited by colons.
The home directory of previously expanded login names are cached and reused. You can use the alias -d command to list, change and add directory aliases to this cache. For example:
alias -d fac=/usr/local/facilities; cd ~fac/bin
Brace expansion (alternation)
Brace expressions, which take the form:
prefix{str1,…,strN}suffix
are expanded to N words, each of which is the concatenation of
prefix, stri and suffix.
For example, a{c,b{X,Y},d}e expands to four words:
ace
, abXe
, abYe
, and ade
).
As noted in the example, you can nest brace expressions, and the resulting
words aren't sorted.
Brace expressions must contain an unquoted comma (,
) for expansion
to occur (i.e., {} and {foo} aren't expanded).
Brace expansion is carried out after parameter substitution and before
filename generation.
Filename patterns
A
filename pattern is a word containing one or more unquoted ?
or
*
characters or […]
sequences. Once brace
expansion has been performed, the shell replaces filename patterns with the sorted names of
all the files that match the pattern (if no files match, the word is left unchanged). The
pattern elements have the following meanings:
?
- Matches any single character.
*
- Matches any sequence of characters.
[…]
- Matches any of the characters inside the brackets. You can specify ranges of characters by
separating two characters with a
-
. For example, [a0-9] matches the lettera
or any digit. In order for a-
to represent itself, you must either quote it or use it as the first or last character in the character list. Similarly, you must quote a]
or use it as the first character in the list if it's to represent itself instead of the end of the list.Also, a
!
appearing at the start of the list has special meaning (see below), so to represent itself, you must quote it or use it later in the list. [!…]
- Like
[…]
, except it matches any character not inside the brackets. *(pattern| … |pattern)
- Matches any string of characters that matches zero or more occurrences of the specified patterns.
For example, the pattern
*(foo|bar)
matches the empty string, as well as the stringsfoo
,bar
,foobarfoo
, and so on. +(pattern| … |pattern)
- Matches any string of characters that matches one or more occurrences of the specified patterns.
For example, the pattern
+(foo|bar)
matches the stringsfoo
,bar
,foobarfoo
, and so on. ?(pattern| … |pattern)
- Matches the empty string or a string that matches one of the specified patterns. For example,
the pattern
?(foo|bar)
matches only the empty string,foo
andbar
. @(pattern| … |pattern)
- Matches a string that matches one of the specified patterns. For example, the pattern
@(foo|bar)
matches only the stringsfoo
andbar
. !(pattern| … |pattern)
- Matches any string that doesn't match one of the specified patterns. For example: the pattern
!(foo|bar)
matches all strings exceptfoo
andbar
; the pattern!(*)
matches no strings; the pattern!(?)*
matches all strings (think about it).
Note that none of the above pattern elements match either a period (.
) at the
start of a filename or a slash (/
), even if they are explicitly used in a
[…]
sequence.
.*
matches the
.
and ..
names. This could cause problems with scripts
that assume that the shell never matches these names.If the markdirs option is set, any directories that result from filename
generation are marked with a trailing /
.
[:class-name:]
inside
a […]
expression) aren't yet implemented.Input/output redirection
When a command is executed, its standard input, standard output and standard error (file descriptors 0, 1 and 2, respectively) are normally inherited from the shell. Three exceptions to this are commands in pipelines, for which standard input and/or standard output are those set up by the pipeline, asynchronous commands created when job control is disabled, for which standard input is initially set to be from /dev/null, and commands for which any of the following redirections have been specified:
>
file- Standard output is redirected to file. If file doesn't exist, it's created; if it does exist, is a regular file and the noclobber option is set, an error occurs, otherwise the file is truncated. Note that this means the command cmd < foo > foo opens foo for reading and then truncates it when it opens it for writing, before cmd gets a chance to actually read it.
>|
file- Same as
>
, except the file is truncated, even if the noclobber option is set. >>
file- Same as
>
, except an existing file is appended to instead of being truncated. Also, the file is opened in append mode, so writes always go to the end of the file (see open()). <
file- Standard input is redirected from file, which is opened for reading.
<>
file- Same as
<
, except the file is opened for reading and writing. <<
marker- After reading the command line containing this kind of redirection (called a here
document), the shell copies lines from the command source into a temporary file
until a line matching marker is read. When the command is executed,
standard input is redirected from the temporary file. Note:The line at the end of the
here document
must match marker exactly; it must not have any leading or trailing whitespace characters.If marker contains no quoted characters, the contents of the temporary file are processed as if enclosed in double quotes each time the command is executed, so parameter, command and arithmetic substitutions are performed, along with backslash (
\
) escapes for$
,`
,\
and\newline
. If multiple here documents are used on the same command line, they're saved in order. <<-
marker- Same as <<, except leading tabs are stripped from lines in the here document.
<&
fd- Standard input is duplicated from file descriptor fd. The
fd can be a single digit, indicating the number of an existing file
descriptor, the letter
p
, indicating the file descriptor associated with the output of the current coprocess, or the character-
, indicating standard input is to be closed. >&
fd- Same as
<&
, except the operation is done on standard output.
In any of the above redirections, you can explicitly give the file descriptor that's redirected (i.e., standard input or standard output) by preceding the redirection with a single digit. Parameter, command and arithmetic substitutions, tilde substitutions and filename generation are all performed on the file, marker and fd arguments of redirections. Note however, that the results of any filename generation are only used if a single file is matched; if multiple files match, the word with the unexpanded filename generation characters is used. Note that in restricted shells, you can't use redirections that can create files.
cat /foo/bar 2>&1 > /dev/null | cat -n
prints an error with a line number prepended to it.Arithmetic expressions
You can use integer arithmetic expressions with the let command, inside $((…))
expressions, inside array references (e.g.,
name[expr]), as numeric arguments to the test command, and as the value of an assignment
to an integer parameter.
Expressions may contain alphanumeric parameter identifiers, array references, and integer constants. You can combine expressions with the following C operators (listed and grouped in increasing order of precedence):
- Unary operators
- + - ! ~ ++ --
- Binary operators
, = *= /= %= += -= <<= >>= &= ^= |= || && | ^ & == != < <= >= > << >> + - * / %
- Ternary operator
- ?: (Precedence is immediately higher than assignment.)
- Grouping operators
- ( )
You can specify integer constants with arbitrary bases by using the notation
base#
number, where base
is a decimal integer specifying
the base, and number is a number in the specified base.
The operators are evaluated as follows:
- Unary
+
- Result is the argument (included for completeness).
- Unary
-
- Negation.
!
- Logical not; the result is 1 if argument is zero, 0 if not.
~
- Arithmetic (bitwise) not.
++
- Increment; you must apply it to a parameter (not a literal or other expression)—the parameter is incremented by 1. When used as a prefix operator, the result is the incremented value of the parameter, when used as a postfix operator, the result is the original value of the parameter.
--
- Similar to
++
, except the parameter is decremented by 1. ,
- Separates two arithmetic expressions; the left hand side is evaluated first, then the right. The result is value of the expression on the right hand side.
=
- Assignment; the variable on the left is set to the value on the right.
*= /= %= += -= <<= >>= &= ^= |=
- Assignment operators:
var op= expr
is the same as:
var = var op ( expr )
||
- Logical OR; the result is 1 if either argument is nonzero, 0 if not. The right argument is evaluated only if the left argument is zero.
&&
- Logical AND; the result is 1 if both arguments are nonzero, 0 if not. The right argument is evaluated only if the left argument is nonzero.
|
- Arithmetic (bitwise) OR.
^
- Arithmetic (bitwise) exclusive-OR.
&
- Arithmetic (bitwise) AND.
==
- Equal; the result is 1 if both arguments are equal, 0 if not.
!=
- Not equal; the result is 0 if both arguments are equal, 1 if not.
<
- Less than; the result is 1 if the left argument is less than the right, 0 if not.
<= >= >
- Less than or equal, greater than or equal, greater than. See
<
. << >>
- Shift left (right); the result is the left argument with its bits shifted left (right) by the amount given in the right argument.
+ - * /
- Addition, subtraction, multiplication, and division.
%
- Remainder; the result is the remainder of the division of the left argument by the right. The sign of the result is undefined if either argument is negative.
arg1 ? arg2 : arg3
- If arg1 is nonzero, the result is arg2, otherwise arg3.
Coprocesses
A coprocess, which is a
pipeline created with the |&
operator, is an asynchronous process that
the shell can both write to (using print
-p) and read from (using read
-p). The input and output of the coprocess can also be manipulated
using >&p
and <&p
redirections,
respectively. Once a coprocess has been started, another can't be started until the
coprocess exits, or until the coprocess input has been redirected using an exec
n>&p redirection. If a
coprocess's input is redirected in this way, the next coprocess to be started shares the
output with the first coprocess, unless the output of the initial coprocess has been
redirected using an exec
n<&p redirection.
Some notes concerning coprocesses:
- The only way to close the coprocess input (so the coprocess reads an end-of-file) is to redirect the input to a numbered file descriptor and then close that file descriptor (e.g., exec 3>&p;exec 3>&-).
- In order for coprocesses to share a common output, the shell must keep the write portion of the
output pipe open. This means that end of file won't be detected until all coprocesses
sharing the coprocess output have exited (when they all exit, the shell closes its copy of
the pipe). You can avoid this by redirecting the output to a numbered file descriptor (as
this also causes the shell to close its copy).Note:This behavior is slightly different from the original Korn shell, which closes its copy of the write portion of the coprocess's output when the most recently started coprocess (instead of when all sharing coprocesses) exits.
- The print -p command ignores SIGPIPE signals during writes if the signal isn't being trapped or ignored; the same isn't true if the coprocess input has been duplicated to another file descriptor and print -un is used.
Functions
Functions are defined using either Korn shell function name syntax or the Bourne/POSIX shell name() syntax (see below for the difference between the two forms). Functions are like .-scripts in that they are executed in the current environment, however, unlike .-scripts, shell arguments (i.e., positional parameters, $1, and so on) are never visible inside them. When the shell is determining the location of a command, functions are searched after special builtin commands, and before regular and nonregular builtins, and before the PATH is searched.
You can delete an existing function by using unset -f function-name. You can list the functions by executing typeset +f, and list the function definitions by executing typeset -f. You can use the autoload command (which is an alias for typeset -fu) to create undefined functions; when an undefined function is executed, the shell searches the path specified in the FPATH parameter for a file with the same name as the function, which, if found is read and executed. If after executing the file, the named function is found to be defined, the function is executed, otherwise, the normal command search is continued (i.e., the shell searches the regular builtin command table and PATH). Note that if a command isn't found using PATH, the shell tries to autoload a function using FPATH (this is an undocumented feature of the original Korn shell).
Functions can have two attributes, trace and export, which you set with typeset -ft and typeset -fx. When a traced function is executed, the shell's xtrace option is turned on for the function's duration, otherwise the xtrace option is turned off. The export attribute of functions is currently not used. In the original Korn shell, exported functions are visible to shell scripts that are executed.
Since functions are executed in the current shell environment, parameter assignments made inside
functions are visible after the function completes. If this isn't the desired effect, you
can use the typeset command inside a
function to create a local parameter. Note that special parameters (e.g.,
$$
, $!
) can't be scoped in this way.
The exit status of a function is that of the last command executed in the function. You can make a function finish immediately by using the return command; you can also use this to explicitly specify the exit status.
Functions defined with the function reserved word are treated differently in
the following ways from functions defined with the ()
notation:
- The
$0
parameter is set to the name of the function (Bourne-style functions leave$0
untouched). - Parameter assignments preceding function calls aren't kept in the shell environment (executing Bourne-style functions keeps assignments).
- OPTIND is saved/reset and restored on entry and exit from the function so you can use getopts properly both inside and outside the function (Bourne-style functions leave OPTIND untouched, so using getopts inside a function interferes with using getopts outside the function).
In the future, the following differences will also be added:
- A separate trap/signal environment will be used during the execution of functions. This will mean that traps set inside a function won't affect the shell's traps and signals that aren't ignored in the shell (but may be trapped) will have their default effect in a function.
- The EXIT trap, if set in a function, will be executed after the function returns.
POSIX mode
The shell is intended to be POSIX compliant, however, in some cases, POSIX behavior is contrary either to the original Korn shell behavior or to user convenience. How the shell behaves in these cases is determined by the state of the posix option (set -o posix); if it's on, the POSIX behavior is followed, otherwise it isn't. The posix option is set automatically when the shell starts up if the environment contains the POSIXLY_CORRECT parameter. (The shell can also be compiled so that it's in POSIX mode by default, however this usually isn't desirable).
The following is a list of things that are affected by the state of the posix option:
\"
inside double quoted`…`
command substitutions- In POSIX mode, the
\"
is interpreted when the command is interpreted; in non-POSIX mode, the backslash is stripped before the command substitution is interpreted. For example, echo "`echo \"hi\"`" produces"hi"
in POSIX mode,hi
in non-POSIX mode. To avoid problems, use the$(…)
form of command substitution. - kill -l output
- In POSIX mode, signal names are listed one a single line; in non-POSIX mode, signal numbers, names and descriptions are printed in columns. In future, a new option (-v perhaps) will be added to distinguish the two behaviors.
- fg exit status
- In POSIX mode, the exit status is 0 if no errors occur; in non-POSIX mode, the exit status is that of the last foregrounded job.
- getopts
- In POSIX mode, options must start with a
-
; in non-POSIX mode, options can start with either-
or+
. - Brace expansion (also known as alternation)
- In POSIX mode, brace expansion is disabled; in non-POSIX mode, it's enabled. Note that set -o posix (or setting the POSIXLY_CORRECT parameter) automatically turns the braceexpand option off, but you can explicitly turn it on later.
- set -
- In POSIX mode, this doesn't clear the verbose or xtrace options; in non-POSIX mode, it does.
- set exit status
- In POSIX mode, the exit status of set is 0 if there are no errors; in non-POSIX mode, the exit status is that of any command substitutions performed in generating the set command. For example, set -- `false`; echo $? prints 0 in POSIX mode, 1 in non-POSIX mode. This construct is used in most shell scripts that use the old getopt command.
- Argument expansion of alias, export, readonly, and typeset commands
- In POSIX mode, normal argument expansion is done; in non-POSIX mode, field splitting, file globing, brace expansion and (normal) tilde expansion are turned off, and assignment tilde expansion is turned on.
- Signal specification
- In POSIX mode, you can specify signals as digits only if the signal numbers match POSIX values (i.e., SIGHUP=1, SIGINT=2, SIGQUIT=3, SIGABRT=6, SIGKILL=9, SIGALRM=14, and SIGTERM=15); in non-POSIX mode, signals can always be digits.
- Alias expansion
- In POSIX mode, alias expansion is only carried out when reading command words; in non-POSIX
mode, alias expansion is carried out on any word following an alias that ended in a
space. For example, the following for loop:
alias a='for ' i='j' a i in 1 2; do echo i=$i j=$j; done
uses parameter i in POSIX mode, but j in non-POSIX mode.
- Test
- In POSIX mode, the expression -t (preceded by some number of
!
arguments) is always true, as it's a nonzero length string; in non-POSIX mode, it tests if file descriptor 1 is a tty (i.e., you can leave out the fd argument to the -t test, and it defaults to 1).
Command execution and builtin commands
After evaluation of command-line arguments, redirections and parameter assignments, the command is checked to determine its type, in this order:
- Special builtin
- Function
- Regular builtin
- Name of a file to execute found using the PATH parameter.
Special builtin commands differ from other commands in that the PATH parameter isn't used to find them, an error during their execution can cause a noninteractive shell to exit and parameter assignments that are specified before the command are kept after the command completes. Just to confuse things, if the posix option is turned off (see set command below) some special commands are very special in that no field splitting, file globing, brace expansion nor tilde expansion is performed on arguments that look like assignments. Regular builtin commands are different only in that the PATH parameter isn't used to find them.
The original ksh and POSIX differ somewhat in which commands are considered special or regular.
The POSIX special commands are:
Additional ksh special commands are:
The very special commands (non-POSIX mode) are:
The POSIX regular commands are:
The additional ksh regular commands are:
In the future, the additional ksh special and regular commands may be treated differently from the POSIX special and regular commands.
Once the type of the command has been determined, any command-line parameter assignments are performed and exported for the duration of the command.
The following sections describe the builtin commands:
. (dot) builtin command
. file [arg …]
Execute the commands in file in the current environment. The file is searched for in the directories of PATH. If arguments are given, you can use the positional parameters to access them while file is being executed. If no arguments are given, the positional parameters are those of the environment the command is used in.
: (null) builtin command
: [ … ]
The null command. The exit status is set to zero.
alias builtin command
alias [ -d | +-t [-r] ] [+-px] [+-] [name[=value] …]
Without arguments, alias lists all
aliases. For any name without a value, the existing alias is listed. Any name with a value
defines an alias (see Aliases,
above).
When listing aliases, one of two formats is used:
- Normally, aliases are listed as name
=
value, where value is quoted. - If options were preceded with
+
or a lone+
is given on the command line, only name is printed.
In addition, if the -p option is used, each alias is prefixed with the string alias .
The -x option sets (+x clears) the export attribute of an alias, or, if no names are given, lists the aliases with the export attribute (exporting an alias has no affect).
The -t option indicates that tracked aliases are to be listed/set (values specified on the command line are ignored for tracked aliases). The -r option indicates that all tracked aliases are to be reset.
The -d option causes directory aliases, which are used in tilde expansion, to be
listed or set (see Tilde expansion,
above).
bg builtin command
bg [job …]
Resume the specified stopped job(s) in the background.
If no jobs are specified, %+
is assumed.
This command is only available on systems that support job control.
See Job control,
below,
for more information.
bind builtin command
bind [-m] [key[=editing-command] …]
Set or view the current
emacs command editing key bindings/macros. See emacs interactive input-line
editing,
below, for a complete description.
break builtin command
break [level]
Exit the levelth innermost for, select, until, or while loop. The level defaults to 1.
builtin builtin command
builtin command [arg …]
Execute the builtin command command. This is useful for explicitly executing the builtin version of commands (such as kill) that are also available as executable files.
cd builtin command
cd [-LP] [dir]
Set the working
directory to dir. If the parameter CDPATH is set, it lists
the search path for the directory containing dir. A null path means the
current directory. If dir is missing, the home directory
$HOME is used. If dir is -
, the
previous working directory is used (see OLDPWD parameter). If
-L option (logical path) is used or if the physical
option (see the set command below) isn't
set, references to ..
in dir are relative to the path
used to get to the directory. If -P option (physical path) is used or if
the physical option is set, ..
is relative to the
filesystem directory tree. The PWD and OLDPWD parameters are
updated to reflect the current and old working directory, respectively.
cd [-LP] old new
The string new is substituted for old in the current directory, and the shell attempts to change to the new directory.
command builtin command
command [-pvV] cmd [arg …]
If neither the -v nor -V option is given, cmd is executed exactly as if the command hadn't been specified, with two exceptions:
- The cmd can't be a shell function.
- Special builtin commands lose their specialness (i.e., redirection and utility errors don't cause the shell to exit, and command assignments aren't permanent).
If you specify the -p option, a default search path is used instead of the current value of PATH. The actual value of the default path is system-dependent: on POSIXish systems, it's the value returned by:
getconf _CS_PATH
If the -v option is given, instead of executing cmd, information about what would be executed is given (and the same is done for arg …): for special and regular builtin commands and functions, their names are simply printed, for aliases, a command that defines them is printed, and for commands found by searching the PATH parameter, the full path of the command is printed. If no command is found, (i.e., the path search fails), nothing is printed and command exits with a nonzero status. The -V option is like the -v option, except it's more verbose.
continue builtin command
continue [level]
Jump to the beginning of the levelth innermost for, select, until, or while loop. The level defaults to 1.
echo builtin command
echo [-neE] [arg …]
Print the arguments (separated by spaces) followed by a newline, to standard output.
The newline is suppressed if any of the arguments contain the backslash sequence \c
.
See the print command below for a list
of other backslash sequences that are recognized.
The options are provided for compatibility with BSD shell scripts: -n suppresses the trailing newline, -e enables backslash interpretation (a no-op, since this is normally done), and -E suppresses backslash interpretation.
This command is also available as an executable; see echo.
eval builtin command
eval command …
Concatenate the arguments (with spaces between them) to form a single string that the shell then parses and executes in the current environment.
exec builtin command
exec [command [arg …]]
Execute the command without forking, replacing the shell process.
If no arguments are given, any IO redirection is permanent and the shell isn't replaced. Any file descriptors greater than 2 that are opened or duped in this way aren't made available to other executed commands (i.e., . commands that aren't builtin to the shell). Note that the Bourne shell differs here: it does pass these file descriptors on.
exit builtin command
exit [status]
Exit from the shell with the specified exit status. If
status isn't specified, the exit status is the current value of the
?
parameter.
export builtin command
export [-p] [parameter[=value]] …
Set the export attribute of the named parameters. Exported parameters are passed in the environment to executed commands. If values are specified, the named parameters also assigned.
If no parameters are specified, the names of all parameters with the export attribute are printed one per line, unless the -p option is used, in which case export commands defining all exported parameters, including their values, are printed.
false builtin command
false
A command that exits with a nonzero status.
This command is also available as an executable; see false.
fc builtin command
fc [-e editor | -l [-n]] [-r] [first [last]]
The first and last arguments select commands from the history. You can select commands by history number, or a string specifying the most recent command starting with that string. The -l option lists the command on stdout, and -n inhibits the default command numbers. The -r option reverses the order of the list. Without -l, the selected commands are edited by the editor specified with the -e option, or if no -e is specified, the editor specified by the FCEDIT parameter (if this parameter isn't set, /bin/ed is used), and then executed by the shell.
fc [-e - | -s] [-g] [old=new] [prefix]
Reexecute the selected command (the previous command by default) after performing the optional substitution of old with new. If -g is specified, all occurrences of old are replaced with new. This command is usually accessed with the predefined alias r='fc -e -'.
fg builtin command
fg [job …]
Resume the specified job(s) in the
foreground. If no jobs are specified, %+
is assumed. This command is
available only on systems that support job control. See Job
control,
below, for more information.
getopts builtin command
getopts optstring name [arg …]
The getopts command is used by shell procedures to parse the specified arguments (or positional parameters, if no arguments are given) and to check for legal options. The optstring argument contains the option letters that getopts is to recognize. If a letter is followed by a colon, the option is expected to have an argument. You can group options that don't take arguments into a single argument. If an option takes an argument and the option character isn't the last character of the argument it's found in, the remainder of the argument is taken to be the option's argument, otherwise, the next argument is the option's argument.
Each time getopts is invoked, it places the next option in the shell parameter
name and the index of the next argument to be processed in the shell
parameter OPTIND. If the option was introduced with a +
, the
option placed in name is prefixed with a +
. When an
option requires an argument, getopts places it in the shell parameter
OPTARG. When an illegal option or a missing option argument is encountered,
a question mark or a colon is placed in name (indicating an illegal
option or missing argument, respectively) and OPTARG is set to the option
character that caused the problem. An error message is also printed to standard error if
optstring doesn't begin with a colon.
When the end of the options is encountered, getopts exits with a nonzero exit
status. Options end at the first (non-option argument) argument that doesn't start with a
-
, or when a -- argument is encountered.
You can reset option parsing by setting OPTIND to 1 (this is done automatically whenever the shell or a shell procedure is invoked).
hash builtin command
hash [-r] [name …]
Without arguments, any hashed executable command pathnames are listed. The -r option causes all hashed commands to be removed from the hash table. If you specify any names, the shell searches for each one as if it were a command name, and adds the name to the hash table if it's an executable command.
jobs builtin command
jobs [-lpn] [job …]
Display
information about the specified jobs; if no jobs are specified, all jobs are displayed. The
-n option causes information to be displayed only for jobs that have
changed state since the last notification. If the -l option is used, the
process ID of each process in a job is also listed. The -p option causes
only the process group of each job to be printed. See Job
control,
below, for the format of job and the displayed
job.
kill builtin command
kill [-s signame | -signum | -signame ] { job | pid | -pgrp } …
Send the
specified signal to the specified jobs, process IDs, or process groups. If no signal is
specified, the signal TERM is sent. If a job is specified, the signal is sent to the job's
process group. See Job control,
below, for the
format of job.
kill -l [exit-status …]
Print the name of the signal that killed a process that exited with the specified exit-statuses. If no arguments are specified, a list of all the signals, their numbers and a short description of them are printed.
This command is also available as an executable; see kill.
let builtin command
let [expr …]
Evaluate each given expression (see
Arithmetic expressions,
above).
If all expressions are successfully evaluated, the exit status is:
- 0 if the last expression evaluated to nonzero
- 1 if the last expression evaluated to zero.
If an error occurs during the parsing or evaluation of an expression, the exit status is greater than 1.
Since expressions may need to be quoted, (( expr )) is syntactic sugar for let "expr".
qon builtin command
qon [-A ability-spec] [-a[d | e]] [-C cpunum] [-c] [-d] [-E] [-e key=value]
[-h] [-L rlimit:cur[:max]] [-p priority[policy]]
[-R runmask] [-s] [-T type]
[-u uid[:gid[,gid,…] | -u user_name]
[-W nsec[:msec]] [-w device] [-Xsched_command]
[command [args]]
The qon utility is a built-in version of the on utility and like on, it runs a command with various options. In various contexts, using qon instead of on can provide a performance benefit. One example is when launching processes with security types when security policies are in place.
Options | Description |
---|---|
-A ability-spec | Configures an ability. For more information, see the on entry in the QNX OS Utility Reference. |
-a[d | e] | Disables or enables address space layout randomization (ASLR) depending on the parameter provided. The -ad option disables ASLR and -ae enables ASLR. If you don't specify either of these options, ASLR is left as it currently is. |
-C cpunum | Sets the processor affinity to cpunum, where the first CPU is 0. You
can use this option multiple times. For more information, see Setting the runmaskin the on entry of the QNX OS Utility Reference. |
-c | Flags a process as a 'critical process.' This flag causes the system to enter its design safe state in the event the process exits or crashes. |
-d | The qon utility returns immediately rather than waiting for the completion of the specified command. |
-E | Clears all environment variables, including any preceding -e options. |
-e key=value | Defines the environment variable key with the value value for the child process. You can specify multiple -e options. |
-h | Starts command in a HELD state. This option is useful for starting up programs with the intention of debugging them. You can also start up several commands in the HELD state, and then send them all a signal to start; they'll all start at almost the exact same time, since their load times will have been eliminated. |
-L rlimit:cur[:max] | Specifies a limit on a system resource for the child process. The arguments are rlimit, cur, and max. The rlimit variable can be either a numeric value or a text-based string and is used to identify the resource limit being set. The cur variable represents a soft limit and can be a numeric value or "inf" for RLIM_INFINITY. The max variable is optional and represents the hard limit; it can be a numeric value or "inf". If a limit is not specified, it maintains its previous value. For more information about the limits, see the entry for setrlimit() in the QNX OS C Library Reference. |
-p priority[policy] | Executes the command at the specified priority, optionally changing the scheduling
policy. The scheduling policy must be one of the following 4 arguments:
f (FIFO), r (round-robin), o
(other) or
s:low_priority:max_repl:repl_period:init_budget
(sporadic scheduling; this scheduling policy requires additional, unique
parameters). For more information, see the on entry in the QNX OS
Utility Reference. |
-R runmask | Sets the processor affinity to runmask. You can use this option
multiple times to specify masks that are more than 32 bits long. For more information,
see Setting the runmaskin the on entry of the QNX OS Utility Reference. |
-s | Spawns the command in a new process group. |
-T type | Runs the command with the given security type. For
more information about security policies, see Security policiesin the System Security Guide. |
-u uid[:gid[,gid,…] | -u user_name | Runs with a different UID and GIDs. These IDs may either be specified as numeric IDs or as a username to be looked up in /etc/passwd. |
-W nsec[:msec] | The number of seconds to wait for the device specified by -w. The default is forever. You can also optionally specify a polling interval, in milliseconds. The default is 100 milliseconds. |
-w device | Waits for a stat() on the given device to
succeed before continuing. If device doesn't contain a slash
(/ ), /dev/ is added to the beginning. |
-Xsched_command | Launches using the specified command for an external scheduler. |
command [args] | Executes the command, and any arguments to be passed to it. |
print builtin command
print [-nprsun | -R [-en]] [argument …]
Print the
arguments on the standard output, separated by spaces, and terminated with a newline. The
-n option suppresses the newline. By default, certain C escapes are
translated. These include \b
, \f
, \n
,
\r
, \t
, \v
, and
\0
### (# is an octal digit, of
which there may be 0 to 3). \c
is equivalent to using the
-n option. You can inhibit backslash expansion by using the
-r option. The -s option prints to the history file
instead of standard output, the -u option prints to file descriptor
n (n defaults to 1 if omitted), and the
-p option prints to the coprocess (see Coprocesses,
above).
The -R option is used to emulate, to some degree, the BSD echo command, which doesn't process \ sequences unless the -e option is given. As above, the -n option suppresses the trailing newline.
pwd builtin command
pwd [-LP]
Print the present working directory.
If -L option is used or if the physical option
(see the set command below) isn't set,
the logical path is printed
(i.e., the path used to cd to the current directory).
If -P option (physical path) is used or if the physical
option is set, the path determined from the filesystem (by following
..
directories to the root directory) is printed.
This command is also available as an executable; see pwd.
read builtin command
read [-prsun] [parameter …]
Read a line of input from
standard input, separate the line into fields using the IFS parameter (see
Substitution,
above), and assign each field
to the specified parameters. If there are more parameters than fields, the extra parameters
are set to null, or alternatively, if there are more fields than parameters, the last
parameter is assigned the remaining fields (inclusive of any separating spaces). If no
parameters are specified, the REPLY parameter is used. If the input-line ends
in a backslash and the -r option wasn't used, the backslash and newline are
stripped and more input is read. If no input is read, read exits with a
nonzero status.
The first parameter may have a question mark and a string appended to it, in which case the string is used as a prompt (printed to standard error before any input is read) if the input is a tty (e.g., read nfoo?'number of foos: ').
The -un and -p options cause input to be
read from file descriptor n or the current coprocess (see Coprocesses,
above, for comments on this),
respectively. If the -s option is used, input is saved to the history
file.
readonly builtin command
readonly [-p] [parameter[=value]] …
Set the readonly attribute of the named parameters. If values are given, parameters are set to them before setting the attribute. Once a parameter is made readonly, it can't be unset and its value can't be changed.
If no parameters are specified, the names of all parameters with the readonly attribute are printed one per line, unless the -p option is used, in which case readonly commands defining all readonly parameters, including their values, are printed.
return builtin command
return [status]
Return
from a function or .
script, with exit status status. If
no status is given, the exit status of the last executed command is used.
If used outside of a function or .
script, it has the same effect as exit. Note that ksh treats
both profile and $ENV files as .
scripts, while the
original Korn shell only treats profiles as .
scripts.
set builtin command
set [+-abCefhiklmnprsuvxX] [+-o [option]] [+-A name] [--] [arg …]
You can use the set command to set
(-
) or clear (+
) shell options, set the positional
parameters, or set an array parameter. You can change options by using the
+-o
option syntax, where option is the long name of an
option, or by using the +-letter syntax, where
letter is the option's single letter name (not all options have a
single letter name). The following table lists both option letters (if they exist) and long
names along with a description of what the option does.
Letter | Long name | Description |
---|---|---|
-A | Sets the elements of the array parameter name to arg …; if -A is used, the array is reset (i.e., emptied) first; if +A is used, the first N elements are set (where N is the number of args), the rest are left untouched. | |
-a | allexport | All new parameters are created with the export attribute. |
-b | notify | Print job notification messages asynchronously, instead of just before the prompt. Used only if job control is enabled (-m). |
-C | noclobber | Prevent > redirection from overwriting existing files (you must use
>| to force an overwrite). |
-e | errexit | Exit (after executing the ERR trap) as soon as an error occurs or a command
fails (i.e., exits with a nonzero status). This doesn't apply to commands whose exit
status is explicitly tested by a shell construct such as if,
until, while, && or
|| statements. |
-f | noglob | Don't expand filename patterns. |
-h | trackall | Create tracked aliases for all executed commands (see Aliases,above). On by default for noninteractive shells. |
-i | interactive | Enable interactive mode—this can only be set/unset when the shell is invoked. |
-k | keyword | Parameter assignments are recognized anywhere in a command. |
-l | login | The shell is a login shell—this can only be set/unset when the shell is invoked (see
Shell startup,above). |
-m | monitor | Enable job control (default for interactive shells). |
-n | noexec | Don't execute any commands—useful for checking the syntax of scripts (ignored if interactive). |
-p | privileged | Set automatically if, when the shell starts, the read uid or gid doesn't match the
effective uid or gid, respectively. See Shell startup,above for a description of what this means. |
-r | restricted | Enable restricted mode—this option can only be used when the shell is invoked. See
Shell startup,above for a description of what this means. |
-s | stdin | If used when the shell is invoked, commands are read from standard input. Set automatically
if the shell is invoked with no arguments. When -s is used in the set command, it causes the specified arguments to be sorted before assigning them to the positional parameters (or to array name, if -A is used). |
-u | nounset | Referencing of an unset parameter is treated as an error, unless
one of the - , + or = modifiers is used.
|
-v | verbose | Write shell input to standard error as it's read. |
-x | xtrace | Print commands and parameter assignments when they are executed, preceded by the value of PS4. |
-X | markdirs | Mark directories with a trailing / during filename generation. |
bgnice | Background jobs are run with lower priority. | |
braceexpand | Enable brace expansion (also known as alternation). | |
emacs | Enable BRL emacs-like command line editing (interactive shells only);
see emacs interactive input-line editing. |
|
gmacs | Enable gmacs-like (Gosling emacs) command line editing (interactive shells only); currently identical to emacs editing except that transpose ( Ctrl T ) acts slightly differently. | |
ignoreeof | The shell won't exit on when end-of-file is read; you have to use exit. | |
nohup | Don't kill running jobs with a SIGHUP signal when a login shell exists. Currently set by default, but this will change in the future to be compatible with the original Korn shell (which doesn't have this option, but does send the SIGHUP signal). | |
nolog | No effect—in the original Korn shell, this prevents function definitions from being stored in the history file. | |
physical | Causes the cd and pwd commands to use physical (i.e., the filesystem's)
.. directories instead of logical directories (i.e., the shell
handles .. , which allows the user to be oblivious of symlink links
to directories). Clear by default. Note that setting this option doesn't effect the
current value of the PWD parameter; only the cd
command changes PWD. See the cd and
pwd commands above for more details. |
|
posix | Enable POSIX mode. See POSIX mode,above. |
These options can also be used upon invocation of the shell. You can find the current set of
options (with single letter names) in the parameter -
. The set
-o command with no option name lists all the options and whether each is on or
off; set +o prints the long names of all options that are currently
on.
Remaining arguments, if any, are positional parameters and are assigned, in order, to the
positional parameters (i.e., 1, 2, and so on). If options are ended with --
and there are no remaining arguments, all positional parameters are cleared. If no options
or arguments are given, then the values of all names are printed. For unknown historical
reasons, a lone -
option is treated specially: it clears both the
-x and -v options.
shift builtin command
shift [number]
The positional parameters number+1, number+2 … are renamed to 1, 2, and so on. The number defaults to 1.
test builtin command
test expression
or:
[ expression ]
Evaluate the expression and return zero status if true, and 1 status if false and greater than 1 if there was an error. It's normally used as the condition command of if and while statements.
The following basic expressions are available:
- str
- The str has nonzero length. Note that there is the potential for problems if
str turns out to be an operator (e.g.,
-r)—it's generally better to use a test like:
[ X"str" != X ]
instead (double quotes are used in case str contains spaces or file globing characters).
- -r file
- The file exists and is readable.
- -w file
- The file exists and is writable.
- -x file
- The file exists and is executable.
- -a file
- The file exists.
- -e file
- The file exists.
- -f file
- The file is a regular file.
- -d file
- The file is a directory.
- -c file
- The file is a character special device.
- -b file
- The file is a block special device.
- -p file
- The file is a named pipe.
- -u file
- The file's mode has setuid bit set.
- -g file
- The file's mode has setgid bit set.
- -k file
- The file's mode has sticky bit set.
- -s file
- The file isn't empty.
- -O file
- The file's owner is the shell's effective user-ID.
- -G file
- The file's group is the shell's effective group-ID.
- -h file
- The file is a symbolic link.
- -H file
- The file is a context-dependent directory (useful only on HP-UX).
- -L file
- The file is a symbolic link. This is the same as -h.
- -S file
- The file is a socket.
- -o option
- The shell option is set (see the set command above for list of options). As a nonstandard
extension, if the option starts with a
!
, the test is negated; the test always fails if option doesn't exist (thus:[ -o foo -o -o !foo ]
returns true if and only if option foo exists).
- file -nt file
- The first file is newer than the second file.
- file -ot file
- The first file is older than the second file.
- file -ef file
- The first file is the same file as the second file.
- -t [fd]
- The file descriptor is a tty device. If the posix option (set -o
posix, see
POSIX mode,
above) isn't set, you can leave out the fd, in which case it's taken to be 1 (the behavior differs due to the special POSIX rules described below). - string
- The string isn't empty.
- -z string
- The string is empty.
- -n string
- The string isn't empty.
- string = string
- The strings are equal.
- string == string
- The strings are equal.
- string != string
- The strings aren't equal.
- number -eq number
- The numbers are equal.
- number -ne number
- The numbers aren't equal.
- number -ge number
- The first number is greater than or equal to the second.
- number -gt number
- The first number is greater than the second.
- number -le number
- The first number is less than or equal to the second.
- number -lt number
- The first number is less than the second.
You can combine the above basic expressions, in which unary operators have precedence over binary operators, with the following operators (listed in increasing order of precedence):
- expr -o expr
- Logical OR.
- expr -a expr
- Logical AND.
- ! expr
- Logical not.
- ( expr )
- Grouping.
On operating systems not supporting /dev/fd/n devices (where n is a file descriptor number), the test command attempts to fake it for all tests that operate on files (except the -e test). That is, [ -w /dev/fd/2 ] tests if file descriptor 2 is writable.
Note that some special rules are applied (courtesy of POSIX) if the number of arguments to
test or [ … ] is less than five: if leading
!
arguments can be stripped such that only one argument remains, then a
string length test is performed (again, even if the argument is a unary operator); if
leading !
arguments can be stripped such that three arguments remain and
the second argument is a binary operator, then the binary operation is performed (even if
first argument is a unary operator, including an unstripped !
).
!
or -n. Use tests like
if [ "X$foo" = Xbar ] instead.times builtin command
times
Print the accumulated user and system times used by the shell and by processes which have exited that the shell started.
trap builtin command
trap [handler signal …]
Set the trap handler that's to be executed when any of the specified signals are received.
The handler is either a null string, indicating the signals are to be ignored,
a minus (-
), indicating that the default action is to be taken for the
signals (see signal()), or a string containing shell commands to be
evaluated and executed at the first opportunity (i.e., when the current command completes,
or before printing the next PS1 prompt) after receipt of one of the
signals.
The signal is the name of a signal (e.g., SIGPIPE or SIGALRM) or the number of the signal (see the kill -l command above). There are two special signals:
- EXIT (also known as 0), which is executed when the shell is about to exit.
- ERR which is executed after an error occurs (an error is something that causes the shell to exit if the -e or errexit option is set—see the set command above).
EXIT handlers are executed in the environment of the last executed command. Note that for noninteractive shells, the trap handler can't be changed for signals that were ignored when the shell started.
With no arguments, trap lists, as a series of trap commands, the current state of the traps that have been set since the shell started.
true builtin command
true
A command that exits with a zero value.
This command is also available as an executable; see true.
typeset builtin command
typeset [[+-Ulprtux] [-L[n]] [-R[n]] [-Z[n]]
[-i[n]] | -f [-tux]] [name[=value] …]
Display
or set parameter attributes. With no name arguments, parameter attributes
are displayed: if no options are used, the current attributes of all parameters are printed
as typeset commands; if an option is given (or -
with no
option letter) all parameters and their values with the specified attributes are printed; if
options are introduced with +
, parameter values aren't printed.
If name arguments are given, the attributes of the named parameters are set
(-
) or cleared (+
). Values for parameters may optionally
be specified. If typeset is used inside a function, any newly created
parameters are local to the function.
When -f is used, typeset operates on the attributes of
functions. As with parameters, if no names are given, functions are
listed with their values (i.e., definitions) unless options are introduced with
+
, in which case only the function names are reported.
The options are:
- -Ln
- Left justify attribute: n specifies the field width. If n isn't specified, the current width of a parameter (or the width of its first assigned value) is used. Leading white space (and zeros, if used with the -Z option) is stripped. If necessary, values are either truncated or space padded to fit the field width.
- -Rn
- Right justify attribute: n specifies the field width. If n isn't specified, the current width of a parameter (or the width of its first assigned value) is used. Trailing white space are stripped. If necessary, values are either stripped of leading characters or space padded to make them fit the field width.
- -Zn
- Zero fill attribute: if not combined with -L, this is the same as -R, except zero padding is used instead of space padding.
- -in
- Integer attribute: n specifies the base to use when displaying the integer (if not specified, the base given in the first assignment is used). You can use arithmetic expressions to assign values to parameters that have this attribute.
- -U
- Unsigned integer attribute: integers are printed as unsigned values (useful only when combined with the -i option). This option isn't in the original Korn shell.
- -f
- Function mode: display or set functions and their attributes, instead of parameters.
- -l
- Lower case attribute: all upper case characters in values are converted to lower case. (In the
original Korn shell, this parameter meant
long integer
when used with the -i option). - -p
- Print complete typeset commands that you can use to recreate the attributes (but not the values) of parameters. This is the default action (option exists for ksh93 compatibility).
- -r
- Readonly attribute: parameters with the this attribute may not be assigned to or unset. Once this attribute is set, it can not be turned off.
- -t
- Tag attribute: has no meaning to the shell; provided for application use.
For functions, -t is the trace attribute. When functions with the trace attribute are executed, the xtrace (-x) shell option is temporarily turned on.
- -u
- Upper case attribute: all lower case characters in values are converted to upper case. (In the
original Korn shell, this parameter meant
unsigned integer
when used with the -i option, which meant uppercase letters would never be used for bases greater than 10. See the -U option).For functions, -u is the undefined attribute. See
Functions,
above for the implications of this. - -x
- Export attribute: parameters (or functions) are placed in the environment of any executed commands. Exported functions aren't implemented yet.
ulimit builtin command
ulimit [-acdfHlmnpsStv] [value]
Display or set process limits.
If no options are used, the file size limit (-f) is assumed.
The value, if specified, may be either be an arithmetic expression
or the word unlimited
.
The limits affect the shell and any processes created by the shell after they're imposed.
The options are:
Option | Description | Resource |
---|---|---|
-a | Display all limits; unless -H is used, soft limits are displayed. | — |
-H | Set the hard limit only (default is to set both hard and soft limits). | — |
-S | Set the soft limit only (default is to set both hard and soft limits). | — |
-c | Impose a size limit of n blocks on the size of core dumps. | RLIMIT_CORE |
-d | Impose a size limit of n kilobytes on the size of the data area. | RLIMIT_DATA |
-f | Impose a size limit of n blocks on files written by the shell and its child processes (files of any size may be read). QNX OS currently doesn't support this limit. | — |
-l | Impose a limit of n kilobytes on the amount of locked (wired) physical memory. QNX OS currently doesn't support this limit. | — |
-m | Impose a limit of n kilobytes on the amount of physical memory used. | RLIMIT_RSS |
-n | Impose a limit of n file descriptors that can be open at once. | RLIMIT_NOFILE |
-p | Impose a limit of n processes that can be run by the user at any one time. | RLIMIT_NPROC |
-s | Impose a size limit of n kilobytes on the size of the stack area. | RLIMIT_STACK |
-t | Impose a time limit of n cpu seconds to be used by each process. | RLIMIT_CPU |
-v | Impose a limit of n kilobytes on the amount of virtual memory used. | RLIMIT_VMEM |
For more information about the resources, see setrlimit() in the C Library Reference.
umask builtin command
umask [-S] [mask]
Display or set the file permission creation mask, or umask (see umask). If the -S option is used, the mask displayed or set is symbolic, otherwise it's an octal number.
This command is also available as an executable; see umask.
Symbolic masks are like those used by chmod:
[ugoa]{{=+-}{rwx}*}+[,…]
in which the first group of characters is the who part, the second group is the op part, and the last group is the perm part. The who part specifies which part of the umask is to be modified. The letters mean:
u
- The user permissions.
g
- The group permissions.
o
- The other permissions (nonuser, nongroup).
a
- All permissions (user, group and other).
The op part indicates how the who permissions are to be modified:
=
- Set.
+
- Added to.
-
- Removed from.
The perm part specifies which permissions are to be set, added or removed:
r
- Read permission.
w
- Write permission.
x
- Execute permission.
When symbolic masks are used, they describe what permissions may be made available (as opposed to
octal masks in which a set bit means the corresponding bit is to be cleared). For example,
ug=rwx,o=
sets the mask so files won't be readable, writable or
executable by others
, and is equivalent (on most systems) to the octal mask
07
.
unalias builtin command
unalias [-adt] [name …]
Remove the aliases for the given names. If the -a option is used, all aliases are removed. If the -t or -d option is used, the indicated operations are carried out on tracked or directory aliases, respectively.
unset builtin command
unset [-fv] parameter …
Unset the named parameters (-v, the default) or functions (-f). The exit status is nonzero if any of the parameters were already unset, zero otherwise.
wait builtin command
wait [job]
Wait for the
specified job(s) to finish. The exit status of wait is that of the last
specified job: if the last job is killed by a signal, the exit status is 128 + the number of
the signal (see kill -l
exit-status above); if the last specified job can't be found
(because it never existed, or had already finished), the exit status of wait is 127. See
Job control,
below, for the format of
job. The wait command returns if a signal for which
a trap has been set is received, or if a SIGHUP, SIGINT or
SIGQUIT signal is received.
If no jobs are specified, wait waits for all currently running jobs (if any) to finish and exits with a zero status. If job monitoring is enabled, the completion status of jobs is printed (this isn't the case when jobs are explicitly specified).
whence builtin command
whence [-pv] [name …]
For each name, the type of command is listed (reserved word, builtin, alias, function, tracked alias or executable). If the -p option is used, a path search is done even if name is a reserved word, alias, and so on. Without the -v option, whence is similar to command -v except that whence finds reserved words and doesn't print aliases as alias commands; with the -v option, whence is the same as command -V. Note that for whence, the -p option doesn't affect the search path used, as it does for command. If the type of one or more of the names couldn't be determined, the exit status is nonzero.
Job control
Job control refers to the shell's ability to monitor and control jobs, which are processes or groups of processes created for commands or pipelines. At a minimum, the shell keeps track of the status of the background (i.e., asynchronous) jobs that currently exist; you can display this information by using the jobs command. If job control is fully enabled (using set -m or set -o monitor), as it is for interactive shells, the processes of a job are placed in their own process group, you can stop foreground jobs by typing the suspend character from the terminal (normally Ctrl Z ), you can restart jobs in either the foreground or background, using the fg and bg commands, and the state of the terminal is saved or restored when a foreground job is stopped or restarted.
Note that you can stop only commands that create processes (e.g., asynchronous commands, subshell commands, and nonbuiltin, nonfunction commands); you can't stop commands such as read.
When a job is created, it's assigned a job number. For interactive shells, this number is printed
inside […]
, followed by the process IDs of the processes in the job
when an asynchronous command is run. You can refer to a job in the bg,
fg, jobs, kill and wait commands either by the process ID of the last process in
the command pipeline (as stored in the $! parameter) or by prefixing the
job number with a percent sign (%
). You can also use other percent
sequences to refer to jobs:
%+
- The most recently stopped job, or, if there are no stopped jobs, the oldest running job.
%%
,%
- Same as
%
. %-
- The job that would be the
%+
job, if the latter didn't exist. %
n- The job with job number n.
%?
string- The job containing the string string (an error occurs if multiple jobs are matched).
%
string- The job starting with string string (an error occurs if multiple jobs are matched).
When a job changes state (e.g., a background job finishes or foreground job is stopped), the shell prints the following status information:
[number] flag status command
The fields are:
- number
- The job number of the job.
- flag
+
or-
if the job is the%+
or%-
job, respectively, or space if it's neither.- status
- The current state of the job:
Running
- The job has neither stopped or exited (note that running doesn't necessarily mean consuming CPU time—the process could be blocked waiting for some event).
Done
[(number)]- The job exited. The number is the exit status of the job, which is omitted if the status is zero.
Stopped
[(signal)]- The job was stopped by the indicated signal (if no signal is given, the job was stopped by SIGTSTP).
- signal-description [
(core dumped)
] - The job was killed by a signal (e.g., Memory fault, Hangup, and so on—use
kill -l for a list of signal
descriptions). The
(core dumped)
message indicates the process created a core file.
- command
- The command that created the process. If there are multiple processes in the job, then each process has a line showing its command and possibly its status, if it's different from the status of the previous process.
When an attempt is made to exit the shell while there are jobs in the stopped state, the shell warns the user that there are stopped jobs and doesn't exit. If another attempt is immediately made to exit the shell, the stopped jobs are sent a SIGHUP signal and the shell exits. Similarly, if the nohup option isn't set and there are running jobs when an attempt is made to exit a login shell, the shell warns the user and doesn't exit. If another attempt is immediately made to exit the shell, the running jobs are sent a SIGHUP signal and the shell exits.
emacs interactive input-line editing
When the emacs option is set, interactive input-line editing is enabled.
In this mode, various editing commands (typically bound to one or more control characters) cause immediate actions without waiting for a new-line. Several editing commands are bound to particular control characters when the shell is invoked; you can use the following commands to change these bindings:
- bind
- The current bindings are listed.
- bind string
=
[editing-command] - Bind the specified editing command to the given string, which should consist
of a control character (which you can write using caret notation
^
X), optionally preceded by one of the two prefix characters.After invoking the bind command, typing the string causes the editing command to be immediately invoked. Note that although only two prefix characters (usually ESC and Ctrl X ) are supported, some multicharacter sequences can be supported. The following binds the arrow keys on an ANSI terminal, or xterm (these are in the default bindings). Of course some escape sequences won't work out quite this nicely:
bind '^[['=prefix-2 bind '^XA'=up-history bind '^XB'=down-history bind '^XC'=forward-char bind '^XD'=backward-char
- bind -l
- List the names of the functions to which keys may be bound.
- bind -m string
=
[substitute] - The specified input string is afterward immediately replaced by the given substitute string, which may contain editing commands.
The editing commands are listed below. Each description starts with the name of the command, a
n (if you can prefix the command with a count), and any keys the
command is bound to by default (written using caret notation, e.g., ASCII ESC character is
written as ^[
). You can enter a count prefix for a command by using the
sequence ^[
n, where n is a sequence
of 1 or more digits; unless otherwise specified, if a count is omitted, it defaults to 1.
Note that editing command names are used only with the bind command.
Furthermore, many editing commands are useful only on terminals with a visible cursor. The
default bindings were chosen to resemble corresponding emacs key
bindings. The user's tty characters (e.g., ERASE) are bound to reasonable substitutes and
override the default bindings.
- abort
- Key binding:
^G
Useful as a response to a request for a search-history pattern in order to abort the search.
- auto-insert n
- Key binding: none
Simply causes the character to appear as literal input. Most ordinary characters are bound to this.
- backward-char n
- Key binding:
^B
Moves the cursor backward n characters.
- backward-word n
- Key binding:
^[B
Moves the cursor backward to the beginning of a word; words consist of alphanumerics, underscore (
_
) and dollar ($
). - beginning-of-history
- Key binding:
^[<
Moves to the beginning of the history.
- beginning-of-line
- Key binding:
^A
Moves the cursor to the beginning of the edited input line.
- capitalize-word n
- Key binding:
^[c
or^[C
Uppercase the first character in the next n words, leaving the cursor past the end of the last word.
If the current line doesn't begin with a comment character, one is added at the beginning of the line and the line is entered (as if return had been pressed), otherwise the existing comment characters are removed and the cursor is placed at the beginning of the line.
- complete
- Key binding:
^[^[
or^I
Automatically completes as much as is unique of the command name or the filename containing the cursor. If the entire remaining command or filename is unique, a space is printed after its completion, unless it's a directory name, in which case
/
is appended. If there is no command or filename with the current partial word as its prefix, a bell character is output (usually causing a audio beep). - complete-command
- Key binding:
^X^[
Automatically completes as much as is unique of the command name having the partial word up to the cursor as its prefix, as in the complete command described above.
- complete-file
- Key binding:
^[^X
Automatically completes as much as is unique of the filename having the partial word up to the cursor as its prefix, as in the complete command described above.
- complete-list
- Key binding:
^[=
List the possible completions for the current word.
- delete-char-backward n
- Key binding:
ERASE
,^?
,^H
Deletes n characters before the cursor.
- delete-char-forward n
- Key binding: none
Deletes n characters after the cursor.
- delete-word-backward n
- Key binding:
^[ERASE
,^[^?
,^[^H
,^[h
Deletes n words before the cursor.
- delete-word-forward n
- Key binding:
^[d
Deletes characters after the cursor up to the end of n words.
- down-history n
- Key binding:
^N
Scrolls the history buffer forward n lines (later). Each input line originally starts just after the last entry in the history buffer, so down-history isn't useful until either search-history or up-history has been performed.
- downcase-word n
- Key binding:
^[L
,^[l
Lowercases the next n words.
- end-of-history
- Key binding:
^[>
Moves to the end of the history.
- end-of-line
- Key binding:
^E
Moves the cursor to the end of the input line.
- eot
- Key binding:
^_
Acts as an end-of-file; this is useful because edit-mode input disables normal terminal input canonicalization.
- eot-or-delete n
- Key binding:
^D
Acts as eot if alone on a line; otherwise acts as delete-char-forward.
- error
- Key binding: none
Error (ring the bell).
- exchange-point-and-mark
- Key binding:
^X^X
Places the cursor where the mark is, and sets the mark to where the cursor was.
- expand-file
- Key binding:
^[*
Appends a
*
to the current word and replaces the word with the result of performing file globbing on the word. If no files match the pattern, the bell is rung. - forward-char n
- Key binding:
^F
Moves the cursor forward n characters.
- forward-word n
- Key binding:
^[f
Moves the cursor forward to the end of the nth word.
- goto-history n
- Key binding:
^[g
Goes to history number n.
- kill-line
- Key binding:
KILL
Deletes the entire input line.
- kill-region
- Key binding:
^W
Deletes the input between the cursor and the mark.
- kill-to-eol n
- Key binding:
^K
Deletes the input from the cursor to the end of the line if n is not specified, otherwise deletes characters between the cursor and column n.
- list
- Key binding:
^[?
Prints a sorted, columnated list of command names or filenames (if any) that can complete the partial word containing the cursor. Directory names have
/
appended to them. - list-command
- Key binding:
^X?
Prints a sorted, columnated list of command names (if any) that can complete the partial word containing the cursor.
- list-file
- Key binding:
^X^Y
Prints a sorted, columnated list of filenames (if any) that can complete the partial word containing the cursor. File type indicators are appended as described under list above.
- newline
- Key binding:
^J
,^M
Causes the current input line to be processed by the shell. The current cursor position may be anywhere on the line.
- newline-and-next
- Key binding:
^O
Causes the current input line to be processed by the shell, and the next line from history becomes the current line. This is useful only after an up-history or search-history.
- no-op
- Key binding:
QUIT
This does nothing.
- prefix-1
- Key binding:
^[
Introduces a 2-character command sequence.
- prefix-2
- Key binding:
^X
,^[[
Introduces a 2-character command sequence.
- prev-hist-word n
- Key binding:
^[.
,^[_
The last (nth) word of the previous command is inserted at the cursor.
- quote
- Key binding:
^^
The following character is taken literally rather than as an editing command.
- redraw
- Key binding:
^L
Reprints the prompt string and the current input line.
- search-character-backward n
- Key binding:
^[^]
Search backward in the current line for the nth occurrence of the next character typed.
- search-character-forward n
- Key binding:
^]
Search forward in the current line for the nth occurrence of the next character typed.
- search-history
- Key binding:
^R
Enter incremental search mode. The internal history list is searched backwards for commands matching the input. An initial
^
in the search string anchors the search. The abort key leaves search mode. Other commands are executed after leaving search mode. Successive search-history commands continue searching backward to the next previous occurrence of the pattern. The history buffer retains only a finite number of lines; the oldest are discarded as necessary. - set-mark-command
- Key binding:
^[
SpaceSet the mark at the cursor position.
- stuff
- Key binding: none
On systems supporting it, pushes the bound character back onto the terminal input where it may receive special processing by the terminal handler. This is useful for the BRL
^T
mini-systat feature, for example. - stuff-reset
- Key binding: none
Acts like stuff, then aborts input the same as an interrupt.
- transpose-chars
- Key binding:
^T
If at the end of line, or if the gmacs option is set, this exchanges the two previous characters; otherwise, it exchanges the previous and current characters and moves the cursor one character to the right.
- up-history n
- Key binding:
^P
Scrolls the history buffer backward n lines (earlier).
- upcase-word n
- Key binding:
^[U
,^[u
Uppercases the next n words.
- version
- Key binding:
^V
Display the version of ksh. The current edit buffer is restored as soon as any key is pressed (the key is then processed, unless it's a space).
- yank
- Key binding:
^Y
Inserts the most recently killed text string at the current cursor position.
- yank-pop
- Key binding:
^[y
Immediately after a yank, replaces the inserted text string with the next previous killed text string.
See also:
- The Korn Shell Command and Programming Language, Morris Bolsky and David Korn, 1989, ISBN 0-13-516972-0.
- UNIX Shell Programming, Stephen G. Kochan, Patrick H. Wood, Hayden.
- IEEE Standard for Information Technology—Portable Operating System Interface (POSIX)—Part 2: Shell and Utilities, IEEE Inc, 1993, ISBN 1-55937-255-9.
Files:
- ~/.profile
- /etc/profile
- /etc/suid_profile
Contributing author:
This shell is based on the public domain 7th edition Bourne shell clone by Charles Forsyth and parts of the BRL shell by Doug A. Gwyn, Doug Kingston, Ron Natalie, Arnold Robbins, Lou Salkind and others. The first release of pdksh was created by Eric Gisin, and it was subsequently maintained by John R. MacMillan (chance!john@sq.sq.com), and Simon J. Gerraty (sjg@zen.void.oz.au). The current maintainer is Michael Rendell (michael@cs.mun.ca). The CONTRIBUTORS file in the source distribution contains a more complete list of people and their part in the shell's development.
Report any bugs in ksh to pdksh@cs.mun.ca. Please include the version of ksh (echo $KSH_VERSION shows it), the machine, operating system and compiler you are using and a description of how to repeat the bug (a small shell script that demonstrates the bug is best). The following, if relevant (if you aren't sure, include them), can also helpful: options you are using (both options.h options and set -o options) and a copy of your config.h (the file generated by the configure script). You can get new versions of ksh from ftp.cs.mun.ca:pub/pdksh/.