/usr/xpg4/bin/sh [ +-abCefhikmnoprstuvx ] [ +-o option ] ... [ -c string ] [ arg... ]
/usr/bin/rksh [ +-abCefhikmnoprstuvx ] [ +-o option ] ... [ -c string ] [ arg... ]
; & ( ) | < > NEWLINE SPACE TAB
A blank is a TAB or a SPACE. An identifier is a sequence of letters, digits, or underscores starting with a letter or underscore. Identifiers are used as names for functions and variables. A word is a sequence of characters separated by one or more non-quoted metacharacters.
A command is a sequence of characters in the syntax of the shell language. The shell reads each command and carries out the desired action either directly or by invoking separate utilities. A special-command is a command that is carried out by the shell without creating a separate process. Except for documented side effects, most special commands can be implemented as separate utilities.
A pipeline is a sequence of one or more commands separated by |. The standard output of each command but the last is connected by a pipe(2) to the standard input of the next command. Each command is run as a separate process; the shell waits for the last command to terminate. The exit status of a pipeline is the exit status of the last command.
A list is a sequence of one or more pipelines separated by ;, &, &&, or ||, and optionally terminated by ;, &, or |&. Of these five symbols, ;, &, and |& have equal precedence, which is lower than that of && and ||. The symbols && and || also have equal precedence. A semicolon (;) causes sequential execution of the preceding pipeline; an ampersand (&) causes asynchronous execution of the preceding pipeline (that is, the shell does not wait for that pipeline to finish). The symbol |& causes asynchronous execution of the preceding command or pipeline with a two-way pipe established to the parent shell.
The standard input and output of the spawned command can be written to and read from by the parent shell using the -p option of the special commands read and print described in Special Commands. The symbol && (||) causes the list following it to be executed only if the preceding pipeline returns 0 (or a non-zero) value. An arbitrary number of new-lines may appear in a list, instead of a semicolon, to delimit a command.
A command is either a simple-command or one of the following. Unless otherwise stated, the value returned by a command is that of the last simple-command executed in the command.
if list ; then list ;
The following reserved words are only recognized as the first word of a command and when not quoted:
! if then else elif fi case esac for while until do done { } function select time [[ ]]
Aliasing is performed when scripts are read, not while they are executed. Therefore, for an alias to take effect the alias definition command has to be executed before the command which references the alias is read.
Aliases are frequently used as a short hand for full path names. An option to the aliasing facility allows the value of the alias to be automatically set to the full pathname of the corresponding command. These aliases are called tracked aliases. The value of a tracked alias is defined the first time the corresponding command is looked up and becomes undefined each time the PATH variable is reset. These aliases remain tracked so that the next subsequent reference will redefine the value. Several tracked aliases are compiled into the shell. The -h option of the set command makes each referenced command name into a tracked alias.
The following exported aliases are compiled into (and built-in to) the shell but can be unset or redefined:
autoload=fmtypeset -fufm
false=fmlet 0fm
functions=fmtypeset -ffm
hash=fmalias -tfm
history=fmfc -lfm
integer=fmtypeset -ifm
nohup=fmnohup fm
r=fmfc -e -fm
true=fm:fm
type=fmwhence -vfm
An example concerning trailing blank characters and reserved words follows. If the user types:
$ alias foo="/bin/ls "
$ alias while="/"
The effect of executing:
$ while true
> do
> echo "Hello, World"
> done
is a never-ending sequence of Hello, World strings to the screen. However, if the user types:
$ foo while
the result will be an ls listing of /. Since the alias substitution for foo ends in a space character, the next word is checked for alias substitution. The next word, while, has also been aliased, so it is substituted as well. Since it is not in the proper position as a command word, it is not recognized as a reserved word.
If the user types:
$ foo; while
while retains its normal reserved-word properties.
In addition, tilde substitution is attempted when the value of a variable assignment begins with a ~.
A tilde-prefix consists of an unquoted tilde character at the beginning of a word, followed by all of the characters preceding the first unquoted slash in the word, or all the characters in the word if there is no slash. In an assignment, multiple tilde-prefixes can be used: at the beginning of the word (that is, following the equal sign of the assignment), following any unquoted colon or both. A tilde-prefix in an assignment is terminated by the first unquoted colon or slash. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name from the user database.
A portable login name cannot contain characters outside the set given in the description of the LOGNAME environment variable. If the login name is null (that is, the tilde-prefix contains only the tilde), the tilde-prefix will be replaced by the value of the variable HOME . If HOME is unset, the results are unspecified. Otherwise, the tilde-prefix will be replaced by a pathname of the home directory associated with the login name obtained using the getpwnam function. If the system does not recognize the login name, the results are undefined.
Tilde expansion generally occurs only at the beginning of words, but an exception based on historical practice has been included:
PATH =/posix/bin:~dgk/bin
is eligible for tilde expansion because tilde follows a colon and none of the relevant characters is quoted. Consideration was given to prohibiting this behavior because any of the following are reasonable substitutes:
PATH =$(printf %s ~karels/bin : ~bostic/bin)
for Dir in ~maart/bin ~srb/bin ...
do
PATH =${PATH :+$PATH :}$Dir
done
With the first command, explicit colons are used for each directory. In all cases, the shell performs tilde expansion on each directory because all are separate words to the shell.
Note that expressions in operands such as:
make -k mumble LIBDIR =~chet/lib
do not qualify as shell variable assignments and tilde expansion is not performed (unless the command does so itself, which make does not).
The special sequence $~ has been designated for future implementations to evaluate as a means of forcing tilde expansion in any word.
Because of the requirement that the word not be quoted, the following are not equivalent; only the last will cause tilde expansion:
\~hlj/ ~h\lj/ ~"hlj"/ ~hlj\/ ~hlj/
The results of giving tilde with an unknown login name are undefined because the KornShell ~+ and ~- constructs make use of this condition, but, in general it is an error to give an incorrect login name with tilde. The results of having HOME unset are unspecified because some historical shells treat this as an error.
Command substitution allows the output of a command to be substituted in place of the command name itself. Command substitution occurs when the command is enclosed as follows:
$(command)
or (backquoted version):
‘command‘
The shell will expand the command substitution by executing command in a subshell environment and replacing the command substitution (the text of command plus the enclosing $( ) or backquotes) with the standard output of the command, removing sequences of one or more newline characters at the end of the substitution. Embedded newline characters before the end of the output will not be removed; however, they may be treated as field delimiters and eliminated during field splitting, depending on the value of IFS and quoting that is in effect.
Within the backquoted style of command substitution, backslash shall retain its literal meaning, except when followed by:
$ ‘ \
(dollar-sign, backquote, backslash). The search for the matching backquote is satisfied by the first backquote found without a preceding backslash; during this search, if a non-escaped backquote is encountered within a shell comment, a here-document, an embedded command substitution of the $(command) form, or a quoted string, undefined results occur. A single- or double-quoted string that begins, but does not end, within the ‘...‘ sequence produces undefined results.
With the $(command) form, all characters following the open parenthesis to the matching closing parenthesis constitute the command. Any valid shell script can be used for command, except:
The results of command substitution will not be field splitting and pathname expansion processed for further tilde expansion, parameter expansion, command substitution or arithmetic expansion. If a command substitution occurs inside double-quotes, it will not be performed on the results of the substitution.
Command substitution can be nested. To specify nesting within the backquoted version, the application must precede the inner backquotes with backslashes; for example:
‘\‘command\‘‘
The $( ) form of command substitution solves a problem of inconsistent behavior when using backquotes. For example:
Command | Output |
echo ’\$x’ | \$x |
echo ‘echo ’\$x’‘ | $x |
echo $(echo ’\$x’) | \$x |
Additionally, the backquoted syntax has historical restrictions on the contents of the embedded command. While the new $( ) form can process any kind of valid embedded script, the backquoted form cannot handle some valid scripts that include backquotes. For example, these otherwise valid embedded scripts do not work in the left column, but do work on the right:
echo ‘ | echo $( |
cat <<eeof | cat <<eeof |
a here-doc with ‘ | a here-doc with ) |
eof | eof |
‘ | ) |
echo ‘ | echo $( |
echo abc # a comment with ‘ | echo abc # a comment with ) |
‘ | ) |
echo ‘ | echo $( |
echo ’‘’ | echo ’)’ |
‘ | ) |
Because of these inconsistent behaviors, the backquoted variety of command substitution is not recommended for new applications that nest command substitutions or attempt to embed complex scripts.
If the command substitution consists of a single subshell, such as:
$( (command) )
a portable application must separate the $( and ( into two tokens (that is, separate them with white space). This is required to avoid any ambiguities with arithmetic expansion.
$((expression))
The expression is treated as if it were in double-quotes, except that a double-quote inside the expression is not treated specially. The shell will expand all tokens in the expression for parameter expansion, command substitution and quote removal.
Next, the shell will treat this as an arithmetic expression and substitute the value of the expression. The arithmetic expression will be processed according to the rules of the ISO C with the following exceptions:
As an extension, the shell may recognize arithmetic expressions beyond those listed. If the expression is invalid, the expansion will fail and the shell will write a message to standard error indicating the failure.
A simple example using arithmetic expansion:
# repeat a command 100 times
x=100
while [ $x -gt 0 ]
do
command
x=$(($x-1))
done
paste <(cut -f1 file1) <(cut -f3 file2) | tee >( process1) >( process2)
cuts fields 1 and 3 from the files file1 and file2 respectively, pastes the results together, and sends it to the processes process1 and process2, as well as putting it onto the standard output. Note that the file, which is passed as an argument to the command, is a UNIX pipe(2) so programs that expect to lseek(2) on the file will not work.
The shell supports a one-dimensional array facility. An element of an array variable is referenced by a subscript. A subscript is denoted by a [, followed by an arithmetic expression (see Arithmetic Evaluation below) followed by a ]. To assign values to an array, use set -A name value .... The value of all subscripts must be in the range of 0 through 1023. Arrays need not be declared. Any reference to a variable with a valid subscript is legal and an array will be created if necessary. Referencing an array without a subscript is equivalent to referencing the element 0. If an array identifier with subscript * or @ is used, then the value for each of the elements is substituted (separated by a field separator character).
The value of a variable may be assigned by writing:
name=value [ name=value ] ...
If the integer attribute, -i, is set for name, the value is subject to arithmetic evaluation as described below.
Positional parameters, parameters denoted by a number, may be assigned values with the set special command. Parameter $0 is set from argument zero when the shell is invoked. If parameter is one or more digits then it is a positional parameter. A positional parameter of more than one digit must be enclosed in braces.
${expression}
where expression consists of all characters until the matching }. Any } escaped by a backslash or within a quoted string, and characters in embedded arithmetic expansions, command substitutions and variable expansions, are not examined in determining the matching }.
The simplest form for parameter expansion is:
${parameter}
The value, if any, of parameter will be substituted.
The parameter name or symbol can be enclosed in braces, which are optional except for positional parameters with more than one digit or when parameter is followed by a character that could be interpreted as part of the name. The matching closing brace will be determined by counting brace levels, skipping over enclosed quoted strings and command substitutions.
If the parameter name or symbol is not enclosed in braces, the expansion will use the longest valid name whether or not the symbol represented by that name exists. When the shell is scanning its input to determine the boundaries of a name, it is not bound by its knowledge of what names are already defined. For example, if F is a defined shell variable, the command:
echo $Fred
does not echo the value of $F followed by red; it selects the longest possible valid name, Fred, which in this case might be unset.
If a parameter expansion occurs inside double-quotes:
In addition, a parameter expansion can be modified by using one of the following formats. In each case that a value of word is needed (based on the state of parameter, as described below), word will be subjected to tilde expansion, parameter expansion, command substitution and arithmetic expansion. If word is not needed, it will not be expanded. The } character that delimits the following parameter expansion modifications is determined as described previously in this section and in dquote. (For example, ${foo-bar}xyz} would result in the expansion of foo followed by the string xyz} if foo is set, else the string barxyz}).
In the parameter expansions shown previously, use of the colon in the format results in a test for a parameter that is unset or null; omission of the colon results in a test for a parameter that is only unset. The following table summarizes the effect of the colon:
parameter | parameter | parameter | |
set and not null | set but null | unset | |
${parameter:-word} | substitute | substitute | substitute |
parameter | word | word | |
${parameter-word} | substitute | substitute | substitute |
parameter | null | word | |
${parameter:=word} | substitute | assign | assign |
parameter | word | word | |
${parameter=word} | substitute | substitute | assign |
parameter | parameter | null | |
${parameter:?word} | substitute | error, | error, |
parameter | exit | exit | |
${parameter?word} | substitute | substitute | error, |
parameter | null | exit | |
${parameter:+word} | substitute | substitute | substitute |
word | null | null | |
${parameter+word} | substitute | substitute | substitute |
word | word | null |
In all cases shown with ‘substitute’, the expression is replaced with the value shown. In all cases shown with ‘assign’ parameter is assigned that value, which also replaces the expression.
The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see patmat), rather than regular expression notation, will be used to evaluate the patterns. If parameter is * or @, then all the positional parameters, starting with $1, are substituted (separated by a field separator character). Enclosing the full parameter expansion string in double-quotes will not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces will have this effect.
Examples:
${parameter:-word}
In this example, ls is executed only if x is null or unset. (The $(ls) command substitution notation is explained in Command Substitution above.)
${x:-$(ls)}
unset X
echo ${X:=abc}
abc
unset posix
echo ${posix:?}
sh: posix: parameter null or not set
set a b c
echo ${3:+posix}
posix
HOME=/usr/posix
echo ${#HOME}
10
x=file.c
echo ${x%.c}.o
file.o
echo ${x%%/*}
posix
x=$HOME/src/cmd
echo ${x#$HOME}
/src/cmd
x=/one/two/three
echo ${x##*/}
three
- #
- The number of positional parameters in decimal.
- -
- Flags supplied to the shell on invocation or by the set command.
- ?
- The decimal value returned by the last executed command.
- $
- The process number of this shell.
- _
- Initially, the value of _ is an absolute pathname of the shell or script being executed as passed in the environment. Subsequently it is assigned the last argument of the previous command. This parameter is not set for commands which are asynchronous. This parameter is also used to hold the name of the matching MAIL file when checking for mail.
- !
- The process number of the last background command invoked.
- ERRNO
- The value of errno as set by the most recently failed system call. This value is system dependent and is intended for debugging purposes.
- LINENO
- The line number of the current line within the script or function being executed.
- OLDPWD
- The previous working directory set by the cd command.
- OPTARG
- The value of the last option argument processed by the getopts special command.
- OPTIND
- The index of the last option argument processed by the getopts special command.
- PPID
- The process number of the parent of the shell.
- PWD
- The present working directory set by the cd command.
- RANDOM
- Each time this variable is referenced, a random integer, uniformly distributed between 0 and 32767, is generated. The sequence of random numbers can be initialized by assigning a numeric value to RANDOM.
- REPLY
- This variable is set by the select statement and by the read special command when no arguments are supplied.
- SECONDS
- Each time this variable is referenced, the number of seconds since shell invocation is returned. If this variable is assigned a value, then the value returned upon reference will be the value that was assigned plus the number of seconds since the assignment.
- CDPATH
- The search path for the cd command.
- COLUMNS
- If this variable is set, the value is used to define the width of the edit window for the shell edit modes and for printing select lists.
- EDITOR
- If the value of this variable ends in emacs, gmacs, or vi and the VISUAL variable is not set, then the corresponding option (see the set special command below) will be turned on.
- ENV
- This variable, when the shell is invoked, is subjected to parameter expansion by the shell and the resulting value is used as a pathname of a file containing shell commands to execute in the current environment. The file need not be executable. If the expanded value of ENV is not an absolute pathname, the results are unspecified. ENV will be ignored if the user’s real and effective user IDs or real and effective group IDs are different.
This variable can be used to set aliases and other items local to the invocation of a shell. The file referred to by ENV differs from $HOME/.profile in that .profile is typically executed at session startup, whereas the ENV file is executed at the beginning of each shell invocation. The ENV value is interpreted in a manner similar to a dot script, in that the commands are executed in the current environment and the file needs to be readable, but not executable. However, unlike dot scripts, no PATH searching is performed. This is used as a guard against Trojan Horse security breaches.
- FCEDIT
- The default editor name for the fc command.
- FPATH
- The search path for function definitions. By default the FPATH directories are searched after the PATH variable. If an executable file is found, then it is read and executed in the current environment. FPATH is searched before PATH when a function with the -u attribute is referenced. The preset alias autoload preset alias causes a function with the -u attribute to be created.
- IFS
- Internal field separators, normally space, tab, and new-line that are used to separate command words which result from command or parameter substitution and for separating words with the special command read. The first character of the IFS variable is used to separate arguments for the $* substitution (See Quoting below).
- HISTFILE
- If this variable is set when the shell is invoked, then the value is the pathname of the file that will be used to store the command history. (See Command re-entry below.)
- HISTSIZE
- If this variable is set when the shell is invoked, then the number of previously entered commands that are accessible by this shell will be greater than or equal to this number. The default is 128.
- HOME
- The default argument (home directory) for the cd command.
- LC_ALL
- This variable provides a default value for the LC_* variables.
- LC_COLLATE
- This variable determines the behavior of range expressions, equivalence classes and multi-character collating elements within pattern matching.
- LC_CTYPE
- Determines how the shell handles characters. When LC_CTYPE is set to a valid value, the shell can display and handle text and filenames containing valid characters for that locale. However, the shell is not multibyte (EUC) capable. In the "C" locale, only ASCII characters are valid. If LC_CTYPE (see environ(5) ) is not set in the environment, the operational behavior of the shell is determined by the value of the LANG environment variable. If LC_ALL is set, its contents are used to override both the LANG and the other LC_* variables. If none of the above variables is set in the environment, the "C" (U.S. style) locale prevails.
- LC_MESSAGES
- This variable determines the language in which messages should be written.
- LANG
- Provide a default value for the internationalization variables that are unset or null. If LANG is unset or null, the corresponding value from the default "C" locale will be used. If any of the internationalization variables contains an invalid setting, the utility will behave as if none of the variables had been defined.
- LINENO
- This variable is set by the shell to a decimal number representing the current sequential line number (numbered starting with 1) within a script or function before it executes each command. If the user unsets or resets LINENO , the variable may lose its special meaning for the life of the shell. If the shell is not currently executing a script or function, the value of LINENO is unspecified.
- LINES
- If this variable is set, the value is used to determine the column length for printing select lists. Select lists will print vertically until about two-thirds of LINES lines are filled.
- If this variable is set to the name of a mail file and the MAILPATH variable is not set, then the shell informs the user of arrival of mail in the specified file.
- MAILCHECK
- This variable specifies how often (in seconds) the shell will check for changes in the modification time of any of the files specified by the MAILPATH or MAIL variables. The default value is 600 seconds. When the time has elapsed the shell will check before issuing the next prompt.
- MAILPATH
- A colon (:) separated list of file names. If this variable is set, then the shell informs the user of any modifications to the specified files that have occurred within the last MAILCHECK seconds. Each file name can be followed by a ? and a message that will be printed. The message will undergo parameter substitution with the variable $_ defined as the name of the file that has changed. The default message is you have mail in $_.
- NLSPATH
- Determine the location of message catalogues for the processing of LC_MESSAGES .
- PATH
- The search path for commands (see Execution below). The user may not change PATH if executing under rksh (except in .profile).
- PPID
- This variable is set by the shell to the decimal process ID of the process that invoked the shell. In a subshell, PPID will be set to the same value as that of the parent of the current shell. For example, echo $PPID and (echo $PPID) would produce the same value.
- PS1
- The value of this variable is expanded for parameter substitution to define the primary prompt string which by default is ‘‘$ ’’. The character ! in the primary prompt string is replaced by the command number (see Command Re-entry below). Two successive occurrences of ! will produce a single ! when the prompt string is printed.
- PS2
- Secondary prompt string, by default ‘‘> ’’.
- PS3
- Selection prompt string used within a select loop, by default ‘‘#? ’’.
- PS4
- The value of this variable is expanded for parameter substitution and precedes each line of an execution trace. If omitted, the execution trace prompt is ‘‘+ ’’.
- SHELL
- The pathname of the shell is kept in the environment. At invocation, if the basename of this variable is rsh, rksh, or krsh, then the shell becomes restricted.
- TMOUT
- If set to a value greater than zero, the shell will terminate if a command is not entered within the prescribed number of seconds after issuing the PS1 prompt. (Note that the shell can be compiled with a maximum bound for this value which cannot be exceeded.)
- VISUAL
- If the value of this variable ends in emacs, gmacs, or vi then the corresponding option (see Special Command set below) will be turned on.
The shell gives default values to PATH , PS1 , PS2 , PS3 , PS4 , MAILCHECK , FCEDIT , TMOUT and IFS , while HOME, SHELL ENV and MAIL are not set at all by the shell (although HOME is set by login(1) ). On some systems MAIL and SHELL are also set by login.
ls .@(r*)
would locate a file named .restore, but ls @(.r*) would not. In other instances of pattern matching the / and . are not treated specially.
- *
- Matches any string, including the null string.
- ?
- Matches any single character.
- [...]
- Matches any one of the enclosed characters. A pair of characters separated by - matches any character lexically between the pair, inclusive. If the first character following the opening "[ " is a "! ", then any character not enclosed is matched. A - can be included in the character set by putting it as the first or last character.
A pattern-list is a list of one or more patterns separated from each other with a |. Composite patterns can be formed with one or more of the following:
- ?(pattern-list)
- Optionally matches any one of the given patterns.
- *(pattern-list)
- Matches zero or more occurrences of the given patterns.
- +(pattern-list)
- Matches one or more occurrences of the given patterns.
- @(pattern-list)
- Matches exactly one of the given patterns.
- !(pattern-list)
- Matches anything, except one of the given patterns.
The special meaning of reserved words or aliases can be removed by quoting any character of the reserved word. The recognition of function names or special command names listed below cannot be altered by quoting them.
An arithmetic expression uses the same syntax, precedence, and associativity of expression as the C language. All the integral operators, other than ++, --, ?:, and , are supported. Variables can be referenced by name within an arithmetic expression without using the parameter substitution syntax. When a variable is referenced, its value is evaluated as an arithmetic expression.
An internal integer representation of a variable can be specified with the -i option of the typeset special command. Arithmetic evaluation is performed on the value of each assignment to a variable with the -i attribute. If you do not specify an arithmetic base, the first assignment to the variable determines the arithmetic base. This base is used when parameter substitution occurs.
Since many of the arithmetic operators require quoting, an alternative form of the let command is provided. For any command which begins with a ((, all the characters until a matching )) are treated as a quoted expression. More precisely, ((...)) is equivalent to let "...".
In each of the above expressions, if file is of the form /dev/fd/n, where n is an integer, then the test is applied to the open file whose descriptor number is n.
A compound expression can be constructed from these primitives by using any of the following, listed in decreasing order of precedence.
If one of the above is preceded by a digit, then the file descriptor number referred to is that specified by the digit (instead of the default 0 or 1). For example:
... 2>&1
means file descriptor 2 is to be opened for writing as a duplicate of file descriptor 1.
The order in which redirections are specified is significant. The shell evaluates each redirection in terms of the (file descriptor, file) association at the time of evaluation. For example:
... 1>fname 2>&1
first associates file descriptor 1 with file fname. It then associates file descriptor 2 with the file associated with file descriptor 1 (that is fname). If the order of redirections were reversed, file descriptor 2 would be associated with the terminal (assuming file descriptor 1 had been) and then file descriptor 1 would be associated with file fname.
If a command is followed by & and job control is not active, then the default standard input for the command is the empty file /dev/null. Otherwise, the environment for the execution of a command contains the file descriptors of the invoking shell as modified by input/output specifications.
The environment for any simple-command or function may be augmented by prefixing it with one or more variable assignments. A variable assignment argument is a word of the form identifier=value. Thus:
TERM =450 cmd args
and
(export TERM ; TERM =450; cmd args)
are equivalent (as far as the above execution of cmd is concerned except for special commands listed below that are preceded with a dagger).
If the -k flag is set, all variable assignment arguments are placed in the environment, even if they occur after the command name. The following first prints a=b c and then c:
echo a=b cset -kecho a=b c
This feature is intended for use with scripts written for early versions of the shell and its use in new scripts is strongly discouraged. It is likely to disappear someday.
The function reserved word, described in the Commands section above, is used to define shell functions. Shell functions are read in and stored internally. Alias names are resolved when the function is read. Functions are executed like commands with the arguments passed as positional parameters. (See Execution below.)
Functions execute in the same process as the caller and share all files and present working directory with the caller. Traps caught by the caller are reset to their default action inside the function. A trap condition that is not caught or ignored by the function causes the function to terminate and the condition to be passed on to the caller. A trap on EXIT set inside a function is executed after the function completes in the environment of the caller. Ordinarily, variables are shared between the calling program and the function. However, the typeset special command used within a function defines local variables whose scope includes the current function and all functions it calls.
The special command return is used to return from function calls. Errors within functions return control to the caller.
The names of all functions can be listed with typeset +f. typeset -f lists all function names as well as the text of all functions. typeset -f function-names lists the text of the named functions only. Functions can be undefined with the -f option of the unset special command.
Ordinarily, functions are unset when the shell executes a shell script. The -xf option of the typeset command allows a function to be exported to scripts that are executed without a separate invocation of the shell. Functions that need to be defined across separate invocations of the shell should be specified in the ENV file with the -xf option of typeset.
The format of a function definition command is as follows:
fname() compound-command[io-redirect ...]
The function is named fname; it must be a name. An implementation may allow other characters in a function name as an extension. The implementation will maintain separate name spaces for functions and variables.
The () in the function definition command consists of two operators. Therefore, intermixing blank characters with the fname, (, and ) is allowed, but unnecessary.
The argument compound-command represents a compound command.
When the function is declared, none of the expansions in wordexp will be performed on the text in compound-command or io-redirect; all expansions will be performed as normal each time the function is called. Similarly, the optional io-redirect redirections and any variable assignments within compound-command will be performed during the execution of the function itself, not the function definition.
When a function is executed, it will have the syntax-error and variable-assignment properties described for the special built-in utilities.
The compound-command will be executed whenever the function name is specified as the name of a simple command The operands to the command temporarily will become the positional parameters during the execution of the compound-command; the special parameter # will also be changed to reflect the number of operands. The special parameter 0 will be unchanged. When the function completes, the values of the positional parameters and the special parameter # will be restored to the values they had before the function was executed. If the special built-in return is executed in the compound-command, the function will complete and execution will resume with the next command after the function call.
An example of how a function definition can be used wherever a simple command is allowed:
# If variable i is equal to "yes",
# define function foo to be ls -l
#
[ "$i" = yes ] && foo() {
ls -l
}
The exit status of a function definition will be 0 if the function was declared successfully; otherwise, it will be greater than zero. The exit status of a function invocation will be the exit status of the last command executed by the function.
If the monitor option of the set command is turned on, an interactive shell associates a job with each pipeline. It keeps a table of current jobs, printed by the jobs command, and assigns them small integer numbers. When a job is started asynchronously with &, the shell prints a line which looks like:
[1] 1234
indicating that the job, which was started asynchronously, was job number 1 and had one (top-level) process, whose process id was 1234.
If you are running a job and wish to do something else you may hit the key ^Z (CTRL-Z ) which sends a STOP signal to the current job. The shell will then normally indicate that the job has been ‘Stopped’, and print another prompt. You can then manipulate the state of this job, putting it in the background with the bg command, or run some other commands and then eventually bring the job back into the foreground with the foreground command fg. A ^Z takes effect immediately and is like an interrupt in that pending output and unread input are discarded when it is typed.
A job being run in the background will stop if it tries to read from the terminal. Background jobs are normally allowed to produce output, but this can be disabled by giving the command ‘stty tostop’. If you set this tty option, then background jobs will stop when they try to produce output like they do when they try to read input.
There are several ways to refer to jobs in the shell. A job can be referred to by the process id of any process of the job or by one of the following:
The shell learns immediately whenever a process changes state. It normally informs you whenever a job becomes blocked so that no further progress is possible, but only just before it prints a prompt. This is done so that it does not otherwise disturb your work.
When the monitor mode is on, each background job that completes triggers any trap set for CHLD .
When you try to leave the shell while jobs are running or stopped, you will be warned that ‘You have stopped(running) jobs.’ You may use the jobs command to see what they are. If you do this or immediately try to exit again, the shell will not warn you a second time, and the stopped jobs will be terminated. If you have nohup’ed jobs running when you attempt to logout, you will be warned with the message
You have jobs running.
You will then need to logout a second time to actually logout; however, your background jobs will continue to run.
The shell variable PATH defines the search path for the directory containing the command. Alternative directory names are separated by a colon (:). The default path is /bin:/usr/bin: (specifying /bin, /usr/bin, and the current directory in that order). The current directory can be specified by two or more adjacent colons, or by a colon at the beginning or end of the path list. If the command name contains a / then the search path is not used. Otherwise, each directory in the path is searched for an executable file. If the file has execute permission but is not a directory or an a.out file, it is assumed to be a file containing shell commands. A sub-shell is spawned to read it. All non-exported aliases, functions, and variables are removed in this case. A parenthesized command is executed in a sub-shell without removing non-exported quantities.
The editing features require that the user’s terminal accept RETURN as carriage return without line feed and that a space must overwrite the current character on the screen.
The editing modes implement a concept where the user is looking through a window at the current line. The window width is the value of COLUMNS if it is defined, otherwise 80. If the window width is too small to display the prompt and leave at least 8 columns to enter input, the prompt is truncated from the left. If the line is longer than the window width minus two, a mark is displayed at the end of the window to notify the user. As the cursor moves and reaches the window boundaries the window will be centered about the cursor. The mark is a > if the line extends on the right side of the window, < if the line extends on the left, and * if the line extends on both sides of the window.
The search commands in each edit mode provide access to the history file. Only strings are matched, not patterns, although a leading ^ in the string restricts the match to begin at the first character in the line.
The notation for escape sequences is M- followed by a character. For example, M-f (pronounced Meta f) is entered by depressing ESC (ascii 033) followed by ‘f’. (M-F would be the notation for ESC followed by SHIFT (capital) ‘F’.)
All edit commands operate from any place on the line (not just at the beginning). Neither the RETURN nor the LINEFEED key is entered after edit commands except when noted.
When in vi mode on most systems, canonical processing is initially enabled and the command will be echoed again if the speed is 1200 baud or greater and it contains any control characters or less than one second has elapsed since the prompt was printed. The ESC character terminates canonical processing for the remainder of the command and the user can then modify the command line. This scheme has the advantages of canonical processing with the type-ahead echoing of raw mode.
If the option viraw is also set, the terminal will always have canonical processing disabled. This mode is implicit for systems that do not support two alternate end of line delimiters, and may be helpful for certain terminals.
- erase
- (User defined erase character as defined by the stty(1) command, usually ^H or #.) Delete previous character.
- ^W
- Delete the previous blank separated word.
- ^D
- Terminate the shell.
- ^V
- Escape next character. Editing characters and the user’s erase or kill characters may be entered in a command line or in a search string if preceded by a ^V. The ^V removes the next character’s editing features (if any).
- \
- Escape the next erase or kill character.
- [count]l
- Cursor forward (right) one character.
- [count]w
- Cursor forward one alpha-numeric word.
- [count]W
- Cursor to the beginning of the next word that follows a blank.
- [count]e
- Cursor to end of word.
- [count]E
- Cursor to end of the current blank delimited word.
- [count]h
- Cursor backward (left) one character.
- [count]b
- Cursor backward one word.
- [count]B
- Cursor to preceding blank separated word.
- [count]|
- Cursor to column count.
- [count]fc
- Find the next character c in the current line.
- [count]Fc
- Find the previous character c in the current line.
- [count]tc
- Equivalent to f followed by h.
- [count]Tc
- Equivalent to F followed by l.
- [count];
- Repeats count times, the last single character find command, f, F, t, or T.
- [count],
- Reverses the last single character find command count times.
- Cursor to start of line.
- ^
- Cursor to first non-blank character in line.
- $
- Cursor to end of line.
- %
- Moves to balancing (, ), {, }, [, or ]. If cursor is not on one of the above characters, the remainder of the line is searched for the first occurrence of one of the above characters first.
- [count]k
- Fetch previous command. Each time k is entered the previous command back in time is accessed.
- [count]-
- Equivalent to k.
- [count]j
- Fetch next command. Each time j is entered the next command forward in time is accessed.
- [count]+
- Equivalent to j.
- [count]G
- The command number count is fetched. The default is the least recent history command.
- /string
- Search backward through history for a previous command containing string. string is terminated by a RETURN or NEWLINE . If string is preceded by a ^, the matched line must begin with string. If string is NULL , the previous string will be used.
- ?string
- Same as / except that search will be in the forward direction.
- n
- Search for next match of the last pattern to / or ? commands.
- N
- Search for next match of the last pattern to / or ?, but in reverse direction. Search history for the string entered by the previous / command.
- a
- Enter input mode and enter text after the current character.
- A
- Append text to the end of the line. Equivalent to $a.
- [count]cmotion
- c[count]motion
- Delete current character through the character that motion would move the cursor to and enter input mode. If motion is c, the entire line will be deleted and input mode entered.
- C
- Delete the current character through the end of line and enter input mode. Equivalent to c$.
- [count]s
- Delete count characters and enter input mode.
- S
- Equivalent to cc.
- D
- Delete the current character through the end of line. Equivalent to d$.
- [count]dmotion
- d[count]motion
- Delete current character through the character that motion would move to. If motion is d, the entire line will be deleted.
- i
- Enter input mode and insert text before the current character.
- I
- Insert text before the beginning of the line. Equivalent to 0i.
- [count]P
- Place the previous text modification before the cursor.
- [count]p
- Place the previous text modification after the cursor.
- R
- Enter input mode and replace characters on the screen with characters you type overlay fashion.
- [count]rc
- Replace the count character(s) starting at the current cursor position with c, and advance the cursor.
- [count]x
- Delete current character.
- [count]X
- Delete preceding character.
- [count].
- Repeat the previous text modification command.
- [count]~
- Invert the case of the count character(s) starting at the current cursor position and advance the cursor.
- [count]_
- Causes the count word of the previous command to be appended and input mode entered. The last word is used if count is omitted.
- *
- Causes an * to be appended to the current word and file name generation attempted. If no match is found, it rings the bell. Otherwise, the word is replaced by the matching pattern and input mode is entered.
- \
- Filename completion. Replaces the current word with the longest common prefix of all filenames matching the current word with an asterisk appended. If the match is unique, a / is appended if the file is a directory and a space is appended if the file is not a directory.
[count]ymotion
- y[count]motion
- Yank current character through character that motion would move the cursor to and puts them into the delete buffer. The text and cursor are unchanged.
- Y
- Yanks from current position to end of line. Equivalent to y$.
- u
- Undo the last text modifying command.
- U
- Undo all the text modifying commands performed on the line.
- [count]v
- Returns the command fc -e ${VISUAL :-${EDITOR :-vi}} count in the input buffer. If count is omitted, then the current line is used.
- ^L
- Line feed and print current line. Has effect only in control mode.
- J
- (New line) Execute the current line, regardless of mode.
- M
- (Return) Execute the current line, regardless of mode.
- #
- If the first character of the command is a #, then this command deletes this # and each # that follows a newline. Otherwise, sends the line after inserting a # in front of each line in the command. Useful for causing the current line to be inserted in the history as a comment and removing comments from previous comment commands in the history file.
- =
- List the file names that match the current word if an asterisk were appended it.
- @letter
- Your alias list is searched for an alias by the name _letter and if an alias of this name is defined, its value will be inserted on the input queue for processing.
.
- Variable assignment lists preceding the command remain in effect when the command completes.
.- I/O redirections are processed after variable assignments.
.- Errors cause a script that contains them to abort.
.- Words, following a command preceded by ** that are in the format of a variable assignment, are expanded with the same rules as a variable assignment. This means that tilde substitution is performed after the = sign and word splitting and file name generation are not performed.
The second form of cd substitutes the string new for the string old in the current directory name, PWD and tries to change to this new directory.
The cd command may not be executed by rksh.
getopts places the next option letter it finds inside variable name each time it is invoked with a + prepended when arg begins with a +. The index of the next arg is stored in OPTIND. The option argument, if any, gets stored in OPTARG.
A leading : in optstring causes getopts to store the letter of an invalid option in OPTARG, and to set name to ? for an unknown option and to : when a required option is missing. Otherwise, getopts prints an error message. The exit status is non-zero when there are no more options. See getoptcvt(1) for usage and description.
The exit status is 0 if the value of the last expression is non-zero, and 1 otherwise.
"[%d]%c %s%s\n", <job-number>, <current>, <status>, <job-name>
where the fields are as follows:
- <current>
- The character + identifies the job that would be used as a default for the fg or bg utilities; this job can also be specified using the job_id %+ or %%. The character - identifies the job that would become the default if the current default job were to exit; this job can also be specified using the job_id %-. For other jobs, this field is a space character. At most one job can be identified with + and at most one job can be identified with -. If there is any suspended job, then the current job will be a suspended job. If there are at least two suspended jobs, then the previous job will also be a suspended job.
- <job-number>
- A number that can be used to identify the process group to the wait, fg, bg, and kill utilities. Using these utilities, the job can be identified by prefixing the job number with %.
- <status>
- Unspecified.
- <job-name>
- Unspecified.
When the shell notifies the user a job has been completed, it may remove the job’s process ID from the list of those known in the current shell execution environment. Asynchronous notification will not be enabled by default.
If no option name is supplied then the current option settings are printed.
Using + rather than - causes these flags to be turned off. These flags can also be used upon invocation of the shell. The current set of flags may be found in $-. Unless -A is specified, the remaining arguments are positional parameters and are assigned, in order, to $1 $2 .... If no arguments are given then the names and values of all variables are printed on the standard output.
stop %jobid ...
If arg is -, the shell will reset each sig to the default value. If arg is null (’’), the shell will ignore each specified sig if it arises. Otherwise, arg will be read and executed by the shell when one of the corresponding sigs arises. The action of the trap will override a previous action (either default action or one explicitly set). The value of $? after the trap action completes will be the value it had before the trap was invoked.
sig can be EXIT , 0 (equivalent to EXIT ) or a signal specified using a symbolic name, without the SIG prefix, for example, HUP , INT , QUIT , TERM . If sig is 0 or EXIT and the trap statement is executed inside the body of a function, then the command arg is executed after the function completes. If sig is 0 or EXIT for a trap set outside any function then the command arg is executed on exit from the shell. If sig is ERR then arg will be executed whenever a command has a non-zero exit status. If sig is DEBUG then arg will be executed after each command.
The environment in which the shell executes a trap on EXIT
will be identical
to the environment immediately after the last command executed before the
trap on EXIT
was taken.
Each time the trap is invoked, arg will be processed in a manner equivalent to:
eval "$arg"Signals that were ignored on entry to a non-interactive shell cannot be trapped or reset, although no error need be reported when attempting to do so. An interactive shell may reset or catch signals ignored on entry. Traps will remain in place for a given shell until explicitly changed with another trap command.
When a subshell is entered, traps are set to the default args. This does not imply that the trap command cannot be used within the subshell to set new traps.
The trap command with no arguments will write to standard output a list of commands associated with each sig. The format is:
trap -- %s %s ... <arg>, <sig> ...The shell will format the output, including the proper use of quoting, so that it is suitable for reinput to the shell as commands that achieve the same trapping results. For example:
save_traps=$(trap)...eval "$save_traps"If the trap name or number is invalid, a non-zero exit status will be returned; otherwise, 0 will be returned. For both interactive and non-interactive shells, invalid signal names or numbers will not be considered a syntax error and will not cause the shell to abort.
Traps are not processed while a job is waiting for a foreground process. Thus, a trap on CHLD won’t be executed until the foreground job terminates.
The -i attribute can not be specified along with -R,
-L, -Z, or -f.
Using + rather than - causes these flags to be turned off. If no name arguments are given but flags are specified, a list of names (and optionally the values) of the variables which have these flags set is printed. (Using + rather than - keeps the values from being printed.) If no names and flags are given, the names and attributes of all variables are printed.
If no option is given, -f is assumed.
The -v flag produces a more verbose report.
The -p flag does a path search for name even if name is an alias, a function, or a reserved word.
The remaining flags and arguments are described under the set command above.
The restrictions above are enforced after .profile and the ENV files are interpreted.
When a command to be executed is found to be a shell procedure, rksh invokes ksh to execute it. Thus, it is possible to provide to the end-user shell procedures that have access to the full power of the standard shell, while imposing a limited menu of commands; this scheme assumes that the end-user does not have write and execute permissions in the same directory.
The net effect of these rules is that the writer of the .profile has complete control over user actions, by performing guaranteed setup actions and leaving the user in an appropriate directory (probably not the login directory).
The system administrator often sets up a directory of commands (that is, /usr/rbin) that can be safely invoked by rksh.
For a non-interactive shell, an error condition encountered by a special built-in or other type of utility will cause the shell to write a diagnostic message to standard error and exit as shown in the following table:
Error | Special Built-in | Other Utilities |
Shell language syntax error | will exit | will exit |
Utility syntax error | ||
(option or operand error) | will exit | will not exit |
Redirection error | will exit | will not exit |
Variable assignment error | will exit | will not exit |
Expansion error | will exit | will exit |
Command not found | n/a | may exit |
Dot script not found | will exit | n/a |
An expansion error is one that occurs when the shell expansions are carried out (for example, ${x!y}, because ! is not a valid operator); an implementation may treat these as syntax errors if it is able to detect them during tokenization, rather than during expansion.
If any of the errors shown as ‘will (may) exit’ occur in a subshell, the subshell will (may) exit with a non-zero status, but the script containing the subshell will not exit because of the error.
In all of the cases shown in the table, an interactive shell will write a diagnostic message to standard error without exiting.
If a command is not found, the exit status will be 127. If the command name is found, but it is not an executable utility, the exit status will be 126. Applications that invoke utilities without using the shell should use these exit status values to report similar errors.
If a command fails during word expansion or redirection, its exit status will be greater than zero.
When reporting the exit status with the special parameter ?, the shell will report the full eight bits of exit status available. The exit status of a command that terminated because it received a signal will be reported as greater than 128.
Morris I. Bolsky and David G. Korn, The KornShell Command and Programming Language, Prentice Hall, 1989.
If a command which is a tracked alias is executed, and then a command with the same name is installed in a directory in the search path before the directory where the original command was found, the shell will continue to exec the original command. Use the -t option of the alias command to correct this situation.
Some very old shell scripts contain a ^ as a synonym for the pipe character |.
Using the fc built-in command within a compound command will cause the whole command to disappear from the history file.
The built-in command . file reads the whole file before any commands are executed. Therefore, alias and unalias commands in the file will not apply to any functions defined in the file.