Movatterモバイル変換


[0]ホーム

URL:


<<<PreviousHomeNext>>>


2.Shell Command Language

This chapter contains the definition of the Shell Command Language.

2.1Shell Introduction

The shell is a command language interpreter. This chapter describes the syntax of that command language as it is used by thesh utility and thesystem() andpopen() functions defined in the System Interfaces volume of POSIX.1-2017.

The shell operates according to the following general overview of operations. The specific details are included in the citedsections of this chapter.

  1. The shell reads its input from a file (seesh), from the-c option or from thesystem() andpopen() functions definedin the System Interfaces volume of POSIX.1-2017. If the first line of a file of shell commands starts with the characters"#!", the results are unspecified.

  2. The shell breaks the input into tokens: words and operators; seeToken Recognition.

  3. The shell parses the input into simple commands (seeSimple Commands) and compound commands (seeCompound Commands).

  4. The shell performs various expansions (separately) on different parts of each command, resulting in a list of pathnames andfields to be treated as a command and arguments; seewordexp.

  5. The shell performs redirection (seeRedirection) and removes redirection operators and their operandsfrom the parameter list.

  6. The shell executes a function (seeFunction Definition Command), built-in (seeSpecial Built-In Utilities), executable file, or script, giving the names of the arguments as positionalparameters numbered 1 ton, and the name of the command (or in the case of a function within a script, the name of thescript) as the positional parameter numbered 0 (seeCommand Search and Execution).

  7. The shell optionally waits for the command to complete and collects the exit status (seeExit Status forCommands).

2.2Quoting

Quoting is used to remove the special meaning of certain characters or words to the shell. Quoting can be used to preserve theliteral meaning of the special characters in the next paragraph, prevent reserved words from being recognized as such, and preventparameter expansion and command substitution within here-document processing (seeHere-Document).

The application shall quote the following characters if they are to represent themselves:

|  &  ;  <  >  (  )  $  `  \  "  '  <space>  <tab>  <newline>

and the following may need to be quoted under certain circumstances. That is, these characters may be special depending onconditions described elsewhere in this volume of POSIX.1-2017:

*   ?   [   #   ˜   =   %

The various quoting mechanisms are the escape character, single-quotes, and double-quotes. The here-document represents anotherform of quoting; seeHere-Document.

2.2.1Escape Character (Backslash)

A <backslash> that is not quoted shall preserve the literal value of the following character, with the exception of a<newline>. If a <newline> follows the <backslash>, the shell shall interpret this as line continuation. The<backslash> and <newline> shall be removed before splitting the input into tokens. Since the escaped <newline> isremoved entirely from the input and is not replaced by any white space, it cannot serve as a token separator.

2.2.2Single-Quotes

Enclosing characters in single-quotes ('' ) shall preserve the literal value of each character within thesingle-quotes. A single-quote cannot occur within single-quotes.

2.2.3Double-Quotes

Enclosing characters in double-quotes ("" ) shall preserve the literal value of all characters within thedouble-quotes, with the exception of the characters backquote, <dollar-sign>, and <backslash>, as follows:

$
The <dollar-sign> shall retain its special meaning introducing parameter expansion (seeParameterExpansion), a form of command substitution (seeCommand Substitution), and arithmetic expansion(seeArithmetic Expansion).

The input characters within the quoted string that are also enclosed between"$(" and the matching')' shallnot be affected by the double-quotes, but rather shall define that command whose output replaces the"$(...)" when theword is expanded. The tokenizing rules inToken Recognition, not including the alias substitutions inAlias Substitution, shall be applied recursively to find the matching')'.

Within the string of characters from an enclosed"${" to the matching'}', an even number of unescapeddouble-quotes or single-quotes, if any, shall occur. A preceding <backslash> character shall be used to escape a literal'{' or'}'. The rule inParameter Expansion shall be used to determine the matching'}'.

`
The backquote shall retain its special meaning introducing the other form of command substitution (seeCommand Substitution). The portion of the quoted string from the initial backquote and the characters up tothe next backquote that is not preceded by a <backslash>, having escape characters removed, defines that command whose outputreplaces"`...`" when the word is expanded. Either of the following cases produces undefined results:
\
The <backslash> shall retain its special meaning as an escape character (seeEscape Character(Backslash)) only when followed by one of the following characters when considered special:
$   `   "   \   <newline>

The application shall ensure that a double-quote is preceded by a <backslash> to be included within double-quotes. Theparameter'@' has special meaning inside double-quotes and is described inSpecial Parameters.

2.3Token Recognition

The shell shall read its input in terms of lines. (For details about how the shell reads its input, see the description ofsh.) The input lines can be of unlimited length. These lines shall be parsed using twomajor modes: ordinary token recognition and processing of here-documents.

When anio_here token has been recognized by the grammar (seeShell Grammar), one or more ofthe subsequent lines immediately following the nextNEWLINE token form the body of one or more here-documents and shall beparsed according to the rules ofHere-Document.

When it is not processing anio_here, the shell shall break its input into tokens by applying the first applicable rulebelow to the next character in its input. The token shall be from the current position in the input until a token is delimitedaccording to one of the rules below; the characters forming the token are exactly those in the input, including any quotingcharacters. If it is indicated that a token is delimited, and no characters have been included in a token, processing shallcontinue until an actual token is delimited.

  1. If the end of input is recognized, the current token (if any) shall be delimited.

  2. If the previous character was used as part of an operator and the current character is not quoted and can be used with theprevious characters to form an operator, it shall be used as part of that (operator) token.

  3. If the previous character was used as part of an operator and the current character cannot be used with the previous charactersto form an operator, the operator containing the previous character shall be delimited.

  4. If the current character is <backslash>, single-quote, or double-quote and it is not quoted, it shall affect quoting forsubsequent characters up to the end of the quoted text. The rules for quoting are as described inQuoting. During token recognition no substitutions shall be actually performed, and the result token shall contain exactly the charactersthat appear in the input (except for <newline> joining), unmodified, including any embedded or enclosing quotes orsubstitution operators, between the <quotation-mark> and the end of the quoted text. The token shall not be delimited by theend of the quoted field.

  5. If the current character is an unquoted'$' or'`', the shell shall identify the start of any candidates forparameter expansion (Parameter Expansion), command substitution (CommandSubstitution), or arithmetic expansion (Arithmetic Expansion) from their introductory unquotedcharacter sequences:'$' or"${","$(" or'`', and"$((", respectively. The shellshall read sufficient input to determine the end of the unit to be expanded (as explained in the cited sections). While processingthe characters, if instances of expansions or quoting are found nested within the substitution, the shell shall recursively processthem in the manner specified for the construct that is found. The characters found from the beginning of the substitution to itsend, allowing for any recursion necessary to recognize embedded constructs, shall be included unmodified in the result token,including any embedded or enclosing substitution operators or quotes. The token shall not be delimited by the end of thesubstitution.

  6. If the current character is not quoted and can be used as the first character of a new operator, the current token (if any)shall be delimited. The current character shall be used as the beginning of the next (operator) token.

  7. If the current character is an unquoted <blank>, any token containing the previous character is delimited and the currentcharacter shall be discarded.

  8. If the previous character was part of a word, the current character shall be appended to that word.

  9. If the current character is a'#', it and all subsequent characters up to, but excluding, the next <newline>shall be discarded as a comment. The <newline> that ends the line is not considered part of the comment.

  10. The current character is used as the start of a new word.

Once a token is delimited, it is categorized as required by the grammar inShell Grammar.

2.3.1Alias Substitution

After a token has been delimited, but before applying the grammatical rules inShell Grammar, aresulting word that is identified to be the command name word of a simple command shall be examined to determine whether it is anunquoted, valid alias name. However, reserved words in correct grammatical context shall not be candidates for alias substitution.A valid alias name (see XBDAlias Name) shall be one that has beendefined by thealias utility and not subsequently undefined usingunalias. Implementations also may provide predefined valid aliases that are in effect whenthe shell is invoked. To prevent infinite loops in recursive aliasing, if the shell is not currently processing an alias of thesame name, the word shall be replaced by the value of the alias; otherwise, it shall not be replaced.

If the value of the alias replacing the word ends in a <blank>, the shell shall check the next command word for aliassubstitution; this process shall continue until a word is found that is not a valid alias or an alias value does not end in a<blank>.

When used as specified by this volume of POSIX.1-2017, alias definitions shall not be inherited by separate invocations of theshell or by the utility execution environments invoked by the shell; seeShell Execution Environment.

2.4Reserved Words

Reserved words are words that have special meaning to the shell; seeShell Commands. The followingwords shall be recognized as reserved words:


!
{
}
case


do
done
elif
else


esac
fi
for
if


in
then
until
while

This recognition shall only occur when none of the characters is quoted and when the word is used as:

See the grammar inShell Grammar.

The following words may be recognized as reserved words on some implementations (when none of the characters are quoted),causing unspecified results:

[[

]]

function

select

Words that are the concatenation of a name and a <colon> (':' ) are reserved; their use produces unspecifiedresults.

2.5Parameters and Variables

A parameter can be denoted by a name, a number, or one of the special characters listed inSpecialParameters. A variable is a parameter denoted by a name.

A parameter is set if it has an assigned value (null is a valid value). Once a variable is set, it can only be unset by usingtheunset special built-in command.

2.5.1Positional Parameters

A positional parameter is a parameter denoted by the decimal value represented by one or more digits, other than the singledigit 0. The digits denoting the positional parameters shall always be interpreted as a decimal value, even if there is a leadingzero. When a positional parameter with more than one digit is specified, the application shall enclose the digits in braces (seeParameter Expansion). Positional parameters are initially assigned when the shell is invoked (seesh), temporarily replaced when a shell function is invoked (seeFunction Definition Command), and can be reassigned with theset special built-incommand.

2.5.2Special Parameters

Listed below are the special parameters and the values to which they shall expand. Only the values of the special parameters arelisted; seewordexp for a detailed summary of all the stages involved in expandingwords.

@
Expands to the positional parameters, starting from one, initially producing one field for each positional parameter that isset. When the expansion occurs in a context where field splitting will be performed, any empty fields may be discarded and each ofthe non-empty fields shall be further split as described inField Splitting. When the expansion occurswithin double-quotes, the behavior is unspecified unless one of the following is true:

If one of these conditions is true, the initial fields shall be retained as separate fields, except that if the parameter beingexpanded was embedded within a word, the first field shall be joined with the beginning part of the original word and the lastfield shall be joined with the end part of the original word. In all other contexts the results of the expansion are unspecified.If there are no positional parameters, the expansion of'@' shall generate zero fields, even when'@' is withindouble-quotes; however, if the expansion is embedded within a word which contains one or more other parts that expand to a quotednull string, these null string(s) shall still produce an empty field, except that if the other parts are all within the samedouble-quotes as the'@', it is unspecified whether the result is zero fields or one empty field.

*
Expands to the positional parameters, starting from one, initially producing one field for each positional parameter that isset. When the expansion occurs in a context where field splitting will be performed, any empty fields may be discarded and each ofthe non-empty fields shall be further split as described inField Splitting. When the expansion occursin a context where field splitting will not be performed, the initial fields shall be joined to form a single field with the valueof each parameter separated by the first character of theIFS variable ifIFS contains at least one character, orseparated by a <space> ifIFS is unset, or with no separation ifIFS is set to a null string.
#
Expands to the decimal number of positional parameters. The command name (parameter 0) shall not be counted in the number givenby'#' because it is a special parameter, not a positional parameter.
?
Expands to the decimal exit status of the most recent pipeline (seePipelines).
-
(Hyphen.) Expands to the current option flags (the single-letter option names concatenated into a string) as specified oninvocation, by theset special built-in command, or implicitly by the shell.
$
Expands to the decimal process ID of the invoked shell. In a subshell (seeShell Execution Environment),'$' shall expand to the same value as that of the current shell.
!
Expands to the decimal process ID of the most recent background command (seeLists) executed fromthe current shell. (For example, background commands executed from subshells do not affect the value of"$!" in thecurrent shell environment.) For a pipeline, the process ID is that of the last command in the pipeline.
0
(Zero.) Expands to the name of the shell or shell script. Seesh for a detaileddescription of how this name is derived.

See the description of theIFS variable inShell Variables.

2.5.3Shell Variables

Variables shall be initialized from the environment (as defined by XBDEnvironment Variables and theexec function in the System Interfaces volumeof POSIX.1-2017) and can be given new values with variable assignment commands. If a variable is initialized from the environment,it shall be marked for export immediately; see theexport special built-in. New variables can bedefined and initialized with variable assignments, with theread orgetopts utilities, with thename parameter in afor loop, with the ${name=word} expansion, or with other mechanisms provided as implementation extensions.

The following variables shall affect the execution of the shell:

ENV
[UP][Option Start]The processing of theENV shell variable shall be supported if the system supports the User Portability Utilities option.[Option End]

This variable, when and only when an interactive shell is invoked, shall be subjected to parameter expansion (seeParameter Expansion) by the shell and the resulting value shall be used as a pathname of a file containingshell commands to execute in the current environment. The file need not be executable. If the expanded value ofENV is notan absolute pathname, the results are unspecified.ENV shall be ignored if the user's real and effective user IDs or realand effective group IDs are different.

HOME
The pathname of the user's home directory. The contents ofHOME are used in tilde expansion (seeTilde Expansion).
IFS
A string treated as a list of characters that is used for field splitting, expansion of the'*' special parameter, andto split lines into fields with theread utility. If the value ofIFS includesany bytes that do not form part of a valid character, the results of field splitting, expansion of'*', and use of theread utility are unspecified.

IfIFS is not set, it shall behave as normal for an unset variable, except that field splitting by the shell and linesplitting by theread utility shall be performed as if the value ofIFS is<space> <tab> <newline>; seeField Splitting.

The shell shall setIFS to <space> <tab> <newline> when it is invoked.

LANG
Provide a default value for the internationalization variables that are unset or null. (See XBDInternationalization Variables for the precedence of internationalizationvariables used to determine the values of locale categories.)
LC_ALL
The value of this variable overrides theLC_* variables andLANG, as described in XBDEnvironment Variables.
LC_COLLATE
Determine the behavior of range expressions, equivalence classes, and multi-character collating elements within patternmatching.
LC_CTYPE
Determine the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed tomulti-byte characters), which characters are defined as letters (character classalpha) and <blank> characters(character classblank), and the behavior of character classes within pattern matching. Changing the value ofLC_CTYPE after the shell has started shall not affect the lexical processing of shell commands in the current shellexecution environment or its subshells. Invoking a shell script or performingexecsh subjects the new shell to the changes inLC_CTYPE.
LC_MESSAGES
Determine the language in which messages should be written.
LINENO
Set by the shell to a decimal number representing the current sequential line number (numbered starting with 1) within a scriptor function before it executes each command. If the user unsets or resetsLINENO, the variable may lose its special meaningfor the life of the shell. If the shell is not currently executing a script or function, the value ofLINENO is unspecified.This volume of POSIX.1-2017 specifies the effects of the variable only for systems supporting the User Portability Utilitiesoption.
NLSPATH
[XSI][Option Start]Determine the location of message catalogs for the processing ofLC_MESSAGES.[Option End]
PATH
A string formatted as described in XBDEnvironment Variables, used toeffect command interpretation; seeCommand Search and Execution.
PPID
Set by the shell to the decimal value of its parent process ID during initialization of the shell. In a subshell (seeShell Execution Environment),PPID shall be set to the same value as that of the parent of the currentshell. For example,echo $PPID and (echo $PPID) would produce the same value.
PS1
Each time an interactive shell is ready to read a command, the value of this variable shall be subjected to parameter expansionand written to standard error. The default value shall be"$ ". For users who have specific additionalimplementation-defined privileges, the default may be another, implementation-defined value. The shell shall replace each instanceof the character'!' inPS1 with the history file number of the next command to be typed. Escaping the'!'with another'!' (that is,"!!" ) shall place the literal character'!' in the prompt. This volume ofPOSIX.1-2017 specifies the effects of the variable only for systems supporting the User Portability Utilities option.
PS2
Each time the user enters a <newline> prior to completing a command line in an interactive shell, the value of thisvariable shall be subjected to parameter expansion and written to standard error. The default value is"> ". Thisvolume of POSIX.1-2017 specifies the effects of the variable only for systems supporting the User Portability Utilitiesoption.
PS4
When an execution trace (set-x) is being performed in an interactive shell, before each linein the execution trace, the value of this variable shall be subjected to parameter expansion and written to standard error. Thedefault value is"+ ". This volume of POSIX.1-2017 specifies the effects of the variable only for systems supportingthe User Portability Utilities option.
PWD
Set by the shell and by thecd utility. In the shell the value shall be initializedfrom the environment as follows. If a value forPWD is passed to the shell in the environment when it is executed, the valueis an absolute pathname of the current working directory that is no longer than {PATH_MAX} bytes including the terminating nullbyte, and the value does not contain any components that are dot or dot-dot, then the shell shall setPWD to the value fromthe environment. Otherwise, if a value forPWD is passed to the shell in the environment when it is executed, the value isan absolute pathname of the current working directory, and the value does not contain any components that are dot or dot-dot, thenit is unspecified whether the shell setsPWD to the value from the environment or setsPWD to the pathname that wouldbe output bypwd-P. Otherwise, theshutility setsPWD to the pathname that would be output bypwd-P. In caseswherePWD is set to the value from the environment, the value can contain components that refer to files of type symboliclink. In cases wherePWD is set to the pathname that would be output bypwd-P, if there is insufficient permission on the current working directory, or on any parent of that directory, to determinewhat that pathname would be, the value ofPWD is unspecified. Assignments to this variable may be ignored. If an applicationsets or unsets the value ofPWD, the behaviors of thecd andpwd utilities are unspecified.

2.6Word Expansions

This section describes the various expansions that are performed on words. Not all expansions are performed on every word, asexplained in the following sections.

Tilde expansions, parameter expansions, command substitutions, arithmetic expansions, and quote removals that occur within asingle word expand to a single field. It is only field splitting or pathname expansion that can create multiple fields from asingle word. The single exception to this rule is the expansion of the special parameter'@' within double-quotes, asdescribed inSpecial Parameters.

The order of word expansion shall be as follows:

  1. Tilde expansion (seeTilde Expansion), parameter expansion (seeParameterExpansion), command substitution (seeCommand Substitution), and arithmetic expansion (seeArithmetic Expansion) shall be performed, beginning to end. See item 5 inTokenRecognition.

  2. Field splitting (seeField Splitting) shall be performed on the portions of the fields generated bystep 1, unlessIFS is null.

  3. Pathname expansion (seePathname Expansion) shall be performed, unlessset-f is in effect.

  4. Quote removal (seeQuote Removal) shall always be performed last.

The expansions described in this section shall occur in the same shell environment as that in which the command is executed.

If the complete expansion appropriate for a word results in an empty field, that empty field shall be deleted from the list offields that form the completely expanded command, unless the original word contained single-quote or double-quote characters.

The'$' character is used to introduce parameter expansion, command substitution, or arithmetic evaluation. If anunquoted'$' is followed by a character that is not one of the following:

the result is unspecified.

2.6.1Tilde Expansion

A "tilde-prefix" consists of an unquoted <tilde> character at the beginning of a word, followed by all of the characterspreceding the first unquoted <slash> in the word, or all the characters in the word if there is no <slash>. In anassignment (see XBDVariable Assignment), multiple tilde-prefixes can beused: at the beginning of the word (that is, following the <equals-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 noneof the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the <tilde> are treated as apossible login name from the user database. A portable login name cannot contain characters outside the set given in thedescription of theLOGNAME environment variable in XBDOther EnvironmentVariables. If the login name is null (that is, the tilde-prefix contains only the tilde), the tilde-prefix is replaced bythe value of the variableHOME. IfHOME is unset, the results are unspecified. Otherwise, the tilde-prefix shall bereplaced by a pathname of the initial working directory associated with the login name obtained using thegetpwnam() function as defined in the System Interfaces volume of POSIX.1-2017. If thesystem does not recognize the login name, the results are undefined.

The pathname resulting from tilde expansion shall be treated as if quoted to prevent it being altered by field splitting andpathname expansion.

2.6.2Parameter Expansion

The format for parameter expansion is as follows:

${expression}

whereexpression 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 variableexpansions, shall not be examined in determining the matching'}'.

The simplest form for parameter expansion is:

${parameter}

The value, if any, ofparameter shall be substituted.

The parameter name or symbol can be enclosed in braces, which are optional except for positional parameters with more than onedigit or whenparameter is a name and is followed by a character that could be interpreted as part of the name. The matchingclosing brace shall be determined by counting brace levels, skipping over enclosed quoted strings, and command substitutions.

If the parameter is not enclosed in braces, and is a name, the expansion shall use the longest valid name (see XBDName), whether or not the variable represented by that name exists. Otherwise,the parameter is a single-character symbol, and behavior is unspecified if that character is neither a digit nor one of the specialparameters (seeSpecial Parameters).

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 ofword is needed (based on the state ofparameter, as described below),word shall be subjected to tildeexpansion, parameter expansion, command substitution, and arithmetic expansion. Ifword is not needed, it shall not beexpanded. The'}' character that delimits the following parameter expansion modifications shall be determined as describedpreviously in this section and inDouble-Quotes.

${parameter:-[word]}
Use Default Values. Ifparameter is unset or null, the expansion ofword (or an empty string ifword is omitted) shall be substituted; otherwise, the value ofparameter shall be substituted.
${parameter:=[word]}
Assign Default Values. Ifparameter is unset or null, the expansion ofword (or an empty string ifword is omitted) shall be assigned toparameter. In all cases, the final value ofparameter shall besubstituted. Only variables, not positional parameters or special parameters, can be assigned in this way.
${parameter:?[word]}
Indicate Error if Null or Unset. Ifparameter is unset or null, the expansion ofword (or a messageindicating it is unset ifword is omitted) shall be written to standard error and the shell exits with a non-zero exitstatus. Otherwise, the value ofparameter shall be substituted. An interactive shell need not exit.
${parameter:+[word]}
Use Alternative Value. Ifparameter is unset or null, null shall be substituted; otherwise, the expansion ofword (or an empty string ifword is omitted) shall be substituted.

In the parameter expansions shown previously, use of the <colon> in the format shall result in a test for a parameter thatis unset or null; omission of the <colon> shall result in a test for a parameter that is only unset. If parameter is'#' and the colon is omitted, the application shall ensure thatword is specified (this is necessary to avoidambiguity with the string length expansion). The following table summarizes the effect of the <colon>:

 

parameter
Set and Not Null

parameter
Set But Null

parameter
Unset

${parameter:-word}

substituteparameter

substituteword

substituteword

${parameter-word}

substituteparameter

substitute null

substituteword

${parameter:=word}

substituteparameter

assignword

assignword

${parameter=word}

substituteparameter

substitute null

assignword

${parameter:?word}

substituteparameter

error, exit

error, exit

${parameter?word}

substituteparameter

substitute null

error, exit

${parameter:+word}

substituteword

substitute null

substitute null

${parameter+word}

substituteword

substituteword

substitute 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.

${#parameter}
String Length. The length in characters of the value ofparameter shall be substituted. Ifparameter is'*' or'@', the result of the expansion is unspecified. Ifparameter is unset andset-u is in effect, the expansion shall fail.

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation(seePattern Matching Notation), rather than regular expression notation, shall be used to evaluate thepatterns. Ifparameter is'#','*', or'@', the result of the expansion is unspecified. Ifparameter is unset andset-u is in effect, the expansion shall fail. Enclosing the fullparameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted,whereas quoting characters within the braces shall have this effect. In each variety, ifword is omitted, the empty patternshall be used.

${parameter%[word]}
Remove Smallest Suffix Pattern. Theword shall be expanded to produce a pattern. The parameter expansion shallthen result inparameter, with the smallest portion of the suffix matched by thepattern deleted. If present,word shall not begin with an unquoted'%'.
${parameter%%[word]}
Remove Largest Suffix Pattern. Theword shall be expanded to produce a pattern. The parameter expansion shallthen result inparameter, with the largest portion of the suffix matched by thepattern deleted.
${parameter#[word]}
Remove Smallest Prefix Pattern. Theword shall be expanded to produce a pattern. The parameter expansion shallthen result inparameter, with the smallest portion of the prefix matched by thepattern deleted. If present,word shall not begin with an unquoted'#'.
${parameter##[word]}
Remove Largest Prefix Pattern. Theword shall be expanded to produce a pattern. The parameter expansion shallthen result inparameter, with the largest portion of the prefix matched by thepattern deleted.

The following sections are informative.
Examples
${parameter}
In this example, the effects of omitting braces are demonstrated.
a=1set 2echo ${a}b-$ab-${1}0-${10}-$101b--20--20
${parameter-word}
This example demonstrates the difference between unset and set to the empty string, as well as the rules for finding the delimitingclose brace.
foo=asdfecho ${foo-bar}xyz}asdfxyz}foo=echo ${foo-bar}xyz}xyz}unset fooecho ${foo-bar}xyz}barxyz}
${parameter:-word}
In this example,ls is executed only ifx is null or unset. (The $(ls) command substitution notation is explained inCommandSubstitution.)
${x:-$(ls)}
${parameter:=word}
unset Xecho ${X:=abc}abc
${parameter:?word}
unset posixecho ${posix:?}sh: posix: parameter null or not set
${parameter:+word}
set a b cecho ${3:+posix}posix
${#parameter}
HOME=/usr/posixecho ${#HOME}10
${parameter%word}
x=file.cecho ${x%.c}.ofile.o
${parameter%%word}
x=posix/src/stdecho ${x%%/*}posix
${parameter#word}
x=$HOME/src/cmdecho ${x#$HOME}/src/cmd
${parameter##word}
x=/one/two/threeecho ${x##*/}three

The double-quoting of patterns is different depending on where the double-quotes are placed:

"${x#*}"
The <asterisk> is a pattern character.
${x#"*"}
The literal <asterisk> is quoted and not special.
End of informative text.

2.6.3Command Substitution

Command substitution allows the output of a command to be substituted in place of the command name itself. Command substitutionshall occur when the command is enclosed as follows:

$(command)

or (backquoted version):

`command`

The shell shall expand the command substitution by executingcommand in a subshell environment (seeShell Execution Environment) and replacing the command substitution (the text ofcommand plus theenclosing"$()" 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 shall not be removed;however, they may be treated as field delimiters and eliminated during field splitting, depending on the value ofIFS andquoting that is in effect. If the output contains any null bytes, the behavior is unspecified.

Within the backquoted style of command substitution, <backslash> shall retain its literal meaning, except when followedby:'$','`', or <backslash>. The search for the matching backquote shall be satisfied by the firstunquoted non-escaped backquote; during this search, if a non-escaped backquote is encountered within a shell comment, ahere-document, an embedded command substitution of the $(command) form, or a quoted string, undefined results occur. Asingle-quoted or double-quoted string that begins, but does not end, within the"`...`" sequence produces undefinedresults.

With the $(command) form, all characters following the open parenthesis to the matching closing parenthesis constitutethecommand. Any valid shell script can be used forcommand, except a script consisting solely of redirections whichproduces unspecified results.

The results of command substitution shall not be processed for further tilde expansion, parameter expansion, commandsubstitution, or arithmetic expansion. If a command substitution occurs inside double-quotes, field splitting and pathnameexpansion shall not be performed on the results of the substitution.

Command substitution can be nested. To specify nesting within the backquoted version, the application shall precede the innerbackquotes with <backslash> characters; for example:

\`command\`

The syntax of the shell command language has an ambiguity for expansions beginning with"$((", which can introduce anarithmetic expansion or a command substitution that starts with a subshell. Arithmetic expansion has precedence; that is, the shellshall first determine whether it can parse the expansion as an arithmetic expansion and shall only parse the expansion as a commandsubstitution if it determines that it cannot parse the expansion as an arithmetic expansion. The shell need not evaluate nestedexpansions when performing this determination. If it encounters the end of input without already having determined that it cannotparse the expansion as an arithmetic expansion, the shell shall treat the expansion as an incomplete arithmetic expansion andreport a syntax error. A conforming application shall ensure that it separates the"$(" and'(' into two tokens(that is, separate them with white space) in a command substitution that starts with a subshell. For example, a commandsubstitution containing a single subshell could be written as:

$( (command) )

2.6.4Arithmetic Expansion

Arithmetic expansion provides a mechanism for evaluating an arithmetic expression and substituting its value. The format forarithmetic expansion shall be as follows:

$((expression))

The expression shall be treated as if it were in double-quotes, except that a double-quote inside the expression is not treatedspecially. The shell shall expand all tokens in the expression for parameter expansion, command substitution, and quoteremoval.

Next, the shell shall treat this as an arithmetic expression and substitute the value of the expression. The arithmeticexpression shall be processed according to the rules given inArithmeticPrecision and Operations, with the following exceptions:

All changes to variables in an arithmetic expression shall be in effect after the arithmetic expansion, as in the parameterexpansion"${x=value}".

If the shell variablex contains a value that forms a valid integer constant, optionally including a leading<plus-sign> or <hyphen-minus>, then the arithmetic expansions"$((x))" and"$(($x))" shall return thesame value.

As an extension, the shell may recognize arithmetic expressions beyond those listed. The shell may use a signed integer typewith a rank larger than the rank ofsigned long. The shell may use a real-floating type instead ofsigned long aslong as it does not affect the results in cases where there is no overflow. If the expression is invalid, or the contents of ashell variable used in the expression are not recognized by the shell, the expansion fails and the shell shall write a diagnosticmessage to standard error indicating the failure.


The following sections are informative.
Examples

A simple example using arithmetic expansion:

# repeat a command 100 timesx=100while [ $x -gt 0 ]docommand   x=$(($x-1))done
End of informative text.

2.6.5Field Splitting

After parameter expansion (Parameter Expansion), command substitution (Command Substitution), and arithmetic expansion (Arithmetic Expansion), theshell shall scan the results of expansions and substitutions that did not occur in double-quotes for field splitting and multiplefields can result.

The shell shall treat each character of theIFS as a delimiter and use the delimiters as field terminators to split theresults of parameter expansion, command substitution, and arithmetic expansion into fields.

  1. If the value ofIFS is a <space>, <tab>, and <newline>, or if it is unset, any sequence of<space>, <tab>, or <newline> characters at the beginning or end of the input shall be ignored and any sequence ofthose characters within the input shall delimit a field. For example, the input:

    <newline><space><tab>foo<tab><tab>bar<space>

    yields two fields,foo andbar.

  2. If the value ofIFS is null, no field splitting shall be performed.

  3. Otherwise, the following rules shall be applied in sequence. The term "IFS white space" is used to mean any sequence(zero or more instances) of white-space characters that are in theIFS value (for example, ifIFS contains<space>/ <comma>/ <tab>, any sequence of <space> and <tab> characters is consideredIFS whitespace).

    1. IFS white space shall be ignored at the beginning and end of the input.

    2. Each occurrence in the input of anIFS character that is notIFS white space, along with any adjacentIFSwhite space, shall delimit a field, as described previously.

    3. Non-zero-lengthIFS white space shall delimit a field.

2.6.6Pathname Expansion

After field splitting, ifset-f is not in effect, each field in the resulting command lineshall be expanded using the algorithm described inPattern Matching Notation, qualified by the rules inPatterns Used for Filename Expansion.

2.6.7Quote Removal

The quote characters ( <backslash>, single-quote, and double-quote) that were present in the original word shall beremoved unless they have themselves been quoted.

2.7Redirection

Redirection is used to open and close files for the current shell execution environment (seeShellExecution Environment) or for any command. Redirection operators can be used with numbers representing file descriptors (seeXBDFile Descriptor) as described below.

The overall format used for redirection is:

[n]redir-op word

The numbern is an optional decimal number designating the file descriptor number; the application shall ensure it isdelimited from any preceding text and immediately precede the redirection operatorredir-op. Ifn is quoted, thenumber shall not be recognized as part of the redirection expression. For example:

echo \2>a

writes the character 2 into filea. If any part ofredir-op is quoted, no redirection expression is recognized.For example:

echo 2\>a

writes the characters 2>a to standard output. The optional number, redirection operator, andword shall notappear in the arguments provided to the command to be executed (if any).

Open files are represented by decimal numbers starting with zero. The largest possible value is implementation-defined; however,all implementations shall support at least 0 to 9, inclusive, for use by the application. These numbers are called "filedescriptors". The values 0, 1, and 2 have special meaning and conventional uses and are implied by certain redirection operations;they are referred to asstandard input,standard output, andstandard error, respectively. Programs usuallytake their input from standard input, and write output on standard output. Error messages are usually written on standard error.The redirection operators can be preceded by one or more digits (with no intervening <blank> characters allowed) to designatethe file descriptor number.

If the redirection operator is"<<" or"<<-", the word that follows the redirection operatorshall be subjected to quote removal; it is unspecified whether any of the other expansions occur. For the other redirectionoperators, the word that follows the redirection operator shall be subjected to tilde expansion, parameter expansion, commandsubstitution, arithmetic expansion, and quote removal. Pathname expansion shall not be performed on the word by a non-interactiveshell; an interactive shell may perform it, but shall do so only when the expansion would result in one word.

If more than one redirection operator is specified with a command, the order of evaluation is from beginning to end.

A failure to open or create a file shall cause a redirection to fail.

2.7.1Redirecting Input

Input redirection shall cause the file whose name results from the expansion ofword to be opened for reading on thedesignated file descriptor, or standard input if the file descriptor is not specified.

The general format for redirecting input is:

[n]<word

where the optionaln represents the file descriptor number. If the number is omitted, the redirection shall refer tostandard input (file descriptor 0).

2.7.2Redirecting Output

The two general formats for redirecting output are:

[n]>word[n]>|word

where the optionaln represents the file descriptor number. If the number is omitted, the redirection shall refer tostandard output (file descriptor 1).

Output redirection using the'>' format shall fail if thenoclobber option is set (see the description ofset-C) and the file named by the expansion ofword exists and is a regular file. Otherwise,redirection using the'>' or">|" formats shall cause the file whose name results from the expansion ofword to be created and opened for output on the designated file descriptor, or standard output if none is specified. If thefile does not exist, it shall be created; otherwise, it shall be truncated to be an empty file after being opened.

2.7.3Appending Redirected Output

Appended output redirection shall cause the file whose name results from the expansion of word to be opened for output on thedesignated file descriptor. The file is opened as if theopen() function as defined inthe System Interfaces volume of POSIX.1-2017 was called with the O_APPEND flag. If the file does not exist, it shall becreated.

The general format for appending redirected output is as follows:

[n]>>word

where the optionaln represents the file descriptor number. If the number is omitted, the redirection refers to standardoutput (file descriptor 1).

2.7.4Here-Document

The redirection operators"<<" and"<<-" both allow redirection of subsequent lines read by theshell to the input of a command. The redirected lines are known as a "here-document".

The here-document shall be treated as a single word that begins after the next <newline> and continues until there is aline containing only the delimiter and a <newline>, with no <blank> characters in between. Then the next here-documentstarts, if there is one. The format is as follows:

[n]<<word    here-documentdelimiter

where the optionaln represents the file descriptor number. If the number is omitted, the here-document refers tostandard input (file descriptor 0). It is unspecified whether the file descriptor is opened as a regular file, a special file, or apipe. Portable applications cannot rely on the file descriptor being seekable (see XSHlseek).

If any part ofword is quoted, the delimiter shall be formed by performing quote removal onword, and thehere-document lines shall not be expanded. Otherwise, the delimiter shall be theword itself.

If no part ofword is quoted, all lines of the here-document shall be expanded for parameter expansion, commandsubstitution, and arithmetic expansion. In this case, the <backslash> in the input behaves as the <backslash> insidedouble-quotes (seeDouble-Quotes). However, the double-quote character (' )' shall not betreated specially within a here-document, except when the double-quote appears within"$()","``", or"${}".

If the redirection operator is"<<-", all leading <tab> characters shall be stripped from input lines andthe line containing the trailing delimiter. If more than one"<<" or"<<-" operator is specified on aline, the here-document associated with the first operator shall be supplied first by the application and shall be read first bythe shell.

When a here-document is read from a terminal device and the shell is interactive, it shall write the contents of the variablePS2, processed as described inShell Variables, to standard error before reading each line ofinput until the delimiter has been recognized.


The following sections are informative.
Examples

An example of a here-document follows:

cat <<eof1; cat <<eof2Hi,eof1Helene.eof2
End of informative text.

2.7.5Duplicating an Input File Descriptor

The redirection operator:

[n]<&word

shall duplicate one input file descriptor from another, or shall close one. Ifword evaluates to one or more digits, thefile descriptor denoted byn, or standard input ifn is not specified, shall be made to be a copy of the filedescriptor denoted byword; if the digits inword do not represent a file descriptor already open for input, aredirection error shall result; seeConsequences of Shell Errors. Ifword evaluates to'-', file descriptorn, or standard input ifn is not specified, shall be closed. Attempts to close a filedescriptor that is not open shall not constitute an error. Ifword evaluates to something else, the behavior isunspecified.

2.7.6Duplicating an Output File Descriptor

The redirection operator:

[n]>&word

shall duplicate one output file descriptor from another, or shall close one. Ifword evaluates to one or more digits, thefile descriptor denoted byn, or standard output ifn is not specified, shall be made to be a copy of the filedescriptor denoted byword; if the digits inword do not represent a file descriptor already open for output, aredirection error shall result; seeConsequences of Shell Errors. Ifword evaluates to'-', file descriptorn, or standard output ifn is not specified, is closed. Attempts to close a filedescriptor that is not open shall not constitute an error. Ifword evaluates to something else, the behavior isunspecified.

2.7.7Open File Descriptors for Reading and Writing

The redirection operator:

[n]<>word

shall cause the file whose name is the expansion ofword to be opened for both reading and writing on the file descriptordenoted byn, or standard input ifn is not specified. If the file does not exist, it shall be created.

2.8Exit Status and Errors

2.8.1Consequences of Shell Errors

Certain errors shall cause the shell to write a diagnostic message to standard error and exit as shown in the followingtable:

Error

Non-Interactive
Shell

Interactive Shell

Shell Diagnostic
Message Required

Shell language syntax error

shall exit

shall not exit

yes

Special built-in utility error

shall exit

shall not exit

no1

Other utility (not a special
built-in) error

shall not exit

shall not exit

no2

Redirection error with
special built-in utilities

shall exit

shall not exit

yes

Redirection error with
compound commands

may exit3

shall not exit

yes

Redirection error with
function execution

may exit3

shall not exit

yes

Redirection error with other
utilities (not special built-ins)

shall not exit

shall not exit

yes

Variable assignment error

shall exit

shall not exit

yes

Expansion error

shall exit

shall not exit

yes

Command not found

may exit

shall not exit

yes

Notes:
  1. Although special built-ins are part of the shell, a diagnostic message written by a special built-in is not considered to be ashell diagnostic message, and can be redirected like any other utility.

  2. The shell is not required to write a diagnostic message, but the utility itself shall write a diagnostic message if required todo so.

  3. A future version of this standard may require the shell to not exit in this condition.

An expansion error is one that occurs when the shell expansions define inwordexp are carried out (for example,"${x!y}", because'!' is not avalid operator); an implementation may treat these as syntax errors if it is able to detect them during tokenization, rather thanduring expansion.

If any of the errors shown as "shall exit" or "may exit" occur in a subshell environment, the shell shall (respectively,may) exit from the subshell environment with a non-zero status and continue in the environment from which that subshell environmentwas invoked.

In all of the cases shown in the table where an interactive shell is required not to exit, the shell shall not perform anyfurther processing of the command in which the error occurred.

2.8.2Exit Status for Commands

Each command has an exit status that can influence the behavior of other shell commands. The exit status of commands that arenot utilities is documented in this section. The exit status of the standard utilities is documented in their respectivesections.

If a command is not found, the exit status shall be 127. If the command name is found, but it is not an executable utility, theexit status shall be 126. Applications that invoke utilities without using the shell should use these exit status values to reportsimilar errors.

If a command fails during word expansion or redirection, its exit status shall be between 1 and 125 inclusive.

Internally, for purposes of deciding whether a command exits with a non-zero exit status, the shell shall recognize the entirestatus value retrieved for the command by the equivalent of thewait() functionWEXITSTATUS macro (as defined in the System Interfaces volume of POSIX.1-2017). When reporting the exit status with the specialparameter'?', the shell shall report the full eight bits of exit status available. The exit status of a command thatterminated because it received a signal shall be reported as greater than 128.

2.9Shell Commands

This section describes the basic structure of shell commands. The following command descriptions each describe a format of thecommand that is only used to aid the reader in recognizing the command type, and does not formally represent the syntax. Inparticular, the representations include spacing between tokens in some places where <blank>s would not be necessary (when oneof the tokens is an operator). Each description discusses the semantics of the command; for a formal definition of the commandlanguage, consultShell Grammar.

Acommand is one of the following:

Unless otherwise stated, the exit status of a command shall be that of the last simple command executed by the command. Thereshall be no limit on the size of any shell command other than that imposed by the underlying system (memory constraints, {ARG_MAX},and so on).

2.9.1Simple Commands

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed bywords and redirections, terminated by a control operator.

When a given simple command is required to be executed (that is, when any conditional construct such as an AND-OR list or acase statement has not bypassed the simple command), the following expansions, assignments, and redirections shall all beperformed from the beginning of the command text to the end:

  1. The words that are recognized as variable assignments or redirections according toShell GrammarRules are saved for processing in steps 3 and 4.

  2. The words that are not variable assignments or redirections shall be expanded. If any fields remain following their expansion,the first field shall be considered the command name and remaining fields are the arguments for the command.

  3. Redirections shall be performed as described inRedirection.

  4. Each variable assignment shall be expanded for tilde expansion, parameter expansion, command substitution, arithmetic expansion,and quote removal prior to assigning the value.

In the preceding list, the order of steps 3 and 4 may be reversed if no command name results from step 2 or if the command namematches the name of a special built-in utility; seeSpecial Built-In Utilities.

Variable assignments shall be performed as follows:

If any of the variable assignments attempt to assign a value to a variable for which thereadonly attribute is set in thecurrent shell environment (regardless of whether the assignment is made in that environment), a variable assignment error shalloccur. SeeConsequences of Shell Errors for the consequences of these errors.

If there is no command name, any redirections shall be performed in a subshell environment; it is unspecified whether thissubshell environment is the same one as that used for a command substitution within the command. (To affect the current executionenvironment, see theexec special built-in.) If any of the redirections performed in the current shellexecution environment fail, the command shall immediately fail with an exit status greater than zero, and the shell shall write anerror message indicating the failure. SeeConsequences of Shell Errors for the consequences of thesefailures on interactive and non-interactive shells.

If there is a command name, execution shall continue as described inCommand Search and Execution. If there is no command name, but the command contained a command substitution, the command shall complete with the exit status ofthe last command substitution performed. Otherwise, the command shall complete with a zero exit status.

Command Search and Execution

If a simple command results in a command name and an optional list of arguments, the following actions shall be performed:

  1. If the command name does not contain any <slash> characters, the first successful step in the following sequence shalloccur:

    1. If the command name matches the name of a special built-in utility, that special built-in utility shall be invoked.

    2. If the command name matches the name of a utility listed in the following table, the results are unspecified.


      alloc
      autoload
      bind
      bindkey
      builtin
      bye
      caller
      cap
      chdir
      clone
       


      comparguments
      compcall
      compctl
      compdescribe
      compfiles
      compgen
      compgroups
      complete
      compquote
      comptags
       


      comptry
      compvalues
      declare
      dirs
      disable
      disown
      dosh
      echotc
      echoti
      help
       


      history
      hist
      let
      local
      login
      logout
      map
      mapfile
      popd
      print
       


      pushd
      readarray
      repeat
      savehistory
      source
      shopt
      stop
      suspend
      typeset
      whence
       

    3. If the command name matches the name of a function known to this shell, the function shall be invoked as described inFunction Definition Command. If the implementation has provided a standard utility in the form of a function,it shall not be recognized at this point. It shall be invoked in conjunction with the path search in step 1e.

    4. If the command name matches the name[XSI][Option Start]  of thetype orulimit utility, or[Option End] of a utility listed in the following table, that utility shall be invoked.


      alias
      bg
      cd
      command
       


      false
      fc
      fg
      getopts
       


      hash
      jobs
      kill
      newgrp
       


      pwd
      read
      true
      umask
       


      unalias
      wait
       

    5. Otherwise, the command shall be searched for using thePATH environment variable as described in XBDEnvironment Variables :

      1. If the search is successful:

        1. If the system has implemented the utility as a regular built-in or as a shell function, it shall be invoked at this point in thepath search.

        2. Otherwise, the shell executes the utility in a separate utility environment (seeShell ExecutionEnvironment) with actions equivalent to calling theexecl() function as definedin the System Interfaces volume of POSIX.1-2017 with thepath argument set to the pathname resulting from the search,arg0 set to the command name, and the remainingexecl() arguments set to thecommand arguments (if any) and the null terminator.

          If theexecl() function fails due to an error equivalent to the [ENOEXEC] errordefined in the System Interfaces volume of POSIX.1-2017, the shell shall execute a command equivalent to having a shell invokedwith the pathname resulting from the search as its first operand, with any remaining arguments passed to the new shell, except thatthe value of"$0" in the new shell may be set to the command name. If the executable file is not a text file, the shellmay bypass this command execution. In this case, it shall write an error message, and shall return an exit status of 126.

          It is unspecified whether environment variables that were passed to the shell when it was invoked, but were not used toinitialize shell variables (seeShell Variables) because they had invalid names, are included in theenvironment passed toexecl() and (ifexecl() fails as described above) to the new shell.

        Once a utility has been searched for and found (either as a result of this specific search or as part of an unspecified shellstart-up activity), an implementation may remember its location and need not search for the utility again unless thePATHvariable has been the subject of an assignment. If the remembered location fails for a subsequent invocation, the shell shallrepeat the search to find the new location for the utility, if any.

      2. If the search is unsuccessful, the command shall fail with an exit status of 127 and the shell shall write an error message.

  2. If the command name contains at least one <slash>, the shell shall execute the utility in a separate utility environmentwith actions equivalent to calling theexecl() function defined in the SystemInterfaces volume of POSIX.1-2017 with thepath andarg0 arguments set to the command name, and the remainingexecl() arguments set to the command arguments (if any) and the null terminator.

    If theexecl() function fails due to an error equivalent to the [ENOEXEC] error,the shell shall execute a command equivalent to having a shell invoked with the command name as its first operand, with anyremaining arguments passed to the new shell. If the executable file is not a text file, the shell may bypass this commandexecution. In this case, it shall write an error message and shall return an exit status of 126.

    It is unspecified whether environment variables that were passed to the shell when it was invoked, but were not used toinitialize shell variables (seeShell Variables) because they had invalid names, are included in theenvironment passed toexecl() and (ifexecl() fails as described above) to the new shell.

If the utility would be executed with file descriptor 0, 1, or 2 closed, implementations may execute the utility with the filedescriptor open to an unspecified file. If a standard utility or a conforming application is executed with file descriptor 0 notopen for reading or with file descriptor 1 or 2 not open for writing, the environment in which the utility or application isexecuted shall be deemed non-conforming, and consequently the utility or application might not behave as described in thisstandard.

2.9.2Pipelines

Apipeline is a sequence of one or more commands separated by the control operator'|'. For each command butthe last, the shell shall connect the standard output of the command to the standard input of the next command as if by creating apipe and passing the write end of the pipe as the standard output of the command and the read end of the pipe as the standard inputof the next command.

The format for a pipeline is:

[!]command1[|command2...]

If the pipeline begins with the reserved word! andcommand1 is a subshell command, the application shall ensurethat the( operator at the beginning ofcommand1 is separated from the! by one or more <blank>characters. The behavior of the reserved word! immediately followed by the( operator is unspecified.

The standard output ofcommand1 shall be connected to the standard input ofcommand2. The standard input, standardoutput, or both of a command shall be considered to be assigned by the pipeline before any redirection specified by redirectionoperators that are part of the command (seeRedirection).

If the pipeline is not in the background (seeAsynchronous Lists), the shell shall wait for thelast command specified in the pipeline to complete, and may also wait for all commands to complete.

Exit Status

If the pipeline does not begin with the! reserved word, the exit status shall be the exit status of the last commandspecified in the pipeline. Otherwise, the exit status shall be the logical NOT of the exit status of the last command. That is, ifthe last command returns zero, the exit status shall be 1; if the last command returns greater than zero, the exit status shall bezero.

2.9.3Lists

AnAND-OR list is a sequence of one or more pipelines separated by the operators"&&" and"||".

Alist is a sequence of one or more AND-OR lists separated by the operators';' and'&'.

The operators"&&" and"||" shall have equal precedence and shall be evaluated with leftassociativity. For example, both of the following commands write solelybar to standard output:

false && echo foo || echo bartrue || echo foo && echo bar

A';' separator or a';' or <newline> terminator shall cause the preceding AND-OR list to be executedsequentially; an'&' separator or terminator shall cause asynchronous execution of the preceding AND-OR list.

The term "compound-list" is derived from the grammar inShell Grammar; it is equivalent to asequence oflists, separated by <newline> characters, that can be preceded or followed by an arbitrary number of<newline> characters.


The following sections are informative.
Examples

The following is an example that illustrates <newline> characters in compound-lists:

while    # a couple of <newline>s
# a list date && who || ls; cat file # a couple of <newline>s
# another list wc file > output & true
do # 2 lists ls cat filedone
End of informative text.

Asynchronous Lists

If a command is terminated by the control operator <ampersand> ('&' ), the shell shall execute the commandasynchronously in a subshell. This means that the shell shall not wait for the command to finish before executing the nextcommand.

The format for running a command in the background is:

command1&[command2& ...]

If job control is disabled (seeset,-m), the standard input for an asynchronous list, beforeany explicit redirections are performed, shall be considered to be assigned to a file that has the same properties as/dev/null. This shall not happen if job control is enabled. In all cases, explicit redirection of standard input shalloverride this activity.

When an element of an asynchronous list (the portion of the list ended by an <ampersand>, such ascommand1, above)is started by the shell, the process ID of the last command in the asynchronous list element shall become known in the currentshell execution environment; seeShell Execution Environment. This process ID shall remain knownuntil:

  1. The command terminates and the application waits for the process ID.

  2. Another asynchronous list is invoked before"$!" (corresponding to the previous asynchronous list) is expanded in thecurrent execution environment.

The implementation need not retain more than the {CHILD_MAX} most recent entries in its list of known process IDs in the currentshell execution environment.

Exit Status

The exit status of an asynchronous list shall be zero.

Sequential Lists

Commands that are separated by a <semicolon> (';' ) shall be executed sequentially.

The format for executing commands sequentially shall be:

command1[;command2]...

Each command shall be expanded and executed in the order specified.

Exit Status

The exit status of a sequential list shall be the exit status of the last command in the list.

AND Lists

The control operator"&&" denotes an AND list. The format shall be:

command1[&&command2]...

Firstcommand1 shall be executed. If its exit status is zero,command2 shall be executed, and so on, until acommand has a non-zero exit status or there are no more commands left to execute. The commands are expanded only if they areexecuted.

Exit Status

The exit status of an AND list shall be the exit status of the last command that is executed in the list.

OR Lists

The control operator"||" denotes an OR List. The format shall be:

command1[||command2]...

First,command1 shall be executed. If its exit status is non-zero,command2 shall be executed, and so on, until acommand has a zero exit status or there are no more commands left to execute.

Exit Status

The exit status of an OR list shall be the exit status of the last command that is executed in the list.

2.9.4Compound Commands

The shell has several programming constructs that are "compound commands", which provide control flow for commands. Each ofthese compound commands has a reserved word or control operator at the beginning, and a corresponding terminator reserved word oroperator at the end. In addition, each can be followed by redirections on the same line as the terminator. Each redirection shallapply to all the commands within the compound command that do not explicitly override that redirection.

Grouping Commands

The format for grouping commands is as follows:

compound-list )
Executecompound-list in a subshell environment; seeShell Execution Environment. Variableassignments and built-in commands that affect the environment shall not remain in effect after the list finishes.

If a character sequence beginning with"((" would be parsed by the shell as an arithmetic expansion if preceded by a'$', shells which implement an extension whereby"((expression))" is evaluated as an arithmeticexpression may treat the"((" as introducing as an arithmetic evaluation instead of a grouping command. A conformingapplication shall ensure that it separates the two leading'(' characters with white space to prevent the shell fromperforming an arithmetic evaluation.

compound-list ; }
Executecompound-list in the current process environment. The semicolon shown here is an example of a control operatordelimiting the} reserved word. Other delimiters are possible, as shown inShell Grammar; a<newline> is frequently used.
Exit Status

The exit status of a grouping command shall be the exit status ofcompound-list.

The for Loop

Thefor loop shall execute a sequence of commands for each member in a list ofitems. Thefor loop requiresthat the reserved wordsdo anddone be used to delimit the sequence of commands.

The format for thefor loop is as follows:

forname[in[word...]]docompound-listdone

First, the list of words followingin shall be expanded to generate a list of items. Then, the variablename shallbe set to each item, in turn, and thecompound-list executed each time. If no items result from the expansion, thecompound-list shall not be executed. Omitting:

inword...

shall be equivalent to:

in "$@"
Exit Status

The exit status of afor command shall be the exit status of the last command that executes. If there are no items, theexit status shall be zero.

Case Conditional Construct

The conditional constructcase shall execute thecompound-list corresponding to the first one of severalpatterns (seePattern Matching Notation) that is matched by the string resulting from the tildeexpansion, parameter expansion, command substitution, arithmetic expansion, and quote removal of the given word. The reserved wordin shall denote the beginning of the patterns to be matched. Multiple patterns with the samecompound-list shall bedelimited by the'|' symbol. The control operator')' terminates a list of patterns corresponding to a givenaction. Thecompound-list for each list of patterns, with the possible exception of the last, shall be terminated with";;". Thecase construct terminates with the reserved wordesac (case reversed).

The format for thecase construct is as follows:

casewordin[(]pattern1)compound-list;;[[(]pattern[|pattern]... )compound-list;;]...[[(]pattern[|pattern]... )compound-list]esac

The";;" is optional for the lastcompound-list.

In order from the beginning to the end of thecase statement, eachpattern that labels acompound-listshall be subjected to tilde expansion, parameter expansion, command substitution, and arithmetic expansion, and the result of theseexpansions shall be compared against the expansion ofword, according to the rules described inPatternMatching Notation (which also describes the effect of quoting parts of the pattern). After the first match, no more patternsshall be expanded, and thecompound-list shall be executed. The order of expansion and comparison of multiplepatterns that label acompound-list statement is unspecified.

Exit Status

The exit status ofcase shall be zero if no patterns are matched. Otherwise, the exit status shall be the exit status ofthe last command executed in thecompound-list.

The if Conditional Construct

Theif command shall execute acompound-list and use its exit status to determine whether to execute anothercompound-list.

The format for theif construct is as follows:

ifcompound-listthencompound-list[elifcompound-listthencompound-list]...[elsecompound-list]fi

Theifcompound-list shall be executed; if its exit status is zero, thethencompound-list shall beexecuted and the command shall complete. Otherwise, eachelifcompound-list shall be executed, in turn, and if itsexit status is zero, thethencompound-list shall be executed and the command shall complete. Otherwise, theelsecompound-list shall be executed.

Exit Status

The exit status of theif command shall be the exit status of thethen orelsecompound-list thatwas executed, or zero, if none was executed.

The while Loop

Thewhile loop shall continuously execute onecompound-list as long as anothercompound-list has a zeroexit status.

The format of thewhile loop is as follows:

whilecompound-list-1docompound-list-2done

Thecompound-list-1 shall be executed, and if it has a non-zero exit status, thewhile command shall complete.Otherwise, thecompound-list-2 shall be executed, and the process shall repeat.

Exit Status

The exit status of thewhile loop shall be the exit status of the lastcompound-list-2 executed, or zero if nonewas executed.

The until Loop

Theuntil loop shall continuously execute onecompound-list as long as anothercompound-list has a non-zeroexit status.

The format of theuntil loop is as follows:

untilcompound-list-1docompound-list-2done

Thecompound-list-1 shall be executed, and if it has a zero exit status, theuntil command completes. Otherwise,thecompound-list-2 shall be executed, and the process repeats.

Exit Status

The exit status of theuntil loop shall be the exit status of the lastcompound-list-2 executed, or zero if nonewas executed.

2.9.5Function Definition Command

A function is a user-defined name that is used as a simple command to call a compound command with new positional parameters. Afunction is defined with a "function definition command".

The format of a function definition command is as follows:

fname( )compound-command[io-redirect...]

The function is namedfname; the application shall ensure that it is a name (see XBDName) and that it is not the name of a special built-in utility. Animplementation may allow other characters in a function name as an extension. The implementation shall maintain separate namespaces for functions and variables.

The argumentcompound-command represents a compound command, as described inCompoundCommands.

When the function is declared, none of the expansions inwordexp shall beperformed on the text incompound-command orio-redirect; all expansions shall be performed as normal each time thefunction is called. Similarly, the optionalio-redirect redirections and any variable assignments withincompound-command shall be performed during the execution of the function itself, not the function definition. SeeConsequences of Shell Errors for the consequences of failures of these operations on interactive andnon-interactive shells.

When a function is executed, it shall have the syntax-error properties described for special built-in utilities in the firstitem in the enumerated list at the beginning ofSpecial Built-In Utilities.

Thecompound-command shall be executed whenever the function name is specified as the name of a simple command (seeCommand Search and Execution). The operands to the command temporarily shall become the positionalparameters during the execution of thecompound-command; the special parameter'#' also shall be changed to reflectthe number of operands. The special parameter 0 shall be unchanged. When the function completes, the values of the positionalparameters and the special parameter'#' shall be restored to the values they had before the function was executed. If thespecial built-inreturn (seereturn) is executed in thecompound-command, the function completes and execution shall resume with the next command after the function call.

Exit Status

The exit status of a function definition shall be zero if the function was declared successfully; otherwise, it shall be greaterthan zero. The exit status of a function invocation shall be the exit status of the last command executed by the function.

2.10.Shell Grammar

The following grammar defines the Shell Command Language. This formal syntax shall take precedence over the preceding textsyntax description.

2.10.1Shell Grammar Lexical Conventions

The input language to the shell must be first recognized at the character level. The resulting tokens shall be classified bytheir immediate context according to the following rules (applied in order). These rules shall be used to determine what a"token" is that is subject to parsing at the token level. The rules for token recognition inTokenRecognition shall apply.

  1. If the token is an operator, the token identifier for that operator shall result.

  2. If the string consists solely of digits and the delimiter character is one of'<' or'>', the tokenidentifierIO_NUMBER shall be returned.

  3. Otherwise, the token identifierTOKEN results.

Further distinction onTOKEN is context-dependent. It may be that the sameTOKEN yieldsWORD, aNAME, anASSIGNMENT_WORD, or one of the reserved words below, dependent upon the context. Some of the productions inthe grammar below are annotated with a rule number from the following list. When aTOKEN is seen where one of thoseannotated productions could be used to reduce the symbol, the applicable rule shall be applied to convert the token identifier typeof theTOKEN to a token identifier acceptable at that point in the grammar. The reduction shall then proceed based upon thetoken identifier type yielded by the rule applied. When more than one rule applies, the highest numbered rule shall apply (which inturn may refer to another rule). (Note that except in rule 7, the presence of an'=' in the token has no effect.)

TheWORD tokens shall have the word expansion rules applied to them immediately before the associated command isexecuted, not at the time the command is parsed.

2.10.2Shell Grammar Rules

  1. [Command Name]

    When theTOKEN is exactly a reserved word, the token identifier for that reserved word shall result. Otherwise, the tokenWORD shall be returned. Also, if the parser is in any state where only a reserved word could be the next correct token,proceed as above.

    Note:
    Because at this point <quotation-mark> characters are retained in the token, quoted strings cannot be recognized asreserved words. This rule also implies that reserved words are not recognized except in certain positions in the input, such asafter a <newline> or <semicolon>; the grammar presumes that if the reserved word is intended, it is properly delimitedby the user, and does not attempt to reflect that requirement directly. Also note that line joining is done before tokenization, asdescribed inEscape Character (Backslash), so escaped <newline> characters are already removedat this point.

    Rule 1 is not directly referenced in the grammar, but is referred to by other rules, or applies globally.

  2. [Redirection to or from filename]

    The expansions specified inRedirection shall occur. As specified there, exactly one field can result(or the result is unspecified), and there are additional requirements on pathname expansion.

  3. [Redirection from here-document]

    Quote removal shall be applied to the word to determine the delimiter that is used to find the end of the here-document thatbegins after the next <newline>.

  4. [Case statement termination]

    When theTOKEN is exactly the reserved wordesac, the token identifier foresac shall result. Otherwise,the tokenWORD shall be returned.

  5. [NAME infor]

    When theTOKEN meets the requirements for a name (see XBDName), the token identifierNAME shall result. Otherwise, the tokenWORD shall be returned.

  6. [Third word offor andcase]

    1. [case only]

      When theTOKEN is exactly the reserved wordin, the token identifier forin shall result. Otherwise, thetokenWORD shall be returned.

    2. [for only]

      When theTOKEN is exactly the reserved wordin ordo, the token identifier forin ordo shallresult, respectively. Otherwise, the tokenWORD shall be returned.

    (For a. and b.: As indicated in the grammar, alinebreak precedes the tokensin anddo. If <newline>characters are present at the indicated location, it is the token after them that is treated in this fashion.)

  7. [Assignment preceding command name]

    1. [When the first word]

      If theTOKEN does not contain the character'=', rule 1 is applied. Otherwise, 7b shall be applied.

    2. [Not the first word]

      If theTOKEN contains an unquoted (as determined while applying rule 4 fromToken Recognition)<equals-sign> character that is not part of an embedded parameter expansion, command substitution, or arithmetic expansionconstruct (as determined while applying rule 5 fromToken Recognition):

      • If theTOKEN begins with'=', then rule 1 shall be applied.

      • If all the characters in theTOKEN preceding the first such <equals-sign> form a valid name (see XBDName), the tokenASSIGNMENT_WORD shall be returned.

      • Otherwise, it is unspecified whether rule 1 is applied orASSIGNMENT_WORD is returned.

      Otherwise, rule 1 shall be applied.

    Assignment to the name within a returnedASSIGNMENT_WORD token shall occur as specified inSimpleCommands.

  8. [NAME in function]

    When theTOKEN is exactly a reserved word, the token identifier for that reserved word shall result. Otherwise, when theTOKEN meets the requirements for a name, the token identifierNAME shall result. Otherwise, rule 7 applies.

  9. [Body of function]

    Word expansion and assignment shall never occur, even when required by the rules above, when this rule is being parsed. EachTOKEN that might either be expanded or have assignment applied to it shall instead be returned as a singleWORDconsisting only of characters that are exactly the token described inToken Recognition.


/* -------------------------------------------------------   The grammar symbols   ------------------------------------------------------- */%token  WORD%token  ASSIGNMENT_WORD%token  NAME%token  NEWLINE%token  IO_NUMBER
/* The following are the operators (see XBDOperator) containing more than one character. */

%token AND_IF OR_IF DSEMI/* '&&' '||' ';;' */
%token DLESS DGREAT LESSAND GREATAND LESSGREAT DLESSDASH/* '<<' '>>' '<&' '>&' '<>' '<<-' */
%token CLOBBER/* '>|' */
/* The following are the reserved words. */
%token If Then Else Elif Fi Do Done/* 'if' 'then' 'else' 'elif' 'fi' 'do' 'done' */
%token Case Esac While Until For/* 'case' 'esac' 'while' 'until' 'for' */
/* These are reserved words, not operator tokens, and are recognized when reserved words are recognized. */
%token Lbrace Rbrace Bang/* '{' '}' '!' */
%token In/* 'in' */
/* ------------------------------------------------------- The Grammar ------------------------------------------------------- */%start program%%program : linebreak complete_commands linebreak | linebreak ;complete_commands: complete_commands newline_list complete_command | complete_command ;complete_command : list separator_op | list ;list : list separator_op and_or | and_or ;and_or : pipeline | and_or AND_IF linebreak pipeline | and_or OR_IF linebreak pipeline ;pipeline : pipe_sequence | Bang pipe_sequence ;pipe_sequence : command | pipe_sequence '|' linebreak command ;command : simple_command | compound_command | compound_command redirect_list | function_definition ;compound_command : brace_group | subshell | for_clause | case_clause | if_clause | while_clause | until_clause ;subshell : '(' compound_list ')' ;compound_list : linebreak term | linebreak term separator ;term : term separator and_or | and_or ;for_clause : For name do_group | For name sequential_sep do_group | For name linebreak in sequential_sep do_group | For name linebreak in wordlist sequential_sep do_group ;name : NAME /* Apply rule 5 */ ;in : In /* Apply rule 6 */ ;wordlist : wordlist WORD | WORD ;case_clause : Case WORD linebreak in linebreak case_list Esac | Case WORD linebreak in linebreak case_list_ns Esac | Case WORD linebreak in linebreak Esac ;case_list_ns : case_list case_item_ns | case_item_ns ;case_list : case_list case_item | case_item ;case_item_ns : pattern ')' linebreak | pattern ')' compound_list | '(' pattern ')' linebreak | '(' pattern ')' compound_list ;case_item : pattern ')' linebreak DSEMI linebreak | pattern ')' compound_list DSEMI linebreak | '(' pattern ')' linebreak DSEMI linebreak | '(' pattern ')' compound_list DSEMI linebreak ;pattern : WORD /* Apply rule 4 */ | pattern '|' WORD /* Do not apply rule 4 */ ;if_clause : If compound_list Then compound_list else_part Fi | If compound_list Then compound_list Fi ;else_part : Elif compound_list Then compound_list | Elif compound_list Then compound_list else_part | Else compound_list ;while_clause : While compound_list do_group ;until_clause : Until compound_list do_group ;function_definition : fname '(' ')' linebreak function_body ;function_body : compound_command /* Apply rule 9 */ | compound_command redirect_list /* Apply rule 9 */ ;fname : NAME /* Apply rule 8 */ ;brace_group : Lbrace compound_list Rbrace ;do_group : Do compound_list Done /* Apply rule 6 */ ;simple_command : cmd_prefix cmd_word cmd_suffix | cmd_prefix cmd_word | cmd_prefix | cmd_name cmd_suffix | cmd_name ;cmd_name : WORD /* Apply rule 7a */ ;cmd_word : WORD /* Apply rule 7b */ ;cmd_prefix : io_redirect | cmd_prefix io_redirect | ASSIGNMENT_WORD | cmd_prefix ASSIGNMENT_WORD ;cmd_suffix : io_redirect | cmd_suffix io_redirect | WORD | cmd_suffix WORD ;redirect_list : io_redirect | redirect_list io_redirect ;io_redirect : io_file | IO_NUMBER io_file | io_here | IO_NUMBER io_here ;io_file : '<' filename | LESSAND filename | '>' filename | GREATAND filename | DGREAT filename | LESSGREAT filename | CLOBBER filename ;filename : WORD /* Apply rule 2 */ ;io_here : DLESS here_end | DLESSDASH here_end ;here_end : WORD /* Apply rule 3 */ ;newline_list : NEWLINE | newline_list NEWLINE ;linebreak : newline_list | /* empty */ ;separator_op : '&' | ';' ;separator : separator_op linebreak | newline_list ;sequential_sep : ';' linebreak | newline_list ;

2.11.Signals and Error Handling

If job control is disabled (see the description ofset-m) when the shell executes anasynchronous list, the commands in the list shall inherit from the shell a signal action of ignored (SIG_IGN) for the SIGINT andSIGQUIT signals. In all other cases, commands executed by the shell shall inherit the same signal actions as those inherited by theshell from its parent unless a signal action is modified by thetrap special built-in (seetrap)

When a signal for which a trap has been set is received while the shell is waiting for the completion of a utility executing aforeground command, the trap associated with that signal shall not be executed until after the foreground command has completed.When the shell is waiting, by means of thewait utility, for asynchronous commands tocomplete, the reception of a signal for which a trap has been set shall cause thewaitutility to return immediately with an exit status >128, immediately after which the trap associated with that signal shall betaken.

If multiple signals are pending for the shell for which there are associated trap actions, the order of execution of trapactions is unspecified.

2.12.Shell Execution Environment

A shell execution environment consists of the following:

Utilities other than the special built-ins (seeSpecial Built-In Utilities) shall be invoked in aseparate environment that consists of the following. The initial value of these objects shall be the same as that for the parentshell, except as noted below.

The environment of the shell process shall not be changed by the utility unless explicitly specified by the utility description(for example,cd andumask).

A subshell environment shall be created as a duplicate of the shell environment, except that signal traps that are not beingignored shall be set to the default action. Changes made to the subshell environment shall not affect the shell environment.Command substitution, commands that are grouped with parentheses, and asynchronous lists shall be executed in a subshellenvironment. Additionally, each command of a multi-command pipeline is in a subshell environment; as an extension, however, any orall commands in a pipeline may be executed in the current environment. All other commands shall be executed in the current shellenvironment.

2.13.Pattern Matching Notation

The pattern matching notation described in this section is used to specify patterns for matching strings in the shell.Historically, pattern matching notation is related to, but slightly different from, the regular expression notation described inXBDRegular Expressions. For this reason, the description of the rules forthis pattern matching notation are based on the description of regular expression notation, modified to account for thedifferences.

2.13.1Patterns Matching a Single Character

The following patterns matching a single character shall match a single character: ordinary characters, special patterncharacters, and pattern bracket expressions. The pattern bracket expression also shall match a single collating element. A<backslash> character shall escape the following character. The escaping <backslash> shall be discarded. If a patternends with an unescaped <backslash>, it is unspecified whether the pattern does not match anything or the pattern is treatedas invalid.

An ordinary character is a pattern that shall match itself. It can be any character in the supported character set except forNUL, those special shell characters inQuoting that require quoting, and the following three specialpattern characters. Matching shall be based on the bit pattern used for encoding the character, not on the graphic representationof the character. If any character (ordinary, shell special, or pattern special) is quoted, that pattern shall match the characteritself. The shell special characters always require quoting.

When unquoted and outside a bracket expression, the following three characters shall have special meaning in the specificationof patterns:

?
A <question-mark> is a pattern that shall match any character.
*
An <asterisk> is a pattern that shall match multiple characters, as described inPatternsMatching Multiple Characters.
[
If an open bracket introduces a bracket expression as in XBDRE BracketExpression, except that the <exclamation-mark> character ('!' ) shall replace the <circumflex>character ('^' ) in its role in a non-matching list in the regular expression notation, it shall introduce a patternbracket expression. A bracket expression starting with an unquoted <circumflex> character produces unspecified results.Otherwise,'[' shall match the character itself.

When pattern matching is used where shell quote removal is not performed (such as in the argument to thefind -name primary whenfind is beingcalled using one of theexec functions as defined in the System Interfaces volume of POSIX.1-2017, or in thepatternargument to thefnmatch() function), special characters can be escaped to removetheir special meaning by preceding them with a <backslash> character. This escaping <backslash> is discarded. Thesequence"\\" represents one literal <backslash>. All of the requirements and effects of quoting on ordinary, shellspecial, and special pattern characters shall apply to escaping in this context.

2.13.2Patterns Matching Multiple Characters

The following rules are used to construct patterns matching multiple characters from patterns matching a single character:

  1. The <asterisk> ('*' ) is a pattern that shall match any string, including the null string.

  2. The concatenation of patterns matching a single character is a valid pattern that shall match the concatenation of the singlecharacters or collating elements matched by each of the concatenated patterns.

  3. The concatenation of one or more patterns matching a single character with one or more <asterisk> characters is a validpattern. In such patterns, each <asterisk> shall match a string of zero or more characters, matching the greatest possiblenumber of characters that still allows the remainder of the pattern to match the string.

2.13.3Patterns Used for Filename Expansion

The rules described so far inPatterns Matching a Single Character andPatterns Matching Multiple Characters are qualified by the following rules that apply when pattern matchingnotation is used for filename expansion:

  1. The <slash> character in a pathname shall be explicitly matched by using one or more <slash> characters in thepattern; it shall neither be matched by the <asterisk> or <question-mark> special characters nor by a bracketexpression. <slash> characters in the pattern shall be identified before bracket expressions; thus, a <slash> cannot beincluded in a pattern bracket expression used for filename expansion. If a <slash> character is found following an unescaped<left-square-bracket> character before a corresponding <right-square-bracket> is found, the open bracket shall betreated as an ordinary character. For example, the pattern"a[b/c]d" does not match such pathnames asabd ora/d. It only matches a pathname of literallya[b/c]d.

  2. If a filename begins with a <period> ('.' ), the <period> shall be explicitly matched by using a<period> as the first character of the pattern or immediately following a <slash> character. The leading <period>shall not be matched by:

    It is unspecified whether an explicit <period> in a bracket expression matching list, such as"[.abc]", canmatch a leading <period> in a filename.

  3. Specified patterns shall be matched against existing filenames and pathnames, as appropriate. Each component that contains apattern character shall require read permission in the directory containing that component. Any component, except the last, thatdoes not contain a pattern character shall require search permission. For example, given the pattern:

    /foo/bar/x*/bam

    search permission is needed for directories/ andfoo, search and read permissions are needed for directorybar, and search permission is needed for eachx* directory. If the pattern matches any existing filenames orpathnames, the pattern shall be replaced with those filenames and pathnames, sorted according to the collating sequence in effectin the current locale. If this collating sequence does not have a total ordering of all characters (see XBDLC_COLLATE), any filenames or pathnames that collate equally should befurther compared byte-by-byte using the collating sequence for the POSIX locale.

    Note:
    A future version of this standard may require the byte-by-byte further comparison described above.

    If the pattern contains an open bracket ('[' ) that does not introduce a bracket expression as in XBDRE Bracket Expression, it is unspecified whether other unquoted patternmatching characters within the same slash-delimited component of the pattern retain their special meanings or are treated asordinary characters. For example, the pattern"a*[/b*" may match all filenames beginning with'b' in thedirectory"a*[" or it may match all filenames beginning with'b' in all directories with names beginning with'a' and ending with'['.

    If the pattern does not match any existing filenames or pathnames, the pattern string shall be left unchanged.

2.14.Special Built-In Utilities

The following "special built-in" utilities shall be supported in the shell command language. The output of each command, ifany, shall be written to standard output, subject to the normal redirection and piping possible with all commands.

The term "built-in" implies that the shell can execute the utility directly and does not need to search for it. Animplementation may choose to make any utility a built-in; however, the special built-in utilities described here differ fromregular built-in utilities in two respects:

  1. An error in a special built-in utility may cause a shell executing that utility to abort, while an error in a regular built-inutility shall not cause a shell executing that utility to abort. (SeeConsequences of Shell Errors forthe consequences of errors on interactive and non-interactive shells.) If a special built-in utility encountering an error does notabort the shell, its exit value shall be non-zero.

  2. As described inSimple Commands, variable assignments preceding the invocation of a specialbuilt-in utility remain in effect after the built-in completes; this shall not be the case with a regular built-in or otherutility.

The special built-in utilities in this section need not be provided in a manner accessible via theexec family offunctions defined in the System Interfaces volume of POSIX.1-2017.

Some of the special built-ins are described as conforming to XBDUtilitySyntax Guidelines. For those that are not, the requirement inUtilityDescription Defaults that"--" be recognized as a first argument to be discarded does not apply and a conformingapplication shall not use that argument.

<<<PreviousHomeNext>>>

 

return to top of page


NAME

break - exit from for, while, or until loop

SYNOPSIS

break[n]

DESCRIPTION

Ifn is specified, thebreak utility shall exit from thenth enclosingfor,while, oruntil loop. Ifn is not specified,break shall behave as ifn wasspecified as 1. Execution shall continue with the command immediately following the exited loop. The value ofn is apositive decimal integer. Ifn is greater than the number of enclosing loops, the outermost enclosing loop shall be exited.If there is no enclosing loop, the behavior is unspecified.

A loop shall enclose abreak orcontinue command if the loop lexically encloses the command. A loop lexicallyencloses abreak orcontinue command if the command is:

Ifn is greater than the number of lexically enclosing loops and there is a non-lexically enclosing loop in progress inthe same execution environment as thebreak orcontinue command, it is unspecified whether that loop encloses thecommand.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

 0
Successful completion.
>0
Then value was not an unsigned decimal integer greater than or equal to 1.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

for i in *do    if test -d "$i"    then break    fidone

The results of running the following example are unspecified: there are two loops in progress when thebreak command is executed, and they are in the same execution environment, but neither loop is lexicallyenclosing thebreak command. (There are no loops lexically enclosing thecontinue commands, either.)

foo() {    for j in 1 2; do        echo 'break 2' >/tmp/do_break        echo "  sourcing /tmp/do_break ($j)..."        # the behavior of the break from running the following command        # results in unspecified behavior:        . /tmp/do_break
do_continue() { continue 2; } echo " running do_continue ($j)..." # the behavior of the continue in the following function call # results in unspecified behavior (if execution reaches this # point): do_continue
trap 'continue 2' USR1 echo " sending SIGUSR1 to self ($j)..." # the behavior of the continue in the trap invoked from the # following signal results in unspecified behavior (if # execution reaches this point): kill -s USR1 $$ sleep 1 done}for i in 1 2; do echo "running foo ($i)..." foodone

RATIONALE

In early proposals, consideration was given to expanding the syntax ofbreak andcontinue to refer to a label associated with the appropriate loop as a preferable alternative to then method. However, this volume of POSIX.1-2017 does reserve the name space of command names ending with a <colon>. Itis anticipated that a future implementation could take advantage of this and provide something like:

outofloop: for i in a b c d edo    for j in 0 1 2 3 4 5 6 7 8 9    do        if test -r "${i}${j}"        then break outofloop        fi    donedone

and that this might be standardized after implementation experience is achieved.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

POSIX.1-2008, Technical Corrigendum 2, XCU/TC2-2008/0046 [842] is applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

colon - null utility

SYNOPSIS

:[argument...]

DESCRIPTION

This utility shall only expand commandarguments. It is used when a command is needed, as in thethen condition ofanif command, but nothing is to be done by the command.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

Zero.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

: ${X=abc}if     falsethen   :else   echo $Xfiabc

As with any of the special built-ins, the null utility can also have variable assignments and redirections associated with it,such as:

x=y : > z

which sets variablex to the valuey (so that it persists after the null utility completes) and creates ortruncates filez.

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

SD5-XCU-ERN-97 is applied, updating the SYNOPSIS.

End of informative text.

<<<PreviousHomeNext>>>

NAME

continue - continue for, while, or until loop

SYNOPSIS

continue[n]

DESCRIPTION

Ifn is specified, thecontinue utility shall return to the top of thenthenclosingfor,while, oruntil loop. Ifn is not specified,continueshall behave as ifn was specified as 1. Returning to the top of the loop involves repeating the condition list of awhile oruntil loop or performing the next assignment of afor loop, and re-executing the loop ifappropriate.

The value ofn is a positive decimal integer. Ifn is greater than the number of enclosing loops, the outermostenclosing loop shall be used. If there is no enclosing loop, the behavior is unspecified.

The meaning of "enclosing" shall be as specified in the description of thebreak utility.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

 0
Successful completion.
>0
Then value was not an unsigned decimal integer greater than or equal to 1.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

for i in *do    if test -d "$i"    then continue    fi    printf '"%s" is not a directory.\n' "$i"done

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

The example is changed to use theprintf utility rather thanecho.

POSIX.1-2008, Technical Corrigendum 2, XCU/TC2-2008/0046 [842] is applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

dot - execute commands in the current environment

SYNOPSIS

.file

DESCRIPTION

The shell shall execute commands from thefile in the current environment.

Iffile does not contain a <slash>, the shell shall use the search path specified byPATH to find thedirectory containingfile. Unlike normal command search, however, the file searched for by thedotutility need not be executable. If no readable file is found, a non-interactive shell shall abort; an interactive shell shall writea diagnostic message to standard error, but this condition shall not be considered a syntax error.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

See the DESCRIPTION.

ENVIRONMENT VARIABLES

See the DESCRIPTION.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If no readable file was found or if the commands in the file could not be parsed, and the shell is interactive (and thereforedoes not abort; seeConsequences of Shell Errors), the exit status shall be non-zero. Otherwise,return the value of the last command executed, or a zero exit status if no command is executed.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

cat foobarfoo=hello bar=world. ./foobarecho $foo $barhello world

RATIONALE

Some older implementations searched the current directory for thefile, even if the value ofPATH disallowed it.This behavior was omitted from this volume of POSIX.1-2008 due to concerns about introducing the susceptibility to trojan horsesthat the user might be trying to avoid by leavingdot out ofPATH.

The KornShell version ofdot takes optional arguments that are set to the positional parameters. Thisis a valid extension that allows adot script to behave identically to a function.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities,return

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

SD5-XCU-ERN-164 is applied.

POSIX.1-2008, Technical Corrigendum 1, XCU/TC1-2008/0038 [114] and XCU/TC1-2008/0039 [214] are applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

eval - construct command by concatenating arguments

SYNOPSIS

eval[argument...]

DESCRIPTION

Theeval utility shall construct a command by concatenatingarguments together, separatingeach with a <space> character. The constructed command shall be read and executed by the shell.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If there are noarguments, or only nullarguments,eval shall return a zero exitstatus; otherwise, it shall return the exit status of the command defined by the string of concatenatedarguments separatedby <space> characters, or a non-zero exit status if the concatenation could not be parsed as a command and the shell isinteractive (and therefore did not abort).

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

Sinceeval is not required to recognize the"--" end of options delimiter, in cases wherethe argument(s) toeval might begin with'-' it is recommended that the first argument isprefixed by a string that will not alter the commands to be executed, such as a <space> character:

eval " $commands"

or:

eval " $(some_command)"

EXAMPLES

foo=10 x=fooy='$'$xecho $y$fooeval y='$'$xecho $y10

RATIONALE

This standard allows, but does not require,eval to recognize"--". Although this meansapplications cannot use"--" to protect against options supported as an extension (or errors reported for unsupportedoptions), the nature of theeval utility is such that other means can be used to provide this protection(see APPLICATION USAGE above).

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

SD5-XCU-ERN-97 is applied, updating the SYNOPSIS.

POSIX.1-2008, Technical Corrigendum 1, XCU/TC1-2008/0040 [114], XCU/TC1-2008/0041 [163], and XCU/TC1-2008/0042 [163] areapplied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

exec - execute commands and open, close, or copy file descriptors

SYNOPSIS

exec[command[argument...]]

DESCRIPTION

Theexec utility shall open, close, and/or copy file descriptors as specified by any redirections aspart of the command.

Ifexec is specified withoutcommand orarguments, and any file descriptors withnumbers greater than 2 are opened with associated redirection statements, it is unspecified whether those file descriptors remainopen when the shell invokes another utility. Scripts concerned that child shells could misuse open file descriptors can alwaysclose them explicitly, as shown in one of the following examples.

Ifexec is specified withcommand, it shall replace the shell withcommand withoutcreating a new process. Ifarguments are specified, they shall be arguments tocommand. Redirection affects thecurrent shell execution environment.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

Ifcommand is specified,exec shall not return to the shell; rather, the exit status of theprocess shall be the exit status of the program implementingcommand, which overlaid the shell. Ifcommand is notfound, the exit status shall be 127. Ifcommand is found, but it is not an executable utility, the exit status shall be 126.If a redirection error occurs (seeConsequences of Shell Errors), the shell shall exit with a value inthe range 1-125. Otherwise,exec shall return a zero exit status.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

Openreadfile as file descriptor 3 for reading:

exec 3< readfile

Openwritefile as file descriptor 4 for writing:

exec 4> writefile

Make file descriptor 5 a copy of file descriptor 0:

exec 5<&0

Close file descriptor 3:

exec 3<&-

Cat the filemaggie by replacing the current shell with thecat utility:

exec cat maggie

RATIONALE

Most historical implementations were not conformant in that:

foo=bar exec cmd

did not passfoo tocmd.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

SD5-XCU-ERN-97 is applied, updating the SYNOPSIS.

End of informative text.

<<<PreviousHomeNext>>>

NAME

exit - cause the shell to exit

SYNOPSIS

exit[n]

DESCRIPTION

Theexit utility shall cause the shell to exit from its current execution environment with the exitstatus specified by the unsigned decimal integern. If the current execution environment is a subshell environment, theshell shall exit from the subshell environment with the specified exit status and continue in the environment from which thatsubshell environment was invoked; otherwise, the shell utility shall terminate with the specified exit status. Ifn isspecified, but its value is not between 0 and 255 inclusively, the exit status is undefined.

Atrap onEXIT shall be executed before the shell terminates, except when theexit utility is invoked in thattrap itself, in which case the shell shall exitimmediately.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The exit status shall ben, if specified, except that the behavior is unspecified ifn is not an unsigned decimalinteger or is greater than 255. Otherwise, the value shall be the exit value of the last command executed, or zero if no commandwas executed. Whenexit is executed in atrap action, the last command isconsidered to be the command that executed immediately preceding thetrap action.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

Exit with atrue value:

exit 0

Exit with afalse value:

exit 1

Propagate error handling from within a subshell:

(    command1 || exit 1    command2 || exit 1    exec command3) > outputfile || exit 1echo "outputfile created successfully"

RATIONALE

As explained in other sections, certain exit status values have been reserved for special uses and should be used byapplications only for those purposes:

 126
A file to be executed was found, but it was not an executable utility.
 127
A utility to be executed was not found.
>128
A command was interrupted by a signal.

The behavior ofexit when given an invalid argument or unknown option is unspecified, because ofdiffering practices in the various historical implementations. A value larger than 255 might be truncated by the shell, and beunavailable even to a parent process that useswaitid() to get the full exit value.It is recommended that implementations that detect any usage error should cause a non-zero exit status (or, if the shell isinteractive and the error does not cause the shell to abort, store a non-zero value in"$?" ), but even this was not donehistorically in all shells.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

POSIX.1-2008, Technical Corrigendum 2, XCU/TC2-2008/0047 [717], XCU/TC2-2008/0048 [960], XCU/TC2-2008/0049 [717], andXCU/TC2-2008/0050 [960] are applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

export - set the export attribute for variables

SYNOPSIS

export name[=word]...
 
export -p

DESCRIPTION

The shell shall give theexport attribute to the variables corresponding to the specifiednames, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable isfollowed by =word, then the value of that variable shall be set toword.

Theexport special built-in shall support XBDUtility Syntax Guidelines.

When-p is specified,export shall write to the standard output the names and values of allexported variables, in the following format:

"export %s=%s\n", <name>, <value>

ifname is set, and:

"export %s\n", <name>

ifname is unset.

The shell shall format the output, including the proper use of quoting, so that it is suitable for reinput to the shell ascommands that achieve the same exporting results, except:

  1. Read-only variables with values cannot be reset.

  2. Variables that were unset at the time they were output need not be reset to the unset state if a value is assigned to thevariable between the time the state was saved and the time at which the saved output is reinput to the shell.

When no arguments are given, the results are unspecified.

OPTIONS

See the DESCRIPTION.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

 0
Allname operands were successfully exported.
>0
At least onename could not be exported, or the-p option was specified and an error occurred.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

Note that, unlessX was previously marked readonly, the value of"$?" after:

export X=$(false)

will be 0 (becauseexport successfully setX to the empty string) and that executioncontinues, even ifset-e is in effect. In order to detect command substitution failures, a usermust separate the assignment from the export, as in:

X=$(false)export X

EXAMPLES

ExportPWD andHOME variables:

export PWD HOME

Set and export thePATH variable:

export PATH=/local/bin:$PATH

Save and restore all exported variables:

export -p >temp-fileunseta lot of variables...processing.temp-file

RATIONALE

Some historical shells use the no-argument case as the functional equivalent of what is required here with-p. Thisfeature was left unspecified because it is not historical practice in all shells, and some scripts may rely on the now-unspecifiedresults on their implementations. Attempts to specify the-p output as the default case were unsuccessful in achievingconsensus. The-p option was added to allow portable access to the values that can be saved and then later restored using;for example, adot script.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

XBDUtility Syntax Guidelines

CHANGE HISTORY

Issue 6

IEEE PASC Interpretation 1003.2 #203 is applied, clarifying the format when a variable is unset.

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/6 is applied, adding the following text to the end of the firstparagraph of the DESCRIPTION: "If the name of a variable is followed by =word, then the value of that variable shall beset toword.". The reason for this change is that the SYNOPSIS forexport includes:

export name[=word]...

but the meaning of the optional "=word" is never explained in the text.

Issue 7

POSIX.1-2008, Technical Corrigendum 1, XCU/TC1-2008/0043 [352] is applied.

POSIX.1-2008, Technical Corrigendum 2, XCU/TC2-2008/0051 [654] and XCU/TC2-2008/0052 [960] are applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

readonly - set the readonly attribute for variables

SYNOPSIS

readonly name[=word]...
 
readonly -p

DESCRIPTION

The variables whosenames are specified shall be given thereadonly attribute. The valuesof variables with thereadonly attribute cannot be changed by subsequent assignment, nor can thosevariables be unset by theunset utility. If the name of a variable is followed by =word, thenthe value of that variable shall be set toword.

Thereadonly special built-in shall support XBDUtility Syntax Guidelines.

When-p is specified,readonly writes to the standard output the names and values of allread-only variables, in the following format:

"readonly %s=%s\n", <name>, <value>

ifname is set, and

"readonly %s\n", <name>

ifname is unset.

The shell shall format the output, including the proper use of quoting, so that it is suitable for reinput to the shell ascommands that achieve the same value andreadonly attribute-setting results in a shell execution environment in which:

  1. Variables with values at the time they were output do not have thereadonly attribute set.

  2. Variables that were unset at the time they were output do not have a value at the time at which the saved output is reinput tothe shell.

When no arguments are given, the results are unspecified.

OPTIONS

See the DESCRIPTION.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

 0
Allname operands were successfully marked readonly.
>0
At least onename could not be marked readonly, or the-p option was specified and an error occurred.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

readonly HOME PWD

RATIONALE

Some historical shells preserve thereadonly attribute across separate invocations. This volume of POSIX.1-2008 allowsthis behavior, but does not require it.

The-p option allows portable access to the values that can be saved and then later restored using, for example, adot script. Also see the RATIONALE forexport for a description of the no-argumentand-p output cases and a related example.

Read-only functions were considered, but they were omitted as not being historical practice or particularly useful. Furthermore,functions must not be read-only across invocations to preclude "spoofing" (spoofing is the term for the practice of creating aprogram that acts like a well-known utility with the intent of subverting the real intent of the user) of administrative orsecurity-relevant (or security-conscious) shell scripts.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

XBDUtility Syntax Guidelines

CHANGE HISTORY

Issue 6

IEEE PASC Interpretation 1003.2 #203 is applied, clarifying the format when a variable is unset.

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/7 is applied, adding the following text to the end of the firstparagraph of the DESCRIPTION: "If the name of a variable is followed by =word, then the value of that variable shall beset toword.". The reason for this change is that the SYNOPSIS forreadonly includes:

readonly name[=word]...

but the meaning of the optional "=word" is never explained in the text.

Issue 7

POSIX.1-2008, Technical Corrigendum 2, XCU/TC2-2008/0052 [960] is applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

return - return from a function or dot script

SYNOPSIS

return[n]

DESCRIPTION

Thereturn utility shall cause the shell to stop executing the current function ordot script. If the shell is not currently executing a function ordot script, theresults are unspecified.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

The value of the special parameter'?' shall be set ton, an unsigned decimal integer, or to the exit status ofthe last command executed ifn is not specified. Ifn is not an unsigned decimal integer, or is greater than 255, theresults are unspecified. Whenreturn is executed in atrap action, the lastcommand is considered to be the command that executed immediately preceding thetrap action.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

None.

RATIONALE

The behavior ofreturn when not in a function ordot script differsbetween the System V shell and the KornShell. In the System V shell this is an error, whereas in the KornShell, the effect is thesame asexit.

The results of returning a number greater than 255 are undefined because of differing practices in the various historicalimplementations. Some shells AND out all but the low-order 8 bits; others allow larger values, but not of unlimited size.

See the discussion of appropriate exit status values underexit.

FUTURE DIRECTIONS

None.

SEE ALSO

Function Definition Command,Special Built-In Utilities,dot

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

POSIX.1-2008, Technical Corrigendum 1, XCU/TC1-2008/0044 [214] and XCU/TC1-2008/0045 [214] are applied.

POSIX.1-2008, Technical Corrigendum 2, XCU/TC2-2008/0052 [960] is applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

set - set or unset options and positional parameters

SYNOPSIS

set[-abCefhmnuvx] [-ooption][argument...]
 
set
[+abCefhmnuvx] [+ooption] [argument...]
 
set --
[argument...]
 
set -o
 
set +o

DESCRIPTION

If nooptions orarguments are specified,set shall write the names and values of allshell variables in the collation sequence of the current locale. Eachname shall start on a separate line, using theformat:

"%s=%s\n", <name>, <value>

Thevalue string shall be written with appropriate quoting; see the description of shell quoting inQuoting. The output shall be suitable for reinput to the shell, setting or resetting, as far as possible, thevariables that are currently set; read-only variables cannot be reset.

When options are specified, they shall set or unset attributes of the shell, as described below. Whenarguments arespecified, they cause positional parameters to be set or unset, as described below. Setting or unsetting attributes and positionalparameters are not necessarily related actions, but they can be combined in a single invocation ofset.

Theset special built-in shall support XBDUtilitySyntax Guidelines except that options can be specified with either a leading <hyphen-minus> (meaning enable theoption) or <plus-sign> (meaning disable it) unless otherwise specified.

Implementations shall support the options in the following list in both their <hyphen-minus> and <plus-sign> forms.These options can also be specified as options tosh.

-a
When this option is on, theexport attribute shall be set for each variable to which an assignment is performed; see XBDVariable Assignment. If the assignment precedes a utility name in acommand, theexport attribute shall not persist in the current execution environment after the utility completes, with theexception that preceding one of the special built-in utilities causes theexport attribute to persist after the built-in hascompleted. If the assignment does not precede a utility name in the command, or if the assignment is a result of the operation ofthegetopts orread utilities, theexport attribute shall persist until the variable is unset.
-b
This option shall be supported if the implementation supports the User Portability Utilities option. It shall cause the shellto notify the user asynchronously of background job completions. The following message is written to standard error:
"[%d]%c %s%s\n", <job-number>, <current>, <status>, <job-name>

where the fields shall be as follows:

<current>
The character'+' identifies the job that would be used as a default for thefg orbg utilities; this job can also be specifiedusing thejob_id"%+" or"%%". The character'-' identifies the job that would become thedefault if the current default job were to exit; this job can also be specified using thejob_id"%-". For otherjobs, this field is a <space>. 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 shall be a suspended job. If there are at least two suspendedjobs, then the previous job also shall be a suspended job.
<job-number>
A number that can be used to identify the process group to thewait,fg,bg, andkill utilities. Using these utilities, the job can be identified by prefixing the job numberwith'%'.
<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 inthe current shell execution environment; seeAsynchronous Lists. Asynchronous notification shallnot be enabled by default.

-C
(Uppercase C.) Prevent existing files from being overwritten by the shell's'>' redirection operator (seeRedirecting Output); the">|" redirection operator shall override thisnoclobber option foran individual file.
-e
When this option is on, when any command fails (for any of the reasons listed inConsequences of ShellErrors or by returning an exit status greater than zero), the shell immediately shall exit, as if by executing theexit special built-in utility with no arguments, with the following exceptions:
  1. The failure of any individual command in a multi-command pipeline shall not cause the shell to exit. Only the failure of thepipeline itself shall be considered.

  2. The-e setting shall be ignored when executing the compound list following thewhile,until,if, orelif reserved word, a pipeline beginning with the! reserved word, or any command of an AND-OR list other than thelast.

  3. If the exit status of a compound command other than a subshell command was the result of a failure while-e was beingignored, then-e shall not apply to this command.

This requirement applies to the shell environment and each subshell environment separately. For example, in:

set -e; (false; echo one) | cat; echo two

thefalse command causes the subshell to exit without executingecho one;however,echo two is executed because the exit status of the pipeline(false; echo one) | cat is zero.

-f
The shell shall disable pathname expansion.
-h
Locate and remember utilities invoked by functions as those functions are defined (the utilities are normally located when thefunction is executed).
-m
This option shall be supported if the implementation supports the User Portability Utilities option. All jobs shall be run intheir own process groups. Immediately before the shell issues a prompt after completion of the background job, a message reportingthe exit status of the background job shall be written to standard error. If a foreground job stops, the shell shall write amessage to standard error to that effect, formatted as described by thejobs utility.In addition, if a job changes status other than exiting (for example, if it stops for input or output or is stopped by a SIGSTOPsignal), the shell shall write a similar message immediately prior to writing the next prompt. This option is enabled by defaultfor interactive shells.
-n
The shell shall read commands but does not execute them; this can be used to check for shell script syntax errors. Aninteractive shell may ignore this option.
-o
Write the current settings of the options to standard output in an unspecified format.
+o
Write the current option settings to standard output in a format that is suitable for reinput to the shell as commands thatachieve the same options settings.
-o option
This option is supported if the system supports the User Portability Utilities option. It shall set various options, many of whichshall be equivalent to the single option letters. The following values ofoption shall be supported:
allexport
Equivalent to-a.
errexit
Equivalent to-e.
ignoreeof
Prevent an interactive shell from exiting on end-of-file. This setting prevents accidental logouts when <control>-D isentered. A user shall explicitlyexit to leave the interactive shell.
monitor
Equivalent to-m. This option is supported if the system supports the User Portability Utilities option.
noclobber
Equivalent to-C (uppercase C).
noglob
Equivalent to-f.
noexec
Equivalent to-n.
nolog
Prevent the entry of function definitions into the command history; seeCommand History List.
notify
Equivalent to-b.
nounset
Equivalent to-u.
verbose
Equivalent to-v.
vi
Allow shell command line editing using the built-invi editor. Enablingvi mode shall disable any other command line editing mode provided as an implementationextension.

It need not be possible to setvi mode on for certain block-mode terminals.

xtrace
Equivalent to-x.
-u
When the shell tries to expand an unset parameter other than the'@' and'*' special parameters, it shallwrite a message to standard error and the expansion shall fail with the consequences specified inConsequences of Shell Errors.
-v
The shell shall write its input to standard error as it is read.
-x
The shell shall write to standard error a trace for each command after it expands the command and before it executes it. It isunspecified whether the command that turns tracing off is traced.

The default for all these options shall be off (unset) unless stated otherwise in the description of the option or unless theshell was invoked with them on; seesh.

The remaining arguments shall be assigned in order to the positional parameters. The special parameter'#' shall be setto reflect the number of positional parameters. All positional parameters shall be unset before any new values are assigned.

If the first argument is'-', the results are unspecified.

The special argument"--" immediately following theset command name can be used to delimitthe arguments if the first argument begins with'+' or'-', or to prevent inadvertent listing of all shellvariables when there are no arguments. The commandset-- withoutargument shall unset allpositional parameters and set the special parameter'#' to zero.

OPTIONS

See the DESCRIPTION.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

 0
Successful completion.
>0
An invalid option was specified, or an error occurred.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

Application writers should avoid relying onset-e within functions. For example, in thefollowing script:

set -estart() {    some_server    echo some_server started successfully}start || echo >&2 some_server failed

the-e setting is ignored within the function body (because the function is a command in an AND-OR list other than thelast). Therefore, ifsome_server fails, the function carries on to echo"some_server started successfully", andthe exit status of the function is zero (which means"some_server failed" is not output).

EXAMPLES

Write out all variables and their values:

set

Set $1, $2, and $3 and set"$#" to 3:

set c a b

Turn on the-x and-v options:

set -xv

Unset all positional parameters:

set --

Set $1 to the value ofx, even if it begins with'-' or'+' :

set -- "$x"

Set the positional parameters to the expansion ofx, even ifx expands with a leading'-' or'+':

set -- $x

RATIONALE

Theset -- form is listed specifically in the SYNOPSIS even though this usage is implied by theUtility Syntax Guidelines. The explanation of this feature removes any ambiguity about whether theset --form might be misinterpreted as being equivalent toset without any options or arguments. Thefunctionality of this form has been adopted from the KornShell. In System V,set -- only unsetsparameters if there is at least one argument; the only way to unset all parameters is to useshift.Using the KornShell version should not affect System V scripts because there should be no reason to issue it without argumentsdeliberately; if it were issued as, for example:

set -- "$@"

and there were in fact no arguments resulting from"$@", unsetting the parameters would have no result.

Theset + form in early proposals was omitted as being an unnecessary duplication ofset alone and not widespread historical practice.

Thenoclobber option was changed to allowset-C as well as theset-onoclobber option. The single-letter version was added so that the historical"$-"paradigm would not be broken; seeSpecial Parameters.

The description of the-e option is intended to match the behavior of the 1988 version of the KornShell.

The-h flag is related to command name hashing. Seehash.

The followingset flags were omitted intentionally with the following rationale:

-k
The-k flag was originally added by the author of the Bourne shell to make it easier for users of pre-release versionsof the shell. In early versions of the Bourne shell the constructsetname=value had to beused to assign values to shell variables. The problem with-k is that the behavior affects parsing, virtually precludingwriting any compilers. To explain the behavior of-k, it is necessary to describe the parsing algorithm, which isimplementation-defined. For example:
set -k; echoname=value

and:

set -kechoname=value

behave differently. The interaction with functions is even more complex. What is more, the-k flag is never needed, sincethe command line could have been reordered.

-t
The-t flag is hard to specify and almost never used. The only known use could be done with here-documents. Moreover,the behavior withksh andsh differs. The reference page says that it exits afterreading and executing one command. What is one command? If the input isdate;date,sh executes bothdate commands whileksh doesonly the first.

Consideration was given to rewritingset to simplify its confusing syntax. A specific suggestion wasthat theunset utility should be used to unset options instead of using the non-getopt() -able +option syntax. However, the conclusion was reached that thehistorical practice of using +option was satisfactory and that there was no compelling reason to modify such widespreadhistorical practice.

The-o option was adopted from the KornShell to address user needs. In addition to its generally friendly interface,-o is needed to provide thevi command line editing mode, for which historicalpractice yields no single-letter option name. (Although it might have been possible to invent such a letter, it was recognized thatother editing modes would be developed and-o provides ample name space for describing such extensions.)

Historical implementations are inconsistent in the format used for-o option status reporting. The+o formatwithout an option-argument was added to allow portable access to the options that can be saved and then later restored using, forinstance, a dot script.

Historically,sh did trace the commandset+x, butksh did not.

Theignoreeof setting prevents accidental logouts when the end-of-file character (typically <control>-D) isentered. A user shall explicitlyexit to leave the interactive shell.

Theset-m option was added to apply only to the UPE because it applies primarily tointeractive use, not shell script applications.

The ability to do asynchronous notification became available in the 1988 version of the KornShell. To have it occur, the userhad to issue the command:

trap "jobs -n" CLD

The C shell provides two different levels of an asynchronous notification capability. The environment variablenotify isanalogous to what is done inset-b orset-onotify. Whenset, it notifies the user immediately of background job completions. When unset, this capability is turned off.

The other notification ability comes through the built-in utilitynotify. The syntax is:

notify[%job ...]

By issuingnotify with no operands, it causes the C shell to notify the user asynchronously when the state of the currentjob changes. If given operands,notify asynchronously informs the user of changes in the states of the specified jobs.

To add asynchronous notification to the POSIX shell, neither the KornShell extensions totrap, northe C shellnotify environment variable seemed appropriate (notify is not a proper POSIX environment variablename).

Theset-b option was selected as a compromise.

Thenotify built-in was considered to have more functionality than was required for simple asynchronous notification.

Historically, some shells applied the-u option to all parameters including$@ and$*. The standarddevelopers felt that this was a misfeature since it is normal and common for$@ and$* to be used in shellscripts regardless of whether they were passed any arguments. Treating these uses as an error when no arguments are passed reducesthe value of-u for its intended purpose of finding spelling mistakes in variable names and uses of unset positionalparameters.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities,hash

XBDVariable Assignment,Utility Syntax Guidelines

CHANGE HISTORY

Issue 6

The obsolescentset command name followed by'-' has been removed.

The following new requirements on POSIX implementations derive from alignment with the Single UNIX Specification:

IEEE PASC Interpretation 1003.2 #167 is applied, clarifying that the options default also takes into account the description ofthe option.

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/8 is applied, changing the square brackets in the example inRATIONALE to be in bold, which is the typeface used for optional items.

Issue 7

Austin Group Interpretation 1003.1-2001 #027 is applied, clarifying the behavior if the first argument is'-'.

SD5-XCU-ERN-97 is applied, updating the SYNOPSIS.

XSI shading is removed from the-h functionality.

POSIX.1-2008, Technical Corrigendum 1, XCU/TC1-2008/0046 [52], XCU/TC1-2008/0047 [155,280], XCU/TC1-2008/0048 [52],XCU/TC1-2008/0049 [52], and XCU/TC1-2008/0050 [155,430] are applied.

POSIX.1-2008, Technical Corrigendum 2, XCU/TC2-2008/0053 [584], XCU/TC2-2008/0054 [717], XCU/TC2-2008/0055 [717], andXCU/TC2-2008/0056 [960] are applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

shift - shift positional parameters

SYNOPSIS

shift[n]

DESCRIPTION

The positional parameters shall be shifted. Positional parameter 1 shall be assigned the value of parameter (1+n),parameter 2 shall be assigned the value of parameter (2+n), and so on. The parameters represented by the numbers"$#" down to"$#-n+1" shall be unset, and the parameter'#' is updated to reflect the new number ofpositional parameters.

The valuen shall be an unsigned decimal integer less than or equal to the value of the special parameter'#'.Ifn is not given, it shall be assumed to be 1. Ifn is 0, the positional and special parameters are not changed.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If then operand is invalid or is greater than"$#", this may be considered a syntax error and anon-interactive shell may exit; if the shell does not exit in this case, a non-zero exit status shall be returned. Otherwise, zeroshall be returned.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

$set a b c d e$shift 2$echo $*c d e

RATIONALE

None.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

POSIX.1-2008, Technical Corrigendum 1, XCU/TC1-2008/0051 [459] is applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

times - write process times

SYNOPSIS

times

DESCRIPTION

Thetimes utility shall write the accumulated user and system times for the shell and for all of itschild processes, in the following POSIX locale format:

"%dm%fs %dm%fs\n%dm%fs %dm%fs\n", <shell user minutes>,    <shell user seconds>, <shell system minutes>,    <shell system seconds>, <children user minutes>,    <children user seconds>, <children system minutes>,    <children system seconds>

The four pairs of times shall correspond to the members of the<sys/times.h>tms structure (defined in XBDHeaders) as returned bytimes():tms_utime,tms_stime,tms_cutime, andtms_cstime, respectively.

OPTIONS

None.

OPERANDS

None.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

 0
Successful completion.
>0
An error occurred.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

$times0m0.43s 0m1.11s8m44.18s 1m43.23s

RATIONALE

Thetimes special built-in from the Single UNIX Specification is now required for all conformingshells.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

XBD<sys/times.h>

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/9 is applied, changing text in the DESCRIPTION from: "Write theaccumulated user and system times for the shell and for all of its child processes ..." to: "Thetimes utility shall write the accumulated user and system times for the shell and for all of its childprocesses ...".

Issue 7

POSIX.1-2008, Technical Corrigendum 2, XCU/TC2-2008/0056 [960] is applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

trap - trap signals

SYNOPSIS

trapn[condition...]
trap[actioncondition...]

DESCRIPTION

If the first operand is an unsigned decimal integer, the shell shall treat all operands as conditions, and shall reset eachcondition to the default value. Otherwise, if there are operands, the first is treated as an action and the remaining asconditions.

Ifaction is'-', the shell shall reset eachcondition to the default value. Ifaction is null ("" ), the shell shall ignore each specifiedcondition if it arises. Otherwise, the argumentaction shall beread and executed by the shell when one of the corresponding conditions arises. The action oftrap shalloverride a previous action (either default action or one explicitly set). The value of"$?" after thetrap action completes shall be the value it had beforetrap was invoked.

The condition can be EXIT, 0 (equivalent to EXIT), or a signal specified using a symbolic name, without the SIG prefix, aslisted in the tables of signal names in the<signal.h> header defined in XBDHeaders; for example, HUP, INT, QUIT, TERM. Implementations may permitnames with the SIG prefix or ignore case in signal names as an extension. Setting a trap for SIGKILL or SIGSTOP produces undefinedresults.

The environment in which the shell executes atrap on EXIT shall be identical to the environmentimmediately after the last command executed before thetrap on EXIT was taken.

Each timetrap is invoked, theaction argument shall be processed in a manner equivalentto:

evalaction

Signals that were ignored on entry to a non-interactive shell cannot be trapped or reset, although no error need be reportedwhen attempting to do so. An interactive shell may reset or catch signals ignored on entry. Traps shall remain in place for a givenshell until explicitly changed with anothertrap command.

When a subshell is entered, traps that are not being ignored shall be set to the default actions, except in the case of acommand substitution containing only a singletrap command, when the traps need not be altered.Implementations may check for this case using only lexical analysis; for example, if`trap` and$( trap -- ) donot alter the traps in the subshell, cases such as assigningvar=trap and then using$($var) may still alterthem. This does not imply that thetrap command cannot be used within the subshell to set new traps.

Thetrap command with no operands shall write to standard output a list of commands associated witheach condition. If the command is executed in a subshell, the implementation does not perform the optional check described abovefor a command substitution containing only a singletrap command, and notrapcommands with operands have been executed since entry to the subshell, the list shall contain the commands that were associatedwith each condition immediately before the subshell environment was entered. Otherwise, the list shall contain the commandscurrently associated with each condition. The format shall be:

"trap -- %s %s ...\n", <action>, <condition> ...

The shell shall format the output, including the proper use of quoting, so that it is suitable for reinput to the shell ascommands that achieve the same trapping results. For example:

save_traps=$(trap)...eval "$save_traps"

[XSI][Option Start]XSI-conformant systems also allow numeric signal numbers for the conditions corresponding to the following signal names:

1
SIGHUP
2
SIGINT
3
SIGQUIT
6
SIGABRT
9
SIGKILL
14
SIGALRM
15
SIGTERM
[Option End]

Thetrap special built-in shall conform to XBDUtility Syntax Guidelines.

OPTIONS

None.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

See the DESCRIPTION.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

If the trap name[XSI][Option Start]  or number[Option End] is invalid, a non-zeroexit status shall be returned; otherwise, zero shall be returned. For both interactive and non-interactive shells, invalid signalnames[XSI][Option Start]  or numbers[Option End] shall not be considered a syntax error and donot cause the shell to abort.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

Write out a list of all traps and actions:

trap

Set a trap so thelogout utility in the directory referred to by theHOME environment variable executes when theshell terminates:

trap '"$HOME"/logout' EXIT

or:

trap '"$HOME"/logout' 0

Unset traps on INT, QUIT, TERM, and EXIT:

trap - INT QUIT TERM EXIT

RATIONALE

Implementations may permit lowercase signal names as an extension. Implementations may also accept the names with the SIGprefix; no known historical shell does so. Thetrap andkillutilities in this volume of POSIX.1-2008 are now consistent in their omission of the SIG prefix for signal names. Somekill implementations do not allow the prefix, andkill-l lists the signals without prefixes.

Trapping SIGKILL or SIGSTOP is syntactically accepted by some historical implementations, but it has no effect. Portable POSIXapplications cannot attempt to trap these signals.

The output format is not historical practice. Since the output of historicaltrap commands is notportable (because numeric signal values are not portable) and had to change to become so, an opportunity was taken to format theoutput in a way that a shell script could use to save and then later reuse a trap if it wanted.

The KornShell uses anERR trap that is triggered wheneverset-e would cause an exit.This is allowable as an extension, but was not mandated, as other shells have not used it.

The text about the environment for the EXIT trap invalidates the behavior of some historical versions of interactive shellswhich, for example, close the standard input before executing a trap on 0. For example, in some historical interactive shellsessions the following trap on 0 would always print"--" :

trap 'read foo; echo "-$foo-"' 0

The command:

trap 'eval " $cmd"' 0

causes the contents of the shell variablecmd to be executed as a command when the shell exits. Using:

trap '$cmd' 0

does not work correctly ifcmd contains any special characters such as quoting or redirections. Using:

trap " $cmd" 0

also works (the leading <space> character protects against unlikely cases wherecmd is a decimal integer or beginswith'-' ), but it expands thecmd variable when thetrap command is executed, not whenthe exit action is executed.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

XBDUtility Syntax Guidelines,<signal.h>

CHANGE HISTORY

Issue 6

XSI-conforming implementations provide the mapping of signal names to numbers given above (previously this had been markedobsolescent). Other implementations need not provide this optional mapping.

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

SD5-XCU-ERN-97 is applied, updating the SYNOPSIS.

Austin Group Interpretation 1003.1-2001 #116 is applied.

POSIX.1-2008, Technical Corrigendum 1, XCU/TC1-2008/0052 [53,268,440], XCU/TC1-2008/0053 [53,268,440], XCU/TC1-2008/0054 [163],XCU/TC1-2008/0055 [163], and XCU/TC1-2008/0056 [163] are applied.

End of informative text.

<<<PreviousHomeNext>>>

NAME

unset - unset values and attributes of variables and functions

SYNOPSIS

unset[-fv]name...

DESCRIPTION

Each variable or function specified byname shall be unset.

If-v is specified,name refers to a variable name and the shell shall unset it and remove it from theenvironment. Read-only variables cannot be unset.

If-f is specified,name refers to a function and the shell shall unset the function definition.

If neither-f nor-v is specified,name refers to a variable; if a variable by that name does not exist, itis unspecified whether a function by that name, if any, shall be unset.

Unsetting a variable or function that was not previously set shall not be considered an error and does not cause the shell toabort.

Theunset special built-in shall support XBDUtility Syntax Guidelines.

Note that:

VARIABLE=

is not equivalent to anunset ofVARIABLE; in the example,VARIABLE is set to"". Also, the variables that can beunset should not be misinterpreted to include the specialparameters (seeSpecial Parameters).

OPTIONS

See the DESCRIPTION.

OPERANDS

See the DESCRIPTION.

STDIN

Not used.

INPUT FILES

None.

ENVIRONMENT VARIABLES

None.

ASYNCHRONOUS EVENTS

Default.

STDOUT

Not used.

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

None.

EXTENDED DESCRIPTION

None.

EXIT STATUS

 0
Allname operands were successfully unset.
>0
At least onename could not be unset.

CONSEQUENCES OF ERRORS

Default.


The following sections are informative.

APPLICATION USAGE

None.

EXAMPLES

UnsetVISUAL variable:

unset -v VISUAL

Unset the functionsfoo andbar:

unset -f foo bar

RATIONALE

Consideration was given to omitting the-f option in favor of anunfunction utility, but the standard developersdecided to retain historical practice.

The-v option was introduced because System V historically used one name space for both variables and functions. Whenunset is used without options, System V historically unset either a function or a variable, and there wasno confusion about which one was intended. A portable POSIX application can useunset without an optionto unset a variable, but not a function; the-f option must be used.

FUTURE DIRECTIONS

None.

SEE ALSO

Special Built-In Utilities

XBDUtility Syntax Guidelines

CHANGE HISTORY

Issue 6

IEEE Std 1003.1-2001/Cor 1-2002, item XCU/TC1/D6/5 is applied so that the reference page sections use terms asdescribed in the Utility Description Defaults (Utility DescriptionDefaults). No change in behavior is intended.

Issue 7

SD5-XCU-ERN-97 is applied, updating the SYNOPSIS.

End of informative text.

<<<PreviousHomeNext>>>


[8]ページ先頭

©2009-2025 Movatter.jp