		 IEEE P1003.2 Draft 11.2 - September 1991


			Copyright (c) 1991 by the
	 Institute of Electrical and Electronics Engineers, Inc.
			   345 East 47th Street
			 New York, NY 10017, USA
	       All rights reserved as an unpublished work.

       This is an unapproved and unpublished IEEE Standards Draft,
       subject to change.  The publication, distribution, or
       copying of this draft, as well as all derivative	works based
       on this draft, is expressly prohibited except as	set forth
       below.

       Permission is hereby granted for	IEEE Standards Committee
       participants to reproduce this document for purposes of IEEE
       standardization activities only,	and subject to the
       restrictions contained herein.

       Permission is hereby also granted for member bodies and
       technical committees of ISO and IEC to reproduce	this
       document	for purposes of	developing a national position,
       subject to the restrictions contained herein.

       Permission is hereby also granted to the	preceding entities
       to make limited copies of this document in an electronic
       form only for the stated	activities.

       The following restrictions apply	to reproducing or
       transmitting the	document in any	form:  1) all copies or
       portions	thereof	must identify the document's IEEE project
       number and draft	number,	and must be accompanied	by this
       entire notice in	a prominent location; 2) no portion of this
       document	may be redistributed in	any modified or	abridged
       form without the	prior approval of the IEEE Standards
       Department.

       Other entities seeking permission to reproduce this
       document, or any	portion	thereof, for standardization or
       other activities, must contact the IEEE Standards Department
       for the appropriate license.

       Use of information contained in this unapproved draft is	at
       your own	risk.

	    IEEE Standards Department
	    Copyright and Permissions
	    445	Hoes Lane, P.O.	Box 1331
	    Piscataway,	NJ 08855-1331, USA
	    +1 (908) 562-3800
	    +1 (908) 562-1571 [FAX]



















                                                             P1003.2/D11.2








                     Section 3: Shell Command Language



 The shell is a command language interpreter.  This section describes the
 syntax of that command language as it is used by the sh utility and the
 functions in 7.1 [such as _s_y_s_t_e_m() and _p_o_p_e_n() in the C binding].

 The shell operates according to the following general overview of
 operations.  The specific details are included in the cited clauses and
 subclauses of this section.  The shell:

     (1)  Reads its input from a file (see sh in 4.56), from the -c
          option, or from one of the functions in 7.1.  If the first line
          of a file of shell commands starts with the characters #!, the
          results are unspecified.

     (2)  Breaks the input into tokens:  words and operators.  (See 3.3.)

     (3)  Parses the input into simple (3.9.1) and compound (3.9.4)
          commands.

     (4)  Performs various expansions (separately) on different parts of
          each command, resulting in a list of pathnames and fields to be
          treated as a command and arguments (3.6).

     (5)  Performs redirection (3.7) and removes redirection operators and
          their operands from the parameter list.

     (6)  Executes a function (3.9.5), built-in (3.14), executable file,
          or script, giving the name of the command (or, in the case of a   1
          function within a script, the name of the script) as the          1
          ``zero'th'' argument and the remaining words and fields as
          parameters (3.9.1.1).

     (7)  Optionally waits for the command to complete and collects the
          exit status (3.8.2).

 BEGIN_RATIONALE





               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3 Shell Command Language                                              215





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.0.1  Shell Command Language Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
        _P_1_0_0_3._2)

 The System V shell was selected as the starting point for this standard.
 The BSD C-shell was excluded from consideration, for the following
 reasons:

     (1)  Most historically portable shell scripts assume the Version 7
          ``Bourne'' shell, from which the System V shell is derived.

     (2)  The majority of tutorial materials on shell programming assume
          the System V shell.

 Despite the selection of the System V shell, the developers of the
 standard did not limit the possibilities for a shell command language
 that was upward-compatible.

 The only programmatic interfaces to the shell language are through the
 functions in 7.1 and the sh utility.  Most implementations provide an
 interface to, and processing mode for, the shell that is suitable for
 direct user interaction.  The behavior of this interactive mode is not
 defined by this standard; however, places where historically an
 interactive shell behaves differently from the behavior described here
 are noted.

     (1)  Aliases are not included in the base POSIX.2 because they
          duplicate functionality already available to applications with
          functions.  In early drafts, the search order of simple command
          lookup was ``aliases, built-ins, functions, file system,'' and
          therefore an alias was necessary to create a user-defined
          command having the same name as a built-in.  To retain this
          capability, the search order has changed to ``special built-ins,
          functions, built-ins, file system,'' and a built-in, called
          command, has been added, which disables the looking up of
          functions.  Aliases are a part of the POSIX.2a UPE because they
          are widely used by human users, as differentiated from
          applications.

     (2)  All references to job control and related commands have been
          omitted from the base POSIX.2.  POSIX.2 describes the
          noninteractive operation of the shell; job control is outside
          the scope of this standard until the UPE revision is developed.
          Apparently it is not widely known that traditionally, even in a
          job control environment, the commands executed during the
          execution of a shell script are not placed into separate process
          groups.  If they were, one could not stop the execution of the
          shell script from the interactive shell, for example.  This
          standard does not require or prohibit job control; it simply
          does not mention it.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 216                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

     (3)  The conditional command (double bracket [[ ]]) was removed from
          an earlier draft.  Objections were lodged that the real problem
          is misuse of the test command ([), and putting it into the shell
          is the wrong way to fix the problem.  Instead, proper
          documentation and a new shell reserved word (!) are sufficient.
          Tests that require multiple test operations can be done at the
          shell level using individual invocations of the test command and
          shell logicals, rather than the error prone -o flag of test.

     (4)  Exportable functions were removed from an earlier draft.  See
          the rationale in 3.9.5.1.

 The construct #! is reserved for implementations wishing to provide that
 extension.  If it were not reserved, the standard would disallow it by
 forcing it to be a comment.  As it stands, a conforming application shall
 not use #!  as the first line of a shell script.

 END_RATIONALE



 3.1  Shell Definitions

 The following terms are used in Section 3.  Because they are specific to
 the shell, they do not appear in 2.2.2.

 3.1.1  control operator:  A token that performs a control function.

 It is one of the following symbols:

                         &           )       <newline>
                        &&           ;           |
                         (          ;;          ||

 The end-of-input indicator used internally by the shell is also
 considered a control operator.  See 3.3.

 On some systems, the symbol (( is a control operator; its use produces     1
 unspecified results.

 3.1.2  expand:  When not qualified, the act of applying all the
 expansions described in 3.6.

 3.1.3  field:  A unit of text that is the result of parameter expansion
 (3.6.2), arithmetic expansion (3.6.4), command substitution (3.6.3), or
 field splitting (3.6.5).

 During command processing (see 3.9.1), the resulting fields are used as
 the command name and its arguments.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.1 Shell Definitions                                                 217





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.1.4  interactive shell:  A processing mode of the shell that is
 suitable for direct user interaction.

 The behavior in this mode is not defined by this standard.

 NOTE:  The preceding sentence is expected to change following the
 eventual approval of the UPE supplement.

 3.1.5  name:  A word consisting solely of underscores, digits, and
 alphabetics from the portable character set (see 2.4).

 The first character of a name shall not be a digit.

 3.1.6  operator:  Either a control operator or a redirection operator.

 3.1.7  parameter:  An entity that stores values.

 There are three types of parameters:  variables (named parameters),
 positional parameters, and special parameters.  Parameter expansion is
 accomplished by introducing a parameter with the $ character.  See 3.5.

 3.1.8  positional parameter:  A parameter denoted by a single digit or
 one or more digits in curly braces.

 See 3.5.1.

 3.1.9  redirection:  A method of associating files with the input/output
 of commands.

 See 3.7.

 3.1.10  redirection operator:  A token that performs a redirection
 function.

 It is one of the following symbols:

       <     >     >|     <<     >>     <&     >&     <<-     <>

 3.1.11  special parameter:  A parameter named by a single character from
 the following list:

       *         @         #         ?         !         -         $        0

 See 3.5.2.

 3.1.12  subshell:  A shell execution environment, distinguished from the
 main or current shell execution environment by the attributes described
 in 3.12.



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 218                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.1.13  token:  A sequence of characters that the shell considers as a
 single unit when reading input, according to the rules in 3.3.

 A token is either an operator or a word.

 3.1.14  variable:  A named parameter.  See 3.5.

 3.1.15  variable assignment [assignment]:  A word consisting of the
 following parts

       _v_a_r_n_a_m_e=_v_a_l_u_e

 When used in a context where assignment is defined to occur (see 3.9.1)
 and at no other time, the _v_a_l_u_e (representing a word or field) shall be
 assigned as the value of the variable denoted by _v_a_r_n_a_m_e. The _v_a_r_n_a_m_e and
 _v_a_l_u_e parts meet the requirements for a name and a word, respectively,
 except that they are delimited by the embedded unquoted equals-sign in
 addition to the delimiting described in 3.3.  In all cases, the variable
 shall be created if it did not already exist.  If _v_a_l_u_e is not specified,
 the variable shall be given a null value.

 An alternative form of variable assignment:

       _s_y_m_b_o_l=_v_a_l_u_e

 (where _s_y_m_b_o_l is a valid word delimited by an equals-sign, but not a
 valid name) produces unspecified results.

 3.1.16  word:  A token other than an operator.

 In some cases a word is also a portion of a word token:  in the various
 forms of parameter expansion (3.6.2), such as ${_n_a_m_e-_w_o_r_d}, and variable
 assignment, such as _n_a_m_e=_w_o_r_d, the word is the portion of the token
 depicted by _w_o_r_d. The concept of a word is no longer applicable following
 word expansions--only fields remain; see 3.6.

 BEGIN_RATIONALE


 3.1.17  Shell Definitions Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
         _P_1_0_0_3._2)

 The _w_o_r_d=_w_o_r_d form of variable assignment was included, producing
 unspecified results, to allow the KornShell _n_a_m_e[_e_x_p_r_e_s_s_i_o_n]=_v_a_l_u_e syntax
 to conform.

 The (( symbol is a control operator in the KornShell, used for an          1
 alternative syntax of an arithmetic expression command.  A strictly
 conforming POSIX.2 application cannot use (( as a single token [with the


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.1 Shell Definitions                                                 219





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 obvious exception of the $(( form described in POSIX.2].  The decision to
 require this is based solely on the pragmatic knowledge that there are
 many more historical shell scripts using the KornShell syntax than there
 might be using nested subshells, such as

       ((foo))       or        ((foo);(bar))

 The latter example should not be misinterpreted by the shell as
 arithmetic because attempts to balance the parentheses pairs would
 indicate that they are subshells.  Thus, in most cases, while a few
 scripts will no longer be strictly portable, the chances of breaking
 existing scripts is even smaller.

 There are no explicit limits in this standard on the sizes of names,       1
 words, lines, or other objects.  However, other implicit limits do apply:  1
 shell script lines produced by many of the standard utilities cannot       1
 exceed {LINE_MAX} and the sum of exported variables comes under the        1
 {ARG_MAX} limit.  Historical shells dynamically allocate memory for names  1
 and words and parse incoming lines a byte at a time.  Lines cannot have    1
 an arbitrary {LINE_MAX} limit because of historical practice such as       1
 makefiles, where make removes the <newline>s associated with the commands  1
 for a target and presents the shell with one very long line.  The text in  1
 2.11.5.2 does allow a shell to run out of memory, but it cannot have
 arbitrary programming limits.

 END_RATIONALE



 3.2  Quoting

 Quoting is used to remove the special meaning of certain characters or
 words to the shell.  Quoting can be used to preserve the literal meaning
 of the special characters in the next paragraph; prevent reserved words
 from being recognized as such; and prevent parameter expansion and
 command substitution within here-document processing (see 3.7.4).

 The following characters shall be quoted 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 on conditions
 described elsewhere in the standard:

       *          ?          [          #          ~          =          %



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 220                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 The various quoting mechanisms are the escape character, single-quotes,
 and double-quotes.  The here-document represents another form of quoting;
 see 3.7.4.


 3.2.1  Escape 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.


 3.2.2  Single-Quotes

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


 3.2.3  Double-Quotes

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

    $     The dollar-sign shall retain its special meaning introducing
          parameter expansion (see 3.6.2), a form of command substitution
          (see 3.6.3), and arithmetic expansion (see 3.6.4).

          The input characters within the quoted string that are also
          enclosed between $( and the matching ) shall not be affected by
          the double-quotes, but rather shall define that command whose
          output replaces the $(...) when the word is expanded.  The
          tokenizing rules in 3.3 shall be applied recursively to find the
          matching ).

          Within the string of characters from an enclosed ${ to the
          matching }, an even number of unescaped double-quotes or
          single-quotes, if any, shall occur.  A preceding backslash
          character shall be used to escape a literal { or }.  The rule in
          3.6.2 shall be used to determine the matching }.

    `     The backquote shall retain its special meaning introducing the
          other form of command substitution (see 3.6.3).  The portion of
          the quoted string from the initial backquote and the characters
          up to the next backquote that is not preceded by a backslash,
          having escape characters removed, defines that command whose


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.2 Quoting                                                           221





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

          output replaces `...` when the word is expanded.  Either of the
          following cases produces undefined results:

           - A single- or double-quoted string that begins, but does not
             end, within the `...` sequence.

           - A `...` sequence that begins, but does not end, within the
             same double-quoted string.

    \     The backslash shall retain its special meaning as an escape
          character (see 3.2.1) only when followed by one of the
          characters:

                $     `     "     \     <newline>

 A double-quote shall be preceded by a backslash to be included within
 double-quotes.  The parameter @ has special meaning inside double-quotes
 and is described in 3.5.2.

 BEGIN_RATIONALE


 3.2.4  Quotes Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 A backslash cannot be used to escape a single-quote in a single-quoted
 string.  An embedded quote can be created by writing, for example,
 'a'\''b', which yields a'b.  (See 3.6.5 for a better understanding of how
 portions of words are either split into fields or remain concatenated.)
 A single token can be made up of concatenated partial strings containing
 all three kinds of quoting/escaping, thus permitting any combination of
 characters.

 The escaped <newline> used for line continuation is removed entirely from
 the input and is not replaced by any white space.  Therefore, it cannot
 serve as a token separator.

 In double-quoting, if a backslash is immediately followed by a character
 that would be interpreted as having a special meaning, the backslash is
 deleted and the subsequent character is taken literally.  If a backslash
 does not precede a character that would have a special meaning, it is
 left in place unmodified and the character immediately following it is
 also left unmodified.  Thus, for example:

       "\$"   =>   $

       "\a"   =>   \a

 It would be desirable to include the statement ``The characters from an
 enclosed ${ to the matching } shall not be affected by the double-


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 222                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 quotes,'' similar to the one for $( ).  However, historical practice in
 the System V shell prevents this.  The requirement that double-quotes be
 matched inside ${...} within double-quotes and the rule for finding the
 matching } in 3.6.2 eliminate several subtle inconsistencies in expansion
 for historical shells in rare cases; for example,

       "${foo-bar"}

 yields bar when foo is not defined, and is an invalid substitution when    1
 foo is defined, in many historical shells.  The differences in processing
 the "${...}" form have led to inconsistencies between the historical
 System V, BSD, and KornShells, and the text in POSIX.2 is an attempt to
 converge them without breaking many applications.  A consequence of the
 new rule is that single-quotes cannot be used to quote the } within
 "${...}"; for example

       unset bar
       foo="${bar-'}'}"

 is invalid because the "${...}" substitution contains an unpaired          1
 unescaped single-quote.  The backslash can be used to escape the } in      1
 this example to achieve the desired result:

       unset bar
       foo="${bar-\}}"

 The only alternative to this compromise between shells would be to make
 the behavior unspecified whenever the literal characters ', {, }, and "
 appear within ${...}.  To write a portable script that uses these values,
 a user would have to assign variables, say,

       squote=\' dquote=\" lbrace='{' rbrace='}'
       ${foo-$squote$rbrace$squote}

 rather than

       ${foo-"'}'"}

 Some systems have allowed the end of the word to terminate the backquoted
 command substitution, such as in

       "`echo hello"

 This usage is undefined in POSIX.2, where the matching backquote is
 required.  The other undefined usage can be illustrated by the example:

       sh -c '` echo "foo`'




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.2 Quoting                                                           223





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 The description of the recursive actions involving command substitution
 can be illustrated with an example.  Upon recognizing the introduction of
 command substitution, the shell must parse input (in a new context),
 gathering the ``source'' for the command substitution until an unbalanced
 ) or ` is located.  For example, in the following

       echo "$(date; echo "
               one" )"

 the double-quote following the echo does not terminate the first double-
 quote; it is part of the command substitution ``script.''  Similarly, in

       echo "$(echo *)"

 the asterisk is not quoted since it is inside command substitution;
 however,

       echo "$(echo "*")"

 is quoted (and represents the asterisk character itself).

 END_RATIONALE



 3.3  Token Recognition

 The shell reads its input in terms of lines from a file, from a terminal
 in the case of an interactive shell, or from a string in the case of
 sh -c or _s_y_s_t_e_m().  The input lines can be of unlimited length.  These     1
 lines are parsed using two major modes:  ordinary token recognition and    1
 processing of here-documents.

 When an io_here token has been recognized by the grammar (see 3.10), one
 or more of the immediately subsequent lines form the body of one or more
 here-documents and shall be parsed according to the rules of 3.7.4.

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

     (1)  If the end of input is recognized, the current token shall be
          delimited.  If there is no current token, the end-of-input
          indicator shall be returned as the token.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 224                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

     (2)  If the previous character was used as part of an operator and
          the current character is not quoted and can be used with the
          current 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 current characters
          to form an operator, the operator containing the previous
          character shall be delimited.

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

     (5)  If the current character is an unquoted $ or `, the shell shall
          identify the start of any candidates for parameter expansion
          (3.6.2), command substitution (3.6.3), or arithmetic expansion
          (3.6.4) from their introductory unquoted character sequences:  $
          or ${, $( or `, and $((, respectively.  The shell shall read
          sufficient input to determine the end of the unit to be expanded
          (as explained in the cited subclauses).  While processing the
          characters, if instances of expansions or quoting are found
          nested within the substitution, the shell shall recursively
          process them in the manner specified for the construct that is
          found.  The characters found from the beginning of the
          substitution to its end, 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 the substitution.

     (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 <newline>, the current
          token shall be delimited.

     (8)  If the current character is an unquoted <blank>, any token
          containing the previous character is delimited and the current


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.3 Token Recognition                                                 225





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

          character is discarded.

     (9)  If the previous character was part of a word, the current
          character is appended to that word.

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

    (11)  The current character is used as the start of a new word.

 Once a token is delimited, it shall be categorized as required by the
 grammar in 3.10.

 BEGIN_RATIONALE


 3.3.1  Token Recognition Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
        _P_1_0_0_3._2)

 The (3) rule about combining characters to form operators is not meant to  1
 preclude systems from extending the shell language when characters are     1
 combined in otherwise invalid ways.  Portable applications cannot use      1
 invalid combinations and test suites should not penalize systems that      1
 take advantage of this fact.  For example, the unquoted combination |& is  1
 not valid in a POSIX.2 script, but has a specific KornShell meaning.       1

 The (10) rule about # as the current character is the first in the
 sequence in which a new token is being assembled.  The # starts a comment
 only when it is at the beginning of a token.  This rule is also written
 to indicate that the search for the end-of-comment does not consider
 escaped <newline> specially, so that a comment cannot be continued to the
 next line.

 END_RATIONALE



 3.4  Reserved Words

 Reserved words are words that have special meaning to the shell.  (See
 3.9.)  The following words shall be recognized as reserved words:

                   !       elif    fi      in      while
                   case    else    for     then    {4)
                   do      esac    if      until   }
                   done



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 226                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

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

     (1)  The first word of a command

     (2)  The first word following one of the reserved words other than
          case, for, or in

     (3)  The third word in a case or for command (only in is valid in
          this case)

 See the grammar in 3.10.

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

                 function   select     [[         ]]                        2

 Words that are the concatenation of a name and a colon (:) are reserved;
 their use produces unspecified results.

 BEGIN_RATIONALE


 3.4.1  Reserved Words Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
        _P_1_0_0_3._2)

 All reserved words are recognized syntactically as such in the contexts
 described.  However, it is useful to point out that in is the only
 meaningful reserved word after a case or for; similarly, in is not
 meaningful as the first word of a simple command.

 Reserved words are recognized only when they are delimited (i.e., meet
 the definition of _w_o_r_d; see 3.1.16), whereas operators are themselves
 delimiters.  For instance, ( and ) are control operators, so that no
 <space> is needed in (list).  However, { and } are reserved words in
 { list;}, so that in this case the leading <space> and semicolon are
 required.



 __________
  4) In some historical systems, the curly braces are treated as control
     operators.  To assist in future standardization activities, portable
     applications should avoid using unquoted braces to represent the
     characters themselves.  It is possible that a future version of
     POSIX.2 may require this, although probably not for the often-used
     find {} construct.



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.4 Reserved Words                                                    227





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 The list of unspecified reserved words is from the KornShell, so portable
 applications cannot use them in places a reserved word would be
 recognized.  This list contained time in earlier drafts, but it was        2
 removed when the time utility was selected for the UPE.                    2

 There was a strong argument for promoting braces to operators (instead of
 reserved words), so they would be syntactically equivalent to subshell
 operators.  Concerns about compatibility outweighed the advantages of
 this approach.  Nevertheless, portable applications should consider
 quoting { and } when they represent themselves.

 The restriction on ending a name with a colon is to allow future
 implementations that support named labels for flow control.  See the
 rationale for break (3.14.1.1).

 END_RATIONALE



 3.5  Parameters and Variables

 A parameter can be denoted by a name, a number, or one of the special
 characters listed in 3.5.2.  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 using the unset special
 built-in command.


 3.5.1  Positional Parameters

 A positional parameter is a parameter denoted by the decimal value
 represented by one or more digits, other than the single digit 0.  When a
 positional parameter with more than one digit is specified, the
 application shall enclose the digits in braces (see 3.6.2).  Positional
 parameters are initially assigned when the shell is invoked (see sh in
 4.56), temporarily replaced when a shell function is invoked (see 3.9.5),
 and can be reassigned with the set special built-in command.

 BEGIN_RATIONALE

 3.5.1.1  Positional Parameters Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t
          _o_f _P_1_0_0_3._2)

 The digits denoting the positional parameters are always interpreted as a
 decimal value, even if there is a leading zero.

 END_RATIONALE



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 228                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.5.2  Special Parameters

 Listed below are the special parameters and the values to which they
 shall expand.  Only the values of the special parameters are listed; see
 3.6 for a detailed summary of all the stages involved in expanding words.

    *     Expands to the positional parameters, starting from one.  When
          the expansion occurs within a double-quoted string (see 3.2.3),
          it expands to a single field with the value of each parameter
          separated by the first character of the IFS variable, or by a
          <space> if IFS is unset.

    @     Expands to the positional parameters, starting from one.  When
          the expansion occurs within double-quotes, each positional
          parameter expands as a separate field, with the provision that
          the expansion of the first parameter is still joined with the
          beginning part of the original word (assuming that the expanded
          parameter was embedded within a word), and the expansion of the
          last parameter is still joined with the last part of the
          original word.  If there are no positional parameters, the        1
          expansion of @ shall generate zero fields, even when @ is         1
          double-quoted.                                                    1

    #     Expands to the decimal number of positional parameters.

    ?     Expands to the decimal exit status of the most recent pipeline
          (see 3.9.2).

    -     (Hyphen) Expands to the current option flags (the single-letter
          option names concatenated into a string) as specified on
          invocation, by the set special built-in command, or implicitly
          by the shell.

    $     Expands to the decimal process ID of the invoked shell.  In a
          subshell (see 3.12), $ shall expand to the same value as that of
          the current shell.

    !     Expands to the decimal process ID of the most recent background
          command (see 3.9.3) executed from the current shell.  For a       1
          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.  See
          sh (4.56) for a detailed description of how this name is
          derived.

 See the description of the IFS variable in 3.5.3.




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.5 Parameters and Variables                                          229





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 BEGIN_RATIONALE


 3.5.2.1  Special Parameters Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
          _P_1_0_0_3._2)

 Most historical implementations implement subshells by forking; thus, the
 special parameter $ does not necessarily represent the process ID of the
 shell process executing the commands since the subshell execution
 environment preserves the value of $.

 If a subshell were to execute a background command, the value of its       1
 parent's $! would not change.  For example:                                1

       (                                                                    1
       date &                                                               1
       echo $!                                                              1
       )                                                                    1
       echo $!                                                              1

 would echo two different values for $!.                                    1

 The descriptions of parameters * and @ assume the reader is familiar with
 the field splitting discussion in 3.6.5 and understands that portions of
 the word will remain concatenated unless there is some reason to split
 them into separate fields.  Some examples of the * and @ properties,
 including the concatenation aspects:

       set "abc" "def ghi" "jkl"

       echo $*         => "abc" "def" "ghi" "jkl"
       echo "$*"       => "abc def ghi jkl"
       echo $@         => "abc" "def" "ghi" "jkl"

       _b_u_t

       echo "$@"       => "abc" "def ghi" "jkl"
       echo "xx$@yy"   => "xxabc" "def ghi" "jklyy"
       echo "$@$@"     => "abc" "def ghi" "jklabc" "def ghi" "jkl"

 In the preceding examples, the double-quote characters that appear after
 the => do not appear in the output and are used only to illustrate word
 boundaries.

 Historical versions of the Bourne shell have used <space> as a separator
 between the expanded members of "$*".  The KornShell has used the first
 character in IFS, which is <space> by default.  If IFS is set to a null    1
 string, this is not equivalent to unsetting it; its first character will   1
 not exist, so the parameter values are concatenated.  For example:         1


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 230                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

       $ IFS=''                                                             1
       $ set foo bar bam                                                    1
       $ echo "$@"                                                          1
       foo bar bam                                                          1
       $ echo "$*"                                                          1
       foobarbam                                                            1
       $ unset IFS                                                          1
       $ echo "$*"                                                          1
       foo bar bam                                                          1

 The $- can be used to save and restore set options:

       Save=$(echo $- | sed 's/[ics]//g')                                   1
       ...
       set +aCefnuvx                                                        2
       set -$Save

 The three options are removed using sed in the example because they may    1
 appear in the value of $- (from the sh command line), but are not valid    1
 options to set.                                                            1

 The command name (parameter 0) is not counted in the number given by #
 because it is a special parameter, not a positional parameter.

 END_RATIONALE


 3.5.3  Variables

 Variables shall be initialized from the environment (as defined by
 POSIX.1 {8}) 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 3.14.8.  New variables can be defined
 and initialized with variable assignments, with the read or getopts
 utilities, with the _n_a_m_e parameter in a for loop (see 3.9.4.2), with the
 ${_n_a_m_e=_w_o_r_d} expansion, or with other mechanisms provided as
 implementation extensions.  The following variables shall affect the
 execution of the shell:

    HOME               This variable shall be interpreted as the pathname
                       of the user's home directory.  The contents of HOME
                       are used in Tilde Expansion (see 3.6.1).

    IFS                _I_n_p_u_t _f_i_e_l_d _s_e_p_a_r_a_t_o_r_s:  a string treated as a list
                       of characters that is used for field splitting and
                       to split lines into fields with the read command.
                       If IFS is not set, the shell shall behave as if the
                       value of IFS were the <space>, <tab>, and <newline>
                       characters.  (See 3.6.5.)


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.5 Parameters and Variables                                          231





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

    LANG               This variable shall provide a default value for the
                       LC_* variables, as described in 2.6.

    LC_ALL             This variable shall interact with the LANG and LC_*
                       variables as described in 2.6.

    LC_COLLATE         This variable shall determine the behavior of range
                       expressions, equivalence classes, and
                       multicharacter collating elements within pattern
                       matching.

    LC_CTYPE           This variable shall determine the interpretation of
                       sequences of bytes of text data as characters
                       (e.g., single- versus multibyte characters), which
                       characters are defined as letters (character class
                       alpha), and the behavior of character classes
                       within pattern matching.

    LC_MESSAGES        This variable shall determine the language in which
                       messages should be written.

    PATH               This variable represents a string formatted as
                       described in 2.6, used to effect command
                       interpretation.  See 3.9.1.1.                        1

 BEGIN_RATIONALE


 3.5.3.1  Variables Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 A description of PWD (which is automatically set by the KornShell
 whenever the current working directory changes) was omitted because its
 functionality is easily reproduced using $(pwd).

 See the discussion of IFS in 3.6.5.1.

 Other common environment variables used by historical shells are not
 specified by this standard, but they should be reserved for the
 historical uses.  For interactive use, other shell variables are expected
 to be introduced by the UPE (and this rationale will be updated
 accordingly):  ENV, FCEDIT, HISTFILE, HISTSIZE, LINENO, PPID, PS1, PS2,
 PS4.

 Tilde expansion for components of the PATH in an assignment such as:

       PATH=~hlj/bin:~dwc/bin:$PATH                                         1

 is a feature of some historical shells and is allowed by the wording of    1
 3.6.1.  Note that the tildes are expanded during the assignment to PATH,   1
 not when PATH is accessed during command search.                           1

               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 232                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 END_RATIONALE                                                              1



 3.6  Word Expansions

 This clause describes the various expansions that are performed on words.
 Not all expansions are performed on every word, as explained in the
 following subclauses.

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

 The order of word expansion shall be as follows:

     (1)  Tilde Expansion (see 3.6.1), Parameter Expansion (see 3.6.2),     1
          Command Substitution (see 3.6.3), and Arithmetic Expansion (see
          3.6.4) shall be performed, beginning to end.  [See item (5) in
          3.3.]

     (2)  Field Splitting (see 3.6.5) shall be performed on fields
          generated by step (1) unless IFS is null.

     (3)  Pathname Expansion (see 3.6.6) shall be performed, unless set -f
          is in effect.

     (4)  Quote Removal (see 3.6.7) shall always be performed last.

 The expansions described in this clause 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 of fields that
 form the completely expanded command, unless the original word contained   1
 single-quote or double-quote characters.                                   1

 The $ character is used to introduce parameter expansion, command
 substitution, or arithmetic evaluation.  If an unquoted $ is followed by
 a character that is either not numeric, the name of one of the special
 parameters (see 3.5.2), a valid first character of a variable name, a
 left curly brace ({), or a left parenthesis, the result is unspecified.

 BEGIN_RATIONALE




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.6 Word Expansions                                                   233





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.6.0.1  Word Expansions Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
          _P_1_0_0_3._2)

 IFS is used for performing field splitting on the results of parameter
 and command substitution; it is not used for splitting all fields.
 Previous versions of the shell used it for splitting all fields during
 field splitting, but this has severe problems because the shell can no
 longer parse its own script.  There are also important security
 implications caused by this behavior.  All useful applications of IFS use
 it for parsing input of the read utility and for splitting the results of
 parameter and command substitution.  New versions of the shell have fixed
 this bug, and POSIX.2 requires the corrected behavior.

 The rule concerning expansion to a single field requires that if foo=abc
 and bar=def, that

       "$foo""$bar"

 expands to the single field

       abcdef

 The rule concerning empty fields can be illustrated by:

       $ unset foo
       $ set $foo bar '' xyz "$foo" abc
       $ for i
       > do
       >       echo "-$i-"
       > done
       -bar-
       --
       -xyz-
       --
       -abc-

 Step (1) indicates that Tilde Expansion, Parameter Expansion, Command      1
 Substitution, and Arithmetic Expansion are all processed simultaneously
 as they are scanned.  For example, the following is valid arithmetic:

       x=1
       echo $(( $(echo 3)+$x ))

 An earlier draft stated that Tilde Expansion preceded the other steps,     1
 but this is not the case in known historical implementations; if it were,  1
 and a referenced home directory contained a $ character, expansions would  1
 result within the directory name.                                          1




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 234                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 END_RATIONALE                                                              1


 3.6.1  Tilde Expansion

 A _t_i_l_d_e-_p_r_e_f_i_x consists of an unquoted tilde character at the beginning
 of a word, followed by all of the characters preceding the first unquoted  2
 slash in the word, or all the characters in the word if there is no        2
 slash.  In an assignment (see 3.1.15), multiple tilde prefixes can be      2
 used:  at the beginning of the word (i.e., following the equals-sign of    2
 the assignment) and/or following any unquoted colon.  A tilde prefix in    2
 an assignment is terminated by the first unquoted colon or slash.  If      2
 none of the characters in the tilde-prefix are quoted, the characters in   1
 the tilde-prefix following the tilde shall be treated as a possible login  1
 name from the user database (see POSIX.1 {8} Section 9).  A portable       2
 login name cannot contain characters outside the set given in the          2
 description of the LOGNAME environment variable in POSIX.1 {8}.  If the    2
 login name is null (i.e., the tilde-prefix contains only the tilde), the
 tilde-prefix shall be replaced by the value of the variable HOME.  If
 HOME is unset, the results are unspecified.  Otherwise, the tilde-prefix
 shall be replaced by a pathname of the home directory associated with the
 login name obtained using the equivalent of the POSIX.1 {8} _g_e_t_p_w_n_a_m()     1
 function.  If the system does not recognize the login name, the results    1
 are undefined.

 BEGIN_RATIONALE


 3.6.1.1  Tilde Expansion Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
          _P_1_0_0_3._2)

                                                                            2

 The text about quoting of the word indicates that \~hlj/, ~h\lj/,          2
 ~"hlj"/, ~hlj\/, and ~hlj/ are not equivalent: only the last will cause    2
 tilde expansion.                                                           2

 Tilde expansion generally occurs only at the beginning of words, but       2
 POSIX.2 has adopted an exception based on historical practice in the       2
 KornShell:                                                                 2

       PATH=/posix/bin:~dgk/bin                                             2

 is eligible for tilde expansion because tilde follows a colon and none of  2
 the relevant characters is quoted.  Consideration was given to             2
 prohibiting this behavior because any of the following are reasonable      2
 substitutes:                                                               2




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.6 Word Expansions                                                   235





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

       PATH=$(printf %s:  rms/bin  bfox/bin ...)                            2
       PATH=$(printf %s  ~karels/bi~n :  bostic/bin)                          2
       for Dir in  maart~/bin  srb/bin ~...                                   2
       do         ~          ~                                              2
               PATH=${PATH:+$PATH:}$Dir                                     2
       done                                                                 2

 (In the first command, any number of directory names are concatenated and  2
 separated with colons, but it may be undesirable to end the variable with  2
 a colon because this is an obsolescent means to include dot at the end of  2
 the PATH.  In the second, explicit colons are used for each directory.     2
 In all cases, the shell performs tilde expansion on each directory         2
 because all are separate words to the shell.)                              2

 The exception was included to avoid breaking numerous KornShell scripts    2
 and interactive users and despite the fact that variable assignments in    2
 scripts derived from other systems will have to use quoting in some cases  2
 to allow literal tildes in strings.  (This latter problem should be        2
 relatively rare because only tildes preceding known login names in         2
 unquoted strings are affected.)                                            2

 Note that expressions in operands such as                                  2

       make -k mumble LIBDIR= chet/lib                                      2
                             ~
 do not qualify as shell variable assignments and tilde expansion is not    2
 performed (unless the command does so itself, which make does not).        2

 In an earlier draft, tilde expansion occurred following any unquoted       2
 equals-sign or colon, but this was removed because of its complexity and   2
 to avoid breaking commands such as:                                        2

       rcp hostname: marc/.profile .                                        2
                    ~
 A suggestion was made that the special sequence ``$ '' should be allowed   2
 to force tilde expansion anywhere.  Since this is n~ot historical           2
 practice, it has been left for future implementations to evaluate.  (The   2
 description in 3.2 requires that a dollar-sign be quoted to represent      2
 itself, so the $  combination is already unspecified.)                     2
                 ~
 The results of giving tilde with an unknown login name are undefined
 because the KornShell  + and  - constructs make use of this condition,
 but in general it is a~n error~to give an incorrect login name with tilde.
 The results of having HOME unset are unspecified because some historical
 shells treat this as an error.

 END_RATIONALE




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 236                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.6.2  Parameter Expansion

 The format for parameter expansion is as follows:

       ${_e_x_p_r_e_s_s_i_o_n}

 where _e_x_p_r_e_s_s_i_o_n consists of all characters until the matching }.  Any }   2
 escaped by a backslash or within a quoted string, and characters in        2
 embedded arithmetic expansions, command substitutions, and variable        2
 expansions, shall not be examined in determining the matching }.

 The simplest form for parameter expansion is:

       ${_p_a_r_a_m_e_t_e_r}

 The value, if any, of _p_a_r_a_m_e_t_e_r shall be substituted.

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

 If the parameter name or symbol is not enclosed in braces, the expansion
 shall use the longest valid name (see 3.1.5), whether or not the symbol
 represented by that name exists.  If a parameter expansion occurs inside
 double-quotes:

     - Pathname expansion shall not be performed on the results of the
       expansion.

     - Field splitting shall not be performed on the results of the
       expansion, with the exception of @; see 3.5.2.

 In addition, a parameter expansion can be modified by using one of the
 following formats.  In each case that a value of _w_o_r_d is needed (based on
 the state of _p_a_r_a_m_e_t_e_r, as described below), _w_o_r_d shall be subjected to
 tilde expansion, parameter expansion, command substitution, and
 arithmetic expansion.  If _w_o_r_d is not needed, it shall not be expanded.
 The } character that delimits the following parameter expansion            1
 modifications shall be determined as described previously in this          1
 subclause and in 3.2.3.  (For example, ${foo-bar}xyz} would result in the  1
 expansion of foo followed by the string xyz} if foo is set, else the
 string barxyz}).






               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.6 Word Expansions                                                   237





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

    ${_p_a_r_a_m_e_t_e_r:-_w_o_r_d}       Use Default Values.  If _p_a_r_a_m_e_t_e_r is unset or
                             null, the expansion of _w_o_r_d shall be
                             substituted; otherwise, the value of
                             _p_a_r_a_m_e_t_e_r shall be substituted.

    ${_p_a_r_a_m_e_t_e_r:=_w_o_r_d}       Assign Default Values.  If _p_a_r_a_m_e_t_e_r is unset
                             or null, the expansion of _w_o_r_d shall be
                             assigned to _p_a_r_a_m_e_t_e_r.  In all cases, the
                             final value of _p_a_r_a_m_e_t_e_r shall be
                             substituted.  Only variables, not positional
                             parameters or special parameters, can be
                             assigned in this way.

    ${_p_a_r_a_m_e_t_e_r:?[_w_o_r_d]}     Indicate Error if Null or Unset.  If
                             _p_a_r_a_m_e_t_e_r is unset or null, the expansion of
                             _w_o_r_d (or a message indicating it is unset if
                             _w_o_r_d is omitted) shall be written to standard
                             error and the shell shall exit with a nonzero
                             exit status.  Otherwise, the value of
                             _p_a_r_a_m_e_t_e_r shall be substituted.  An
                             interactive shell need not exit.

    ${_p_a_r_a_m_e_t_e_r:+_w_o_r_d}       Use Alternate Value.  If _p_a_r_a_m_e_t_e_r is unset
                             or null, null shall be substituted;
                             otherwise, the expansion of _w_o_r_d shall be
                             substituted.

 In the parameter expansions shown previously, use of the colon in the
 format results in a test for a parameter that is unset or null; omission
 of the colon results in a test for a parameter that is only unset.

    ${#_p_a_r_a_m_e_t_e_r}            String Length.  The length in characters of
                             the value of _p_a_r_a_m_e_t_e_r. If _p_a_r_a_m_e_t_e_r is * or
                             @, the result of the expansion is
                             unspecified.

 The following four varieties of parameter expansion provide for substring
 processing.  In each case, pattern matching notation (see 3.13), rather
 than regular expression notation, shall be used to evaluate the patterns.
 If _p_a_r_a_m_e_t_e_r is * or @, the result of the expansion is unspecified.
 Enclosing the full parameter expansion string in double-quotes shall not   1
 cause the following four varieties of pattern characters to be quoted,     1
 whereas quoting characters within the braces shall have this effect.

    ${_p_a_r_a_m_e_t_e_r%_w_o_r_d}        Remove Smallest Suffix Pattern.  The _w_o_r_d
                             shall be expanded to produce a pattern.  The
                             parameter expansion then shall result in
                             _p_a_r_a_m_e_t_e_r, with the smallest portion of the
                             suffix matched by the _p_a_t_t_e_r_n deleted.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 238                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

    ${_p_a_r_a_m_e_t_e_r%%_w_o_r_d}       Remove Largest Suffix Pattern.  The _w_o_r_d
                             shall be expanded to produce a pattern.  The
                             parameter expansion then shall result in
                             _p_a_r_a_m_e_t_e_r, with the largest portion of the
                             suffix matched by the _p_a_t_t_e_r_n deleted.

    ${_p_a_r_a_m_e_t_e_r#_w_o_r_d}        Remove Smallest Prefix Pattern.  The _w_o_r_d
                             shall be expanded to produce a pattern.  The
                             parameter expansion then shall result in
                             _p_a_r_a_m_e_t_e_r, with the smallest portion of the
                             prefix matched by the _p_a_t_t_e_r_n deleted.

    ${_p_a_r_a_m_e_t_e_r##_w_o_r_d}       Remove Largest Prefix Pattern.  The _w_o_r_d
                             shall be expanded to produce a pattern.  The
                             parameter expansion then shall result in
                             _p_a_r_a_m_e_t_e_r, with the largest portion of the
                             prefix matched by the _p_a_t_t_e_r_n deleted.

 BEGIN_RATIONALE


 3.6.2.1  Parameter Expansion Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
          _P_1_0_0_3._2)

 When the shell is scanning its input to determine the boundaries of a
 name, it is not bound by its knowledge of what names are already defined.
 For example, if F is a defined shell variable, the command "echo $Fred"
 does not echo the value of $F followed by red; it selects the longest
 possible valid name, Fred, which in this case might be unset.

 The rule for finding the closing } in ${...} is the one used in the
 KornShell and is upward compatible with the Bourne shell, which does not
 determine the closing } until the word is expanded.  The advantage of
 this is that incomplete expansions, such as

       ${foo

 can be determined during tokenization, rather than during expansion.

 The four expansions with the optional colon have been hard to understand
 from the historical documentation.  The following table summarizes the
 effect of the colon:









               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.6 Word Expansions                                                   239





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

                             _pppp_aaaa_rrrr_aaaa_mmmm_eeee_tttt_eeee_rrrr        _pppp_aaaa_rrrr_aaaa_mmmm_eeee_tttt_eeee_rrrr     _pppp_aaaa_rrrr_aaaa_mmmm_eeee_tttt_eeee_rrrr
                          set and not null   set but null     unset
                          ________________   ____________   __________
     ${_p_a_r_a_m_e_t_e_r:-_w_o_r_d}      substitute       substitute    substitute
                             _p_a_r_a_m_e_t_e_r           _w_o_r_d          _w_o_r_d

     ${_p_a_r_a_m_e_t_e_r-_w_o_r_d}       substitute       substitute    substitute
                             _p_a_r_a_m_e_t_e_r           null          _w_o_r_d

     ${_p_a_r_a_m_e_t_e_r:=_w_o_r_d}      substitute         assign        assign
                             _p_a_r_a_m_e_t_e_r           _w_o_r_d          _w_o_r_d

     ${_p_a_r_a_m_e_t_e_r=_w_o_r_d}       substitute       substitute      assign
                             _p_a_r_a_m_e_t_e_r        _p_a_r_a_m_e_t_e_r        _w_o_r_d

     ${_p_a_r_a_m_e_t_e_r:?_w_o_r_d}      substitute         error,        error,
                             _p_a_r_a_m_e_t_e_r           exit          exit

     ${_p_a_r_a_m_e_t_e_r?_w_o_r_d}       substitute       substitute      error,
                             _p_a_r_a_m_e_t_e_r           null          exit

     ${_p_a_r_a_m_e_t_e_r:+_w_o_r_d}      substitute       substitute    substitute
                                _w_o_r_d             null          null         1

     ${_p_a_r_a_m_e_t_e_r+_w_o_r_d}       substitute       substitute    substitute
                                _w_o_r_d             _w_o_r_d          null         1


 In all cases shown with ``substitute,'' the expression is replaced with
 the value shown.  In all cases shown with ``assign,'' _p_a_r_a_m_e_t_e_r is
 assigned that value, which also replaces the expression.

 The string length and substring capabilities were included because of the
 demonstrated need for them, based on their usage in other shells, such as
 C-shell and KornShell.

 Historical versions of the KornShell have not performed tilde expansion
 on the word part of parameter expansion; however, it is more consistent
 to do so.












               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 240                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 _E_x_a_m_p_l_e_s

    ${_p_a_r_a_m_e_t_e_r:-_w_o_r_d}

                In this example, ls is executed only if x is null or
                unset.  [The $(ls) command substitution notation is
                explained in 3.6.3.]

                ${x:-$(ls)}

    ${_p_a_r_a_m_e_t_e_r:=_w_o_r_d}

                unset X
                echo ${X:=abc}
                abc

    ${_p_a_r_a_m_e_t_e_r:?_w_o_r_d}

                unset posix
                echo ${posix:?}
                sh: posix: parameter null or not set

    ${_p_a_r_a_m_e_t_e_r:+_w_o_r_d}

                set a b c
                echo ${3:+posix}
                posix

    ${#_p_a_r_a_m_e_t_e_r}

                HOME=/usr/posix
                echo ${#HOME}
                10

    ${_p_a_r_a_m_e_t_e_r%_w_o_r_d}

                x=file.c
                echo ${x%.c}.o
                file.o

    ${_p_a_r_a_m_e_t_e_r%%_w_o_r_d}

                x=posix/src/std
                echo ${x%%/*}
                posix






               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.6 Word Expansions                                                   241





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

    ${_p_a_r_a_m_e_t_e_r#_w_o_r_d}

                x=$HOME/src/cmd
                echo ${x#$HOME}
                /src/cmd

    ${_p_a_r_a_m_e_t_e_r##_w_o_r_d}

                x=/one/two/three
                echo ${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_RATIONALE


 3.6.3  Command Substitution

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

       $(_c_o_m_m_a_n_d)

 or (``backquoted'' version):

       `_c_o_m_m_a_n_d`

 The shell shall expand the command substitution by executing _c_o_m_m_a_n_d in a
 subshell environment (see 3.12) and replacing the command substitution
 [the text of _c_o_m_m_a_n_d plus the enclosing $( ) or backquotes] with the
 standard output of the command, removing sequences of one or more
 <newline>s at the end of the substitution.  (Embedded <newline>s before
 the end of the output shall not be removed; however, during field
 splitting, they may be translated into <space>s, depending on the value
 of IFS and quoting that is in effect.)

 Within the backquoted style of command substitution, backslash shall
 retain its literal meaning, except when followed by

       $  `  \

 (dollar-sign, backquote, backslash).  The search for the matching          2


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 242                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 backquote shall be satisfied by the first backquote found without a        2
 preceding backslash; during this search, if a nonescaped backquote is      2
 encountered within a shell comment, a here-document, an embedded command   2
 substitution of the $(_c_o_m_m_a_n_d) form, or a quoted string, undefined         2
 results occur.  A single- or double-quoted string that begins, but does
 not end, within the `...` sequence produces undefined results.

 With the $(_c_o_m_m_a_n_d) form, all characters following the open parenthesis
 to the matching closing parenthesis constitute the _c_o_m_m_a_n_d. Any valid      2
 shell script can be used for _c_o_m_m_a_n_d, except:                              2

     - A script consisting solely of redirections produces unspecified      2
       results.                                                             2

     - See the restriction on single subshells described below.             2

 The results of command substitution shall not be processed for further     1
 tilde expansion, parameter expansion, command substitution, or arithmetic  1
 expansion.  If a command substitution occurs inside double-quotes, field
 splitting and pathname expansion 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 inner backquotes
 with backslashes; for example,

       \`_c_o_m_m_a_n_d\`

 If the command substitution consists of a single subshell, such as

       $( (_c_o_m_m_a_n_d) )

 a conforming application shall separate the $( and ( into two tokens
 (i.e., separate them with white space).

 BEGIN_RATIONALE


 3.6.3.1  Command Substitution Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
          _P_1_0_0_3._2)

 The new $( ) form of command substitution was adopted from the KornShell
 to solve a problem of inconsistent behavior when using backquotes.  For
 example:

                        _____C_o_m_m_a_n_d_______   O_u_t_p_u_t_
                        echo '\$x'           \$x




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.6 Word Expansions                                                   243





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

                        echo `echo '\$x'`    $x
                        echo $(echo '\$x')   \$x

 Additionally, the backquoted syntax has historical restrictions on the     2
 contents of the embedded command.  While the new $( ) form can process     2
 any kind of valid embedded script, the backquoted cannot handle some       2
 valid scripts that include backquotes.  For example, these otherwise       2
 valid embedded scripts do not work in the left column, but do work on the  2
 right:                                                                     2

         echo `                        echo $(                              2
         cat <<\eof                    cat <<\eof                           2
         a here-doc with `             a here-doc with )                    2
         eof                           eof                                  2
         `                             )                                    2

         echo `                        echo $(                              2
         echo abc # a comment with `   echo abc # a comment with )          2
         `                             )                                    2

         echo `                        echo $(                              2
         echo '`'                      echo ')'                             2
         `                             )                                    2

 Some historical KornShell implementations did not process the first two    2
 examples correctly, but the author has agreed to make the appropriate      2
 modifications to do so.  The KornShell will also be modified so that the   2
 following works:                                                           2

       echo $(                                                              2
               case word in                                                 2
                       [Ff]oo) echo found foo ;;                            2
               esac                                                         2
       )                                                                    2

 Because of these inconsistent behaviors, the backquoted variety of
 command substitution is not recommended for new applications that nest
 command substitutions or attempt to embed complex scripts.  Because of     2
 its widespread historical use, particularly by interactive users,
 however, the backquotes were retained in POSIX.2 without being declared
 obsolescent.

 The KornShell feature:

       If _c_o_m_m_a_n_d is of the form <_w_o_r_d, _w_o_r_d is expanded to generate a
       pathname, and the value of the command substitution is the contents
       of this file with any trailing <newline>_s deleted.




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 244                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 was omitted from this standard because $(cat word) is an appropriate
 substitute.  However, to prevent breaking numerous scripts relying on      2
 this feature, it is unspecified to have a script within $( ) that has      2
 only redirections.                                                         2

 The requirement to separate $( and ( when a single subshell is command-
 substituted is to avoid any ambiguities with Arithmetic Expansion.  See
 3.6.4.1.

 END_RATIONALE


 3.6.4  Arithmetic Expansion

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

       $((_e_x_p_r_e_s_s_i_o_n))

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

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

     (1)  Only integer arithmetic is required.

     (2)  The sizeof() operator and the prefix and postfix ++ and --
          operators are not required.

     (3)  Selection, Iteration, and Jump Statements are not supported.

 As an extension, the shell may recognize arithmetic expressions beyond
 those listed.  If the expression is invalid, the expansion fails and the
 shell shall write a message to standard error indicating the failure.

 BEGIN_RATIONALE









               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.6 Word Expansions                                                   245





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.6.4.1  Arithmetic Expansion Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
          _P_1_0_0_3._2)

 Numerous ballots were received objecting to the inclusion of the (( ))
 form of KornShell arithmetic in previous drafts.  The developers of the
 standard concluded that there is a strong desire for some kind of
 arithmetic evaluator to replace expr, and that tying it in with $ makes
 it fit in nicely with the standard shell language, and provides access to
 arithmetic evaluation in places where accessing a utility would be
 inconvenient or clumsy.

 Following long debate by interested members of the balloting group, the
 syntax and semantics for arithmetic were changed.  The language is
 essentially a pure arithmetic evaluator of constants and operators
 (excluding assignment) and represents a simple subset of the previous
 arithmetic language [which was derived from the KornShell's (( ))
 construct].  The syntax was changed from that of a command denoted by
 ((_e_x_p_r_e_s_s_i_o_n)), to an expansion denoted by $((_e_x_p_r_e_s_s_i_o_n)).  The new form
 is a dollar expansion ($), which evaluates the expression and substitutes
 the resulting value.  Objections to the previous style of arithmetic
 included that it was too complicated, did not fit in well with the
 shell's use of variables, and the syntax conflicted with subshells.  The
 justification for the new syntax is that the shell is traditionally a
 macro language, and if a new feature is to be added, it should be done by
 extending the capabilities presented by the current model of the shell,
 rather than by inventing a new one outside the model:  adding a new
 dollar expansion was perceived to be the most intuitive and least
 destructive way to add such a new capability.

 In Drafts 9 and 10, a form $[_e_x_p_r_e_s_s_i_o_n] was used.  It was functionally
 equivalent to the $(( )) of the current text, but objections were lodged
 that the 1988 KornShell had already implemented $(( )) and there was no
 compelling reason to invent yet another syntax.  Furthermore, the $[]
 syntax had a minor incompatibility involving the patterns in case
 statements.

 The portion of the C Standard {7} arithmetic operations selected
 corresponds to the operations historically supported in the KornShell.

 A simple example using arithmetic expansion:

       # repeat a command 100 times
       x=100
       while [ $x -gt 0 ]
       do
               _c_o_m_m_a_n_d
               x=$(($x-1))
       done



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 246                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 It was concluded that the test command ([) was sufficient for the
 majority of relational arithmetic tests, and that tests involving
 complicated relational expressions within the shell are rare, yet could
 still be accommodated by testing the value of $(()) itself.  For example:

       # a complicated relational expression
       while [ $(( (($x + $y)/($a * $b)) < ($foo*$bar) )) -ne 0 ]

 or better yet, the rare script that has many complex relational
 expressions could define a function like this:

       val() {
               return $((!$1))
       }

 and complicated tests would be less intimidating:

       while val $(( (($x + $y)/($a * $b)) < ($foo*$bar) ))
       do
               # some calculations
       done

 Another suggestion was to modify true and false to take an optional
 argument, and true would exit true only if the argument is nonzero, and
 false would exit false only if the argument is nonzero.  The suggestion
 was not favorably received by the balloting group (those contacted were
 negative about it, all others were silent in their latest ballots).

       while true $(($x > 5 && $y <= 25))

 There is a minor portability concern with the new syntax.  The example
 $((2+2)) could have been intended to mean a command substitution of a
 utility named 2+2 in a subshell.  The developers of POSIX.2 consider this
 to be obscure and isolated to some KornShell scripts [because $( )
 command substitution existed previously only in the KornShell].  The text
 on Command Substitution has been changed to require that the $( and ( be
 separate tokens if this usage is needed.

 An example such as

       echo $((echo hi);(echo there))

 should not be misinterpreted by the shell as arithmetic because attempts
 to balance the parentheses pairs would indicate that they are subshells.   1
 However, as indicated by 3.1.1, a conforming application must separate     1
 two adjacent parentheses with white space to indicate nested subshells.    1

 END_RATIONALE                                                              1



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.6 Word Expansions                                                   247





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.6.5  Field Splitting

 After parameter expansion (3.6.2), command substitution (3.6.3), and
 arithmetic expansion (3.6.4) the shell shall scan the results of
 expansions and substitutions that did not occur in double-quotes for
 field splitting and multiple fields can result.

 The shell shall treat each character of the IFS as a delimiter and use
 the delimiters to split the results of parameter expansion and command
 substitution into fields.

     (1)  If the value of IFS is <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 of those characters within the input shall
          delimit a field.  (For example, the input

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

          yields two fields, foo and bar).

     (2)  If the value of IFS is null, no field splitting shall be
          performed.

     (3)  Otherwise, the following rules shall be applied in sequence.      1
          The term ``IFS white space'' is used to mean any sequence (zero   1
          or more instances) of white-space characters that are in the IFS  1
          value (e.g., if IFS contains <space><comma><tab>, any sequence    1
          of <space> and <tab> characters is considered IFS white space).   1

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

           (b)  Each occurrence in the input of an IFS character that is    1
                not IFS white space, along with any adjacent IFS white      1
                space, shall delimit a field, as described previously.      1

           (c)  Nonzero-length IFS white space shall delimit a field.       1

 BEGIN_RATIONALE


 3.6.5.1  Field Splitting Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
          _P_1_0_0_3._2)

 The operation of field splitting using IFS as described in earlier drafts
 was based on the way the KornShell splits words, but is incompatible with
 other common versions of the shell.  However, each has merit, and so a
 decision was made to allow both.  If the IFS variable is unset, or is
 <space><tab><newline>, the operation is equivalent to the way the

               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 248                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 System V shell splits words.  Using characters outside the
 <space><tab><newline> set yields the KornShell behavior, where each of
 the non-<space><tab><newline> characters is significant.  This behavior,
 which affords the most flexibility, was taken from the way the original
 awk handled field splitting.

 The (3) rule can be summarized as a pseudo ERE:                            1

       (s*ns*|s+)                                                           1

 where s is an IFS white-space character and n is a character in the IFS    1
 that is not white space.  Any string matching that ERE delimits a field,   1
 except that the s+ form does not delimit fields at the beginning or the    1
 end of a line.  For example, if IFS is <space><comma>, the string          1

       <space><space>red<space><space>,<space>white<space>blue              1

 yields the three colors as the delimited fields.                           1

 END_RATIONALE                                                              1


 3.6.6  Pathname Expansion

 After field splitting, if set -f is not in effect, each field in the
 resulting command line shall be expanded using the algorithm described in
 3.13, qualified by the rules in 3.13.3.


 3.6.7  Quote Removal

 The quote characters

       \  '  "

 (backslash, single-quote, double-quote) that were present in the original
 word shall be removed unless they have themselves been quoted.



 3.7  Redirection

 Redirection is used to open and close files for the current shell
 execution environment (see 3.12) or for any command.  _R_e_d_i_r_e_c_t_i_o_n
 _o_p_e_r_a_t_o_r_s can be used with numbers representing file descriptors (see the
 definition in POSIX.1 {8}) as described below.  See also 2.9.1.  The
 relationship between these file descriptors and access to them in a
 programming language is specified in the language binding for that
 language to this standard.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.7 Redirection                                                       249





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 The overall format used for redirection is:

       [_n]_r_e_d_i_r-_o_p   _w_o_r_d

 The number _n is an optional decimal number designating the file
 descriptor number; it shall be delimited from any preceding text and
 immediately precede the redirection operator _r_e_d_i_r-_o_p. If _n is quoted,
 the number shall not be recognized as part of the redirection expression.
 (For example, echo \2>a writes the character 2 into file a).  If any part
 of _r_e_d_i_r-_o_p is quoted, no redirection expression shall be recognized.
 (For example, echo 2\>a writes the characters 2>a to standard output.)
 The optional number, redirection operator, and _w_o_r_d shall not appear in
 the arguments provided to the command to be executed (if any).

 In this standard, open files are represented by decimal numbers starting
 with zero.  It is implementation defined what the largest value can be;
 however, all implementations shall support at least 0 through 9 for use
 by the application.  These numbers are called _f_i_l_e _d_e_s_c_r_i_p_t_o_r_s.  The
 values 0, 1, and 2 have special meaning and conventional uses and are
 implied by certain redirection operations; they are referred to as
 _s_t_a_n_d_a_r_d _i_n_p_u_t, _s_t_a_n_d_a_r_d _o_u_t_p_u_t, and _s_t_a_n_d_a_r_d _e_r_r_o_r, respectively.
 Programs usually take their input from standard input, and write output
 on standard output.  Error messages are usually written to standard
 error.  The redirection operators can be preceded by one or more digits
 (with no intervening <blank>s allowed) to designate the file descriptor
 number.

 If the redirection operator is << or <<-, the word that follows the
 redirection operator shall be subjected to quote removal; it is
 unspecified whether any of the other expansions occur.  For the other
 redirection operators, the word that follows the redirection operator
 shall be subjected to tilde expansion, parameter expansion, command
 substitution, arithmetic expansion, and quote removal.  Pathname
 expansion shall not be performed on the word by a noninteractive shell;
 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.

 In the following description of redirections, references are made to
 opening and creating files.  These references shall conform to the
 requirements in 2.9.1.4.  A failure to open or create a file shall cause
 the redirection to fail.







               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 250                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.7.1  Redirecting Input

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

 The general format for redirecting input is:

       [_n]<_w_o_r_d

 where the optional _n represents the file descriptor number.  If the
 number is omitted, the redirection shall refer to standard input (file
 descriptor 0).


 3.7.2  Redirecting Output

 The two general formats for redirecting output are:

       [_n]>_w_o_r_d
       [_n]>|_w_o_r_d

 where the optional _n represents the file descriptor number.  If the
 number is omitted, the redirection shall refer to standard output (file
 descriptor 1).

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


 3.7.3  Appending Redirected Output

 Appended output redirection shall cause the file whose name results from
 the expansion of word to be opened for output on the designated file
 descriptor.  The file is opened as if the POSIX.1 {8} _o_p_e_n() function was
 called with the O_APPEND flag.  If the file does not exist, it shall be
 created.

 The general format for appending redirected output is as follows:

       [_n]>>_w_o_r_d

 where the optional _n represents the file descriptor number.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.7 Redirection                                                       251





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.7.4  Here-Document

 The redirection operators << and <<- both allow redirection of lines
 contained in a shell input file, known as a _h_e_r_e-_d_o_c_u_m_e_n_t, to the
 standard input of a command.

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

       [_n]<<_w_o_r_d
               _h_e_r_e-_d_o_c_u_m_e_n_t
       _d_e_l_i_m_i_t_e_r

 If any character in _w_o_r_d is quoted, the delimiter shall be formed by
 performing quote removal on _w_o_r_d, and the here-document lines shall not
 be expanded.  Otherwise, the delimiter shall be the _w_o_r_d itself.

 If no characters in _w_o_r_d are quoted, all lines of the here-document shall
 be expanded for parameter expansion, command substitution, and arithmetic
 expansion.  In this case, the backslash in the input shall behave as the
 backslash inside double-quotes (see 3.2.3).  However, the double-quote
 character (") shall not be treated specially within a here-document,
 except when the double-quote appears within $( ), ` `, or ${ }.            1

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


 3.7.5  Duplicating an Input File Descriptor

 The redirection operator

       [_n]<&_w_o_r_d

 is used to duplicate one input file descriptor from another, or to close
 one.  If _w_o_r_d evaluates to one or more digits, the file descriptor
 denoted by _n, or standard input if _n is not specified, shall be made to
 be a copy of the file descriptor denoted by _w_o_r_d; if the digits in _w_o_r_d
 do not represent a file descriptor already open for input, a redirection   1
 error shall result (see 3.8.1).  If _w_o_r_d evaluates to -, file descriptor   1
 _n, or standard input if _n is not specified, shall be closed.  If _w_o_r_d
 evaluates to something else, the behavior is unspecified.




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 252                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.7.6  Duplicating an Output File Descriptor

 The redirection operator

       [_n]>&_w_o_r_d

 is used to duplicate one output file descriptor from another, or to close
 one.  If _w_o_r_d evaluates to one or more digits, the file descriptor
 denoted by _n, or standard output if _n is not specified, shall be made to
 be a copy of the file descriptor denoted by _w_o_r_d; if the digits in _w_o_r_d
 do not represent a file descriptor already open for output, a redirection  1
 error shall result (see 3.8.1).  If _w_o_r_d evaluates to -, file descriptor   1
 _n, or standard output if _n is not specified, shall be closed.  If _w_o_r_d
 evaluates to something else, the behavior is unspecified.


 3.7.7  Open File Descriptors for Reading and Writing.

 The redirection operator

       [_n]<>_w_o_r_d

 shall cause the file whose name is the expansion of _w_o_r_d to be opened for
 both reading and writing on the file descriptor denoted by _n, or standard
 input if _n is not specified.  If the file does not exist, it shall be
 created.

 BEGIN_RATIONALE


 3.7.8  Redirection Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 In the C binding for POSIX.1 {8}, file descriptors are integers in the
 range 0 - ({OPEN_MAX}-1).  The file descriptors discussed in Redirection
 are that same set of small integers.

 As POSIX.2 is being finalized, it is not known how file descriptors will
 be represented in the language-independent description of POSIX.1 {8}.
 The current consensus appears to be that they will remain as small
 integers, but it is still possible that they will be defined as an opaque
 type.  If they remain as integers, then the current POSIX.2 wording is
 acceptable.  If they become an opaque type, then the C binding to
 POSIX.1 {8} will have to define the mapping from the binding's small
 integers to the opaque type, and the Redirection clause in POSIX.2 will
 have to be modified to specify that same mapping.

 Having multidigit file descriptor numbers for I/O redirection can cause
 some obscure compatibility problems.  Specifically, scripts that depend
 on an example command:


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.7 Redirection                                                       253





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

       echo 22>/dev/null

 echoing "2" are somewhat broken to begin with.  However, the file
 descriptor number still must be delimited from the preceding text.  For
 example,

       cat file2>foo

 will write the contents of file2, not the contents of file.

 The >| format of output redirection was adopted from the KornShell.
 Along with the _n_o_c_l_o_b_b_e_r option, set -C, it provides a safety feature to
 prevent inadvertent overwriting of existing files.  (See the rationale
 with the pathchk utility for why this step was taken.)  The restriction
 on regular files is historical practice.

 The System V shell and the KornShell have differed historically on
 pathname expansion of _w_o_r_d; the former never performed it, the latter
 only when the result was a single field (file).  As a compromise, it was
 decided that the KornShell functionality was useful, but only as a
 shorthand device for interactive users.  No reasonable shell script would
 be written with a command such as:

       cat foo > a*

 Thus, shell scripts are prohibited from doing it, while interactive users
 can select the shell with which they are most comfortable.

 The construct 2>&1 is often used to redirect standard error to the same
 file as standard output.  Since the redirections take place beginning to
 end, the order of redirections is significant.  For example:

       ls > foo 2>&1

 directs both standard output and standard error to file foo.  However

       ls 2>&1 > foo

 only directs standard output to file foo because standard error was
 duplicated as standard output before standard output was directed to file
 foo.

 The <> operator is a feature first documented in the KornShell, but it
 has been silently present in both System V and BSD shells.  It could be
 useful in writing an application that worked with several terminals, and
 occasionally wanted to start up a shell.  That shell would in turn be
 unable to run applications that run from an ordinary controlling terminal  1
 unless it could make use of <> redirection.  The specific example is a     1
 historical version of the pager more, which reads from standard error to


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 254                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 get its commands, so standard input and standard output are both
 available for their usual usage.  There is no way of saying the following
 in the shell without <>:

       cat food | more - >/dev/tty03 2<>/dev/tty03

 Another example of <> is one that opens /dev/tty on file descriptor 3 for
 reading and writing:

       exec 3<> /dev/tty

 An example of creating a lock file for a critical code region:

       set -C
       until   2> /dev/null > lockfile
       do      sleep 30
       done
       set +C
       _p_e_r_f_o_r_m _c_r_i_t_i_c_a_l _f_u_n_c_t_i_o_n
       rm lockfile

 Since /dev/null is not a regular file, no error is generated by
 redirecting to it in _n_o_c_l_o_b_b_e_r mode.

 The case of a missing delimiter at the end of a here-document is not
 specified.  This is considered an error in the script (one that sometimes
 can be difficult to diagnose), although some systems have treated end-
 of-file as an implicit delimiter.

 Tilde expansion is not performed on a here-document because the data is    1
 treated as if it were enclosed in double-quotes.                           1

 END_RATIONALE                                                              1



 3.8  Exit Status and Errors


 3.8.1  Consequences of Shell Errors

 For a noninteractive shell, an error condition encountered by a special
 built-in (see 3.14) or other type of utility shall cause the shell to
 write a diagnostic message to standard error and exit as shown in the
 following table:

                                     S_p_e_c_i_a_l__B_u_i_l_t_-_i_n_ O_t_h_e_r__U_t_i_l_i_t_i_e_s_




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.8 Exit Status and Errors                                            255





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

      Shell language syntax error       shall exit      shall exit
      Utility syntax error (option      shall exit    shall not exit
      or operand error)
      Redirection error                 shall exit    shall not exit
      Variable assignment error         shall exit    shall not exit
      Expansion error                   shall exit      shall exit
      Command not found                    n/a           may exit
      dot script not found              shall exit          n/a

 An ``expansion error'' is one that occurs when the shell expansions
 defined in 3.6 are carried out (e.g., ${x!y}, because ! is not a valid
 operator); an implementation may treat these as syntax errors if it is
 able to detect them during tokenization, rather than during expansion.

 If any of the errors shown as ``shall (may) exit'' occur in a subshell,
 the subshell shall (may) exit with a nonzero status, but the script
 containing the subshell shall not exit because of the error.

 In all of the cases shown in the table, an interactive shell shall write
 a diagnostic message to standard error without exiting.


 3.8.2  Exit Status for Commands

 Each command has an exit status that can influence the behavior of other
 shell commands.  The exit status of commands that are not utilities are
 documented in this subclause.  The exit status of the standard utilities
 are documented in their respective clauses.

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

 If a command fails during word expansion or redirection, its exit status
 shall be greater than zero.

 Internally, for purposes of deciding if a command exits with a nonzero
 exit status, the shell shall recognize the entire status value retrieved
 for the command by the equivalent of the POSIX.1 {8} _w_a_i_t() function
 WEXITSTATUS macro.  When reporting the exit status with the special
 parameter ?, the shell shall report the full eight bits of exit status
 available.  The exit status of a command that terminated because it
 received a signal shall be reported as greater than 128.

 BEGIN_RATIONALE




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 256                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.8.3  Exit Status and Errors Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
        _P_1_0_0_3._2)

 There is a historical difference in sh and ksh noninteractive error
 behavior.  When a command named in a script is not found, some
 implementations of sh exit immediately, but ksh continues with the next
 command.  Thus, POSIX.2 says that the shell ``may'' exit in this case.
 This puts a small burden on the programmer, who will have to test for
 successful completion following a command if it is important that the
 next command not be executed if the previous was not found.  If it is
 important for the command to have been found, it was probably also
 important for it to complete successfully.  The test for successful
 completion would not need to change.

 Historically, shells have returned an exit status of 128+_n, where _n
 represents the signal number.  Since signal numbers are not standardized,
 there is no portable way to determine which signal caused the
 termination.  Also, it is possible for a command to exit with a status in
 the same range of numbers that the shell would use to report that the
 command was terminated by a signal.  Implementations are encouraged to     1
 chose exit values greater than 256 to indicate programs that terminated    1
 by a signal so that the exit status cannot be confused with an exit        1
 status generated by a normal termination.                                  1

 Historical shells make the distinction between ``utility not found'' and   1
 ``utility found but cannot execute'' in their error messages.  By          1
 specifying two seldomly used exit status values for these cases, 127 and   1
 126 respectively, this gives an application the opportunity to make use    1
 of this distinction without having to parse an error message that would    1
 probably change from locale to locale.  The POSIX.2 command, env, nohup,   1
 and xargs utilities also have been specified to use this convention.       1

 When a command fails during word expansion or redirection, most
 historical implementations exit with a status of 1.  However, there was
 some sentiment that this value should probably be much higher, so that an
 application could distinguish this case from the more normal exit status
 values.  Thus, the language ``greater than zero'' was selected to allow
 either method to be implemented.

 END_RATIONALE











               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.8 Exit Status and Errors                                            257





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.9  Shell Commands

 This clause describes the basic structure of shell commands.  The
 following command descriptions each describe a format of the command that
 is only used to aid the reader in recognizing the command type, and does
 not formally represent the syntax.  Each description discusses the
 semantics of the command; for a formal description of the command
 language, consult the grammar in 3.10.

 A _c_o_m_m_a_n_d is one of the following:

     - _s_i_m_p_l_e _c_o_m_m_a_n_d (see 3.9.1)

     - _p_i_p_e_l_i_n_e (see 3.9.2)

     - _l_i_s_t or _c_o_m_p_o_u_n_d-_l_i_s_t (see 3.9.3)

     - _c_o_m_p_o_u_n_d _c_o_m_m_a_n_d (see 3.9.4)

     - _f_u_n_c_t_i_o_n _d_e_f_i_n_i_t_i_o_n (see 3.9.5).

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

 BEGIN_RATIONALE


 3.9.0.1  Shell Commands Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
          _P_1_0_0_3._2)

 A description of an ``empty command'' was removed from an earlier draft    1
 because it is only relevant in the cases of sh -c  "", system(""), or an   1
 empty shell-script file (such as the implementation of true on some        1
 historical systems).  Since it is no longer mentioned in POSIX.2, it       1
 falls into the silently unspecified category of behavior where             1
 implementations can continue to operate as they have historically, but     1
 conforming applications will not construct empty commands.  (However,      1
 note that sh does explicitly state an exit status for an empty string or   1
 file.)  In an interactive session or a script with other commands, extra
 <newline>s or semicolons, such as

       $ false
       $
       $ echo $?
       1

 would not qualify as the empty command described here because they would
 be consumed by other parts of the grammar.

               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 258                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 END_RATIONALE


 3.9.1  Simple Commands

 A _s_i_m_p_l_e _c_o_m_m_a_n_d is a sequence of optional variable assignments and
 redirections, in any sequence, optionally followed by words and
 redirections, terminated by a control operator.

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

     (1)  The words that are recognized as variable assignments or
          redirections according to 3.10.2 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 shall be the arguments for the command.

     (3)  Redirections shall be performed as described in 3.7.

     (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 for
 the processing of special built-in utilities.  See 3.14.

 If no command name results, variable assignments shall affect the current
 execution environment.  Otherwise, the variable assignments shall be
 exported for the execution environment of the command and shall not
 affect the current execution environment (except for special built-ins).
 If any of the variable assignments attempt to assign a value to a read-
 only variable, a variable assignment error shall occur.  See 3.8.1 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 this subshell environment
 is the same one as that used for a command substitution within the
 command.  [To affect the current execution environment, see exec
 (3.14.6)].  If any of the redirections performed in the current shell
 execution environment fail, the command shall immediately fail with an
 exit status greater than zero, and the shell shall write an error message
 indicating the failure.  See 3.8.1 for the consequences of these failures


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    259





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 on interactive and noninteractive shells.

 If there is a command name, execution shall continue as described in
 3.9.1.1.  If there is no command name, but the command contained a
 command substitution, the command shall complete with the exit status of
 the last command substitution performed.  Otherwise, the command shall
 complete with a zero exit status.

 BEGIN_RATIONALE

 3.9.1.0.1  Simple Commands Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
            _P_1_0_0_3._2)

 The enumerated list is used only when the command is actually going to be  1
 executed.  For example, in:                                                1

       true || $foo *                                                       1

 no expansions are performed.                                               1

 The following example illustrates both how a variable assignment without
 a command name affects the current execution environment, and how an
 assignment with a command name only affects the execution environment of
 the command.

       $ x=red
       $ echo $x
       red
       $ export x
       $ sh -c 'echo $x'
       red
       $ x=blue sh -c 'echo $x'
       blue
       $ echo $x
       red

 This next example illustrates that redirections without a command name
 are still performed.

       $ ls foo
       ls: foo: no such file or directory
       $ > foo
       $ ls foo
       foo

 Historical practice is for a command without a command name, but that
 includes a command substitution, to have an exit status of the last
 command substitution that the shell performed and some historical scripts
 rely on this.  For example:


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 260                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

       if      x=$(_c_o_m_m_a_n_d)
       then    ...
       fi

 An example of redirections without a command name being performed in a
 subshell shows that the here-document does not disrupt the standard input
 of the while loop:

       IFS=:
       while   read a b
       do      echo $a
               <<-eof
               Hello
               eof
       done </etc/passwd

 Some examples of commands without command names in AND/OR lists:

       > foo || {
               echo "error: foo cannot be created" >&2                      1
               exit 1                                                       1
       }

       # set saved if /vmunix.save exists
       test -f /vmunix.save && saved=1

 Command substitution and redirections without command names both occur in
 subshells, but they are not the same ones.  For example, in:               1

       exec 3> file
       var=$(echo foo >&3) 3>&1

 it is unspecified whether foo will be echoed to the file or to standard
 output.

 END_RATIONALE


 3.9.1.1  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 slashes, the first
          successful step in the following sequence shall occur:

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



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    261





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

           (b)  If the command name matches the name of a function known
                to this shell, the function shall be invoked as described
                in 3.9.5.  [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 (1)(d).]

           (c)  If the command name matches the name of a utility listed
                in Table 2-2 (see 2.3), that utility shall be invoked.

           (d)  Otherwise, the command shall be searched for using the
                PATH environment variable as described in 2.6:

                 [1]  If the search is successful:

                       [a]  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 the path
                            search.

                       [b]  Otherwise, the shell shall execute the utility  1
                            in a separate utility environment (see 3.12)    1
                            with actions equivalent to calling the          1
                            POSIX.1 {8} _e_x_e_c_v_e() function with the _p_a_t_h
                            argument set to the pathname resulting from
                            the search, _a_r_g_0 set to the command name, and
                            the remaining arguments set to the operands,
                            if any.

                            If the _e_x_e_c_v_e() function fails due to an error
                            equivalent to the POSIX.1 {8} error [ENOEXEC],
                            the shell shall execute a command equivalent
                            to having a shell invoked with the command
                            name as its first operand, along with any
                            remaining arguments passed along.  If the
                            executable file is not a text file, the shell
                            may bypass this command execution, write an
                            error message, and return an exit status of     1
                            126.                                            1

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


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 262                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

                 [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 does contain slashes, the shell shall
          execute the utility in a separate utility environment with        1
          actions equivalent to calling the POSIX.1 {8} _e_x_e_c_v_e() function   1
          with the _p_a_t_h and _a_r_g_0 arguments set to the command name, and
          the remaining arguments set to the operands, if any.

          If the _e_x_e_c_v_e() function fails due to an error equivalent to the
          POSIX.1 {8} error [ENOEXEC], the shell shall execute a command
          equivalent to having a shell invoked with the command name as
          its first operand, along with any remaining arguments passed
          along.  If the executable file is not a text file, the shell may
          bypass this command execution, write an error message, and
          return an exit status of 126.                                     1

 BEGIN_RATIONALE

 3.9.1.1.1  Command Search and Execution Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t
            _a _p_a_r_t _o_f _P_1_0_0_3._2)

 This description requires that the shell can execute shell scripts
 directly, even if the underlying system does not support the common #!
 interpreter convention.  That is, if file foo contains shell commands and
 is executable, the following will execute foo:

       ./foo

 The command search shown here does not match all historical
 implementations.  A more typical sequence has been:

     - Any built-in, special or regular.

     - Functions.

     - Path search for executable files.

 But there are problems with this sequence.  Since the programmer has no
 idea in advance which utilities might have been built into the shell, a
 function cannot be used to portably override a utility of the same name.
 (For example, a function named cd cannot be written for many historical
 systems.)  Furthermore, the PATH variable is partially ineffective in
 this case and only a pathname with a slash can be used to ensure a
 specific executable file is invoked.

 The sequence selected for POSIX.2 acknowledges that special built-ins
 cannot be overridden, but gives the programmer full control over which


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    263





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 versions of other utilities are executed.  It provides a means of
 suppressing function lookup (via the command utility; see 4.12) for the
 user's own functions and ensures that any regular built-ins or functions
 provided by the implementation are under the control of the path search.
 The mechanisms for associating built-ins or functions with executable
 files in the path are not specified by POSIX.2, but the wording requires
 that if either is implemented, the application will not be able to
 distinguish a function or built-in from an executable (other than in
 terms of performance, presumably).  The implementation must ensure that
 all effects specified by POSIX.2 resulting from the invocation of the
 regular built-in or function (interaction with the environment,
 variables, traps, etc.) are identical to those resulting from the
 invocation of an executable file.

 Example:  Consider three versions of the ls utility:

     - The application includes a shell function named ls.

     - The user writes her own utility named ls and puts it in /hsa/bin.

     - The example implementation provides ls as a regular shell built-in
       that will be invoked (either by the shell or directly by _e_x_e_c) when
       the path search reaches the directory /posix/bin.

 If PATH=/posix/bin, various invocations yield different versions of ls:

                     Invocation                        Version of ls
   _______________________________________________   __________________
   ls (from within application script)               (1) function
   command ls (from within application script)       (3) built-in
   ls (from within makefile called by application)   (3) built-in
   system("ls")                                      (3) built-in
   PATH="/hsa/bin:$PATH" ls                          (2) user's version

 After the _e_x_e_c_v_e() failure described, the shell normally executes the
 file as a shell script.  Some implementations, however, attempt to detect
 whether the file is actually a script and not an executable from some
 other architecture.  The method used by the KornShell is allowed by the
 text that indicates nontext files may be bypassed.

 END_RATIONALE


 3.9.2  Pipelines

 A _p_i_p_e_l_i_n_e is a sequence of one or more commands separated by the control
 operator |.  The standard output of all but the last command shall be
 connected to the standard input of the next command.



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 264                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 The format for a pipeline is:

       [!] _c_o_m_m_a_n_d_1 [ | _c_o_m_m_a_n_d_2 ...]

 The standard output of _c_o_m_m_a_n_d_1 shall be connected to the standard input
 of _c_o_m_m_a_n_d_2. The standard input, standard output, or both of a command
 shall be considered to be assigned by the pipeline before any redirection
 specified by redirection operators that are part of the command (see
 3.7).

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

 _E_x_i_t__S_t_a_t_u_s

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

 BEGIN_RATIONALE


 3.9.2.1  Pipelines Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Because pipeline assignment of standard input or standard output or both
 takes place before redirection, it can be modified by redirection.  For
 example:

       $ command1 2>&1 | command2

 sends both the standard output and standard error of command1 to the
 standard input of command2.

 The reserved word ! was added to allow more flexible testing using AND
 and OR lists.

 It was suggested that it would be better to return a nonzero value if any
 command in the pipeline terminates with nonzero status (perhaps the
 bitwise OR of all return values).  However, the choice of the last-
 specified command semantics are historical practice and would cause
 application breakage if changed.  An example of historical (and POSIX.2)
 behavior:





               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    265





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

       $ sleep 5 | (exit 4)
       $ echo $?
       4
       $ (exit 4) | sleep 5                                                 1
       $ echo $?                                                            1
       0                                                                    1

 END_RATIONALE


 3.9.3  Lists

 An _A_N_D-_O_R-_l_i_s_t is a sequence of one or more pipelines separated by the
 operators

       &&    ||

 A _l_i_s_t is a sequence of one or more AND-OR-lists separated by the
 operators

       ;    &

 and optionally terminated by

       ;    &    <newline>

 The operators && and || shall have equal precedence and shall be
 evaluated from beginning to end.

 A ; or <newline> terminator shall cause the preceding AND-OR-list to be
 executed sequentially; an & shall cause asynchronous execution of the
 preceding AND-OR-list.

 The term _c_o_m_p_o_u_n_d-_l_i_s_t is derived from the grammar in 3.10; it is
 equivalent to a sequence of _l_i_s_t_s, separated by <newline>s, that can be
 preceded or followed by an arbitrary number of <newline>s.

 BEGIN_RATIONALE

 3.9.3.0.1  Lists Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 The equal precedence of && and || is historical practice.  The developers
 of the standard evaluated the model used more frequently in high level
 programming languages, such as C, to allow the shell logical operators to
 be used for complex expressions in an unambiguous way, but could not in
 the end allow existing scripts to break in the subtle way unequal
 precedence might cause.  Some arguments were posed concerning the { } or
 ( ) groupings that are required historically.  There are some
 disadvantages to these groupings:


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 266                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

     - The ( ) can be expensive, as they spawn other processes on some
       systems.  This performance concern is primarily an implementation
       issue.

     - The { } braces are not operators (they are reserved words) and
       require a trailing space after each {, and a semicolon before each
       }.  Most programmers (and certainly interactive users) have avoided
       braces as grouping constructs because of the irritating syntax
       required.  Braces were not changed to operators because that would
       generate compatibility issues even greater than the precedence
       question; braces appear outside the context of a keyword in many
       shell scripts.

 An example reiterates the precedence of the lists as they associate from   1
 beginning to end.  Both of the following commands write solely bar to      1
 standard output:                                                           1

       false && echo foo || echo bar                                        1
       true || echo foo && echo bar                                         1

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

       while
               # a couple of newlines

               # a list
               date && who || ls; cat file
               # a couple of newlines

               # another list
               wc file > output & true

       do
               # 2 lists
               ls
               cat file
       done

 END_RATIONALE


 3.9.3.1  Asynchronous Lists

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



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    267





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 The format for running a command in background is:

       _c_o_m_m_a_n_d_1 & [_c_o_m_m_a_n_d_2 & ...]

 The standard input for an asynchronous list, before any explicit
 redirections are performed, shall be considered to be assigned to a file
 that has the same properties as /dev/null.  If it is an interactive
 shell, this need not happen.  In all cases, explicit redirection of
 standard input shall override this activity.

 When an element of an asynchronous list (the portion of the list ended by  1
 an ampersand, such as _c_o_m_m_a_n_d_1, above) is started by the shell, the        1
 process ID of the last command in the asynchronous list element shall      1
 become known in the current shell execution environment; see 3.12.  This
 process ID shall remain known until:

     - The command terminates and the application waits for the process
       ID, or

     - Another asynchronous list is invoked before $! (corresponding to     1
       the previous asynchronous list) is expanded in the current           1
       execution environment.                                               1

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

 _E_x_i_t__S_t_a_t_u_s

 The exit status of an asynchronous list shall be zero.

 BEGIN_RATIONALE

 3.9.3.1.1  Asynchronous Lists Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
            _P_1_0_0_3._2)

 The grammar treats a construct such as                                     1

       foo & bar & bam &                                                    1

 as one ``asynchronous list,'' but since the status of each element is      1
 tracked by the shell, the term ``element of an asynchronous list'' was     1
 introduced to identify just one of the foo, bar, bam portions of the       1
 overall list.                                                              1

 Unless the implementation has an internal limit, such as {CHILD_MAX}, on   1
 the retained process IDs, it would require unbounded memory for the        1
 following example:                                                         1



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 268                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

       while true                                                           1
       do      foo & echo $!                                                1
       done                                                                 1

 The treatment of the signals SIGINT and SIGQUIT with asynchronous lists
 is described in 3.11.

 Since the connection of the input to the equivalent of /dev/null is
 considered to occur before redirections, the following script would
 produce no output:

       exec < /etc/passwd
       cat <&0 &
       wait

 END_RATIONALE


 3.9.3.2  Sequential Lists

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

 The format for executing commands sequentially is:

       _c_o_m_m_a_n_d_1 [; _c_o_m_m_a_n_d_2] ...

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

 _E_x_i_t__S_t_a_t_u_s

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

 3.9.3.3  AND Lists

 The control operator && shall denote an AND list.  The format is:

       _c_o_m_m_a_n_d_1 [ && _c_o_m_m_a_n_d_2] ...

 First _c_o_m_m_a_n_d_1 is executed.  If its exit status is zero, _c_o_m_m_a_n_d_2 is
 executed, and so on until a command has a nonzero exit status or there
 are no more commands left to execute.  The commands shall be expanded
 only if they are executed.

 _E_x_i_t__S_t_a_t_u_s

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


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    269





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.9.3.4  OR Lists

 The control operator || shall denote an OR List.  The format is:

       _c_o_m_m_a_n_d_1 [ || _c_o_m_m_a_n_d_2] ...

 First, _c_o_m_m_a_n_d_1 is executed.  If its exit status is nonzero, _c_o_m_m_a_n_d_2 is
 executed, and so on until a command has a zero exit status or there are
 no more commands left to execute.

 _E_x_i_t__S_t_a_t_u_s

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


 3.9.4  Compound Commands

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


 3.9.4.1  Grouping Commands

 The format for grouping commands is as follows:

    (_c_o_m_p_o_u_n_d-_l_i_s_t)       Execute _c_o_m_p_o_u_n_d-_l_i_s_t in a subshell environment;
                          see 3.12.  Variable assignments and built-in
                          commands that affect the environment shall not
                          remain in effect after the list finishes.

    { _c_o_m_p_o_u_n_d-_l_i_s_t;}     Execute _c_o_m_p_o_u_n_d-_l_i_s_t in the current process
                          environment.

 _E_x_i_t__S_t_a_t_u_s

 The exit status of a grouping command shall be the exit status of _l_i_s_t.

 BEGIN_RATIONALE







               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 270                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.9.4.1.1  Grouping Commands Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
            _P_1_0_0_3._2)

 The semicolon shown in { _c_o_m_p_o_u_n_d-_l_i_s_t;} is an example of a control
 operator delimiting the } reserved word.  Other delimiters are possible,
 as shown in 3.10; <newline> is frequently used.

 A proposal was made to use the <do-done> construct in all cases where
 command grouping performed in the current process environment is
 performed, identifying it as a construct for the grouping commands, as
 well as for shell functions.  This was not included because the shell
 already has a grouping construct for this purpose ({ }), and changing it
 would have been counter-productive.

 END_RATIONALE


 3.9.4.2  for Loop

 The for loop shall execute a sequence of commands for each member in a
 list of _i_t_e_m_s.  The for loop requires that the _r_e_s_e_r_v_e_d _w_o_r_d_s do and done
 be used to delimit the sequence of commands.

 The format for the for loop is as follows.

       for _n_a_m_e [ in _w_o_r_d ... ]
       do
               _c_o_m_p_o_u_n_d-_l_i_s_t
       done

 First, the list of words following in shall be expanded to generate a
 list of items.  Then, the variable _n_a_m_e shall be set to each item, in
 turn, and the _c_o_m_p_o_u_n_d-_l_i_s_t executed each time.  If no items result from
 the expansion, the _c_o_m_p_o_u_n_d-_l_i_s_t shall not be executed.  Omitting

       in _w_o_r_d ...

 is equivalent to

       in "$@"

 _E_x_i_t__S_t_a_t_u_s

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

 BEGIN_RATIONALE



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    271





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.9.4.2.1  for Loop Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 The format is shown with generous usage of <newline>s.  See the grammar
 in 3.10 for a precise description of where <newline>s and semicolons can
 be interchanged.

 Some historical implementations support { and } as substitutes for do and
 done.  The working group chose to omit them, even as an obsolescent
 feature.  (Note that these substitutes were only for the for command; the
 while and until commands could not use them historically, because they     1
 are followed by compound-lists that may contain {...} grouping commands    1
 themselves                                                                 1

 The reserved word pair do ...  done was selected rather than do ...  od
 (which would have matched the spirit of if ...  fi and case ...  esac)
 because od is a commonly-used utility name and this would have been an
 unacceptable choice.

 END_RATIONALE


 3.9.4.3  case Conditional Construct

 The conditional construct case shall execute the _c_o_m_p_o_u_n_d-_l_i_s_t
 corresponding to the first one of several _p_a_t_t_e_r_n_s (see 3.13) that is
 matched by the string resulting from the tilde expansion, parameter
 expansion, command substitution, and arithmetic expansion and quote
 removal of the given word.  The reserved word in shall denote the
 beginning of the patterns to be matched.  Multiple patterns with the same
 _c_o_m_p_o_u_n_d-_l_i_s_t are delimited by the | symbol.  The control operator )
 terminates a list of patterns corresponding to a given action.  The
 _c_o_m_p_o_u_n_d-_l_i_s_t for each list of patterns is terminated with ;;.  The case
 construct terminates with the reserved word esac (case reversed).

 The format for the case construct is as follows.

       case _w_o_r_d in
            [(]_p_a_t_t_e_r_n_1)   _c_o_m_p_o_u_n_d-_l_i_s_t;;                                  2
            [(]_p_a_t_t_e_r_n_2|_p_a_t_t_e_r_n_3)_c_o_m_p_o_u_n_d-_l_i_s_t;;                            2
            ...
       esac

 The ;; is optional for the last _c_o_m_p_o_u_n_d-_l_i_s_t.

 Each pattern in a pattern list shall be expanded and compared against the
 expansion of _w_o_r_d.  After the first match, no more patterns shall be
 expanded, and the _c_o_m_p_o_u_n_d-_l_i_s_t shall be executed.  The order of
 expansion and comparing of patterns in a multiple pattern list is
 unspecified.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 272                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 _E_x_i_t__S_t_a_t_u_s

 The exit status of case is zero if no patterns are matched.  Otherwise,
 the exit status shall be the exit status of the last command executed in
 the _c_o_m_p_o_u_n_d-_l_i_s_t.

 BEGIN_RATIONALE

 3.9.4.3.1  case Conditional Construct Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a
            _p_a_r_t _o_f _P_1_0_0_3._2)

 An optional open-parenthesis before _p_a_t_t_e_r_n was added to allow numerous    2
 historical KornShell scripts to conform.  At one time, using the leading   2
 parenthesis was required if the case statement were to be embedded within  2
 a $( ) command substitution; this is no longer the case with the POSIX     2
 shell.  Nevertheless, many existing scripts use the open-parenthesis, if   2
 only because it makes matching-parenthesis searching easier in vi and      2
 other editors.  This is a relatively simple implementation change that is  2
 fully upward compatible for all scripts.                                   2

 Consideration was given to requiring break inside the _c_o_m_p_o_u_n_d-_l_i_s_t to
 prevent falling through to the next pattern action list.  This was
 rejected as being nonexisting practice.  An interesting undocumented
 feature of the KornShell is that using ;& instead of ;; as a terminator
 causes the exact opposite behavior--the flow of control continues with
 the next _c_o_m_p_o_u_n_d-_l_i_s_t.

 The pattern "*", given as the last pattern in a case construct, is
 equivalent to the default case in a C-language switch statement

 The grammar shows that reserved words can be used as patterns, even if
 one is the first word on a line.  Obviously, the reserved word esac
 cannot be used in this manner.

 END_RATIONALE


 3.9.4.4  if Conditional Construct

 The if command shall execute a _c_o_m_p_o_u_n_d-_l_i_s_t and use its exit status to
 determine whether to execute another _c_o_m_p_o_u_n_d-_l_i_s_t.

 The format for the if construct is as follows.








               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    273





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

       if _c_o_m_p_o_u_n_d-_l_i_s_t
       _t_h_e_n
               _c_o_m_p_o_u_n_d-_l_i_s_t
       [elif _c_o_m_p_o_u_n_d-_l_i_s_t
       _t_h_e_n
               _c_o_m_p_o_u_n_d-_l_i_s_t] ...
       [else
               _c_o_m_p_o_u_n_d-_l_i_s_t]
       fi

 The if _c_o_m_p_o_u_n_d-_l_i_s_t is executed; if its exit status is zero, the then
 _c_o_m_p_o_u_n_d-_l_i_s_t is executed and the command shall complete.  Otherwise,
 each elif _c_o_m_p_o_u_n_d-_l_i_s_t is executed, in turn, and if its exit status is
 zero, the then _c_o_m_p_o_u_n_d-_l_i_s_t is executed and the command shall complete.
 Otherwise, the else _c_o_m_p_o_u_n_d-_l_i_s_t is executed.

 _E_x_i_t__S_t_a_t_u_s

 The exit status of the if command shall be the exit status of the then or
 else _c_o_m_p_o_u_n_d-_l_i_s_t that was executed, or zero, if none was executed.

 BEGIN_RATIONALE

 3.9.4.4.1  if Conditional Construct Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a
            _p_a_r_t _o_f _P_1_0_0_3._2)

 The precise format for the command syntax is described in 3.10.

 END_RATIONALE


 3.9.4.5  while Loop

 The while loop continuously shall execute one _c_o_m_p_o_u_n_d-_l_i_s_t as long as
 another _c_o_m_p_o_u_n_d-_l_i_s_t has a zero exit status.

 The format of the while loop is as follows

       while _c_o_m_p_o_u_n_d-_l_i_s_t-_1
       _d_o
               _c_o_m_p_o_u_n_d-_l_i_s_t-_2
       _d_o_n_e

 The _c_o_m_p_o_u_n_d-_l_i_s_t-_1 shall be executed, and if it has a nonzero exit
 status, the while command shall complete.  Otherwise, the _c_o_m_p_o_u_n_d-_l_i_s_t-_2
 shall be executed, and the process shall repeat.





               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 274                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 _E_x_i_t__S_t_a_t_u_s

 The exit status of the while loop shall be the exit status of the last
 _c_o_m_p_o_u_n_d-_l_i_s_t-_2 executed, or zero if none was executed.

 BEGIN_RATIONALE

 3.9.4.5.1  while Loop Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
            _P_1_0_0_3._2)

 The precise format for the command syntax is described in 3.10.

 END_RATIONALE


 3.9.4.6  until Loop

 The until loop continuously shall execute one _c_o_m_p_o_u_n_d-_l_i_s_t as long as
 another _c_o_m_p_o_u_n_d-_l_i_s_t has a nonzero exit status.

 The format of the until loop is as follows

       until _c_o_m_p_o_u_n_d-_l_i_s_t-_1
       _d_o
               _c_o_m_p_o_u_n_d-_l_i_s_t-_2
       _d_o_n_e

 The _c_o_m_p_o_u_n_d-_l_i_s_t-_1 shall be executed, and if it has a zero exit status,
 the until command shall complete.  Otherwise, the _c_o_m_p_o_u_n_d-_l_i_s_t-_2 shall
 be executed, and the process shall repeat.

 _E_x_i_t__S_t_a_t_u_s

 The exit status of the until loop shall be the exit status of the last
 _c_o_m_p_o_u_n_d-_l_i_s_t-_2 executed, or zero if none was executed.

 BEGIN_RATIONALE

 3.9.4.6.1  until Loop Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
            _P_1_0_0_3._2)

 The precise format for the command syntax is described in 3.10.

 END_RATIONALE







               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    275





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.9.5  Function 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.  A function is
 defined with a _f_u_n_c_t_i_o_n _d_e_f_i_n_i_t_i_o_n _c_o_m_m_a_n_d.

 The format of a function definition command is as follows:

       _f_n_a_m_e() _c_o_m_p_o_u_n_d-_c_o_m_m_a_n_d [_i_o-_r_e_d_i_r_e_c_t ...]

 The function is named _f_n_a_m_e; it shall be a name (see 3.1.5).  An           1
 implementation may allow other characters in a function name as an         1
 extension.  The implementation shall maintain separate namespaces for      1
 functions and variables.

 The argument _c_o_m_p_o_u_n_d-_c_o_m_m_a_n_d represents a compound command, as described
 in 3.9.4.

 When the function is declared, none of the expansions in 3.6 shall be
 performed on the text in _c_o_m_p_o_u_n_d-_c_o_m_m_a_n_d or _i_o-_r_e_d_i_r_e_c_t; all expansions
 shall be performed as normal each time the function is called.
 Similarly, the optional _i_o-_r_e_d_i_r_e_c_t redirections and any variable
 assignments within _c_o_m_p_o_u_n_d-_c_o_m_m_a_n_d shall be performed during the
 execution of the function itself, not the function definition.  See 3.8.1
 for the consequences of failures of these operations on interactive and
 noninteractive shells.

 When a function is executed, it shall have the syntax-error and
 variable-assignment properties described for special built-in utilities,
 in the enumerated list at the beginning of 3.14.

 The _c_o_m_p_o_u_n_d-_c_o_m_m_a_n_d shall be executed whenever the function name is
 specified as the name of a simple command (see 3.9.1.1).  The operands to
 the command temporarily shall become the positional parameters during the
 execution of the _c_o_m_p_o_u_n_d-_c_o_m_m_a_n_d; the special parameter # shall also be
 changed to reflect the number of operands.  The special parameter 0 shall
 be unchanged.  When the function completes, the values of the positional
 parameters and the special parameter # shall be restored to the values
 they had before the function was executed.  If the special built-in
 return is executed in the _c_o_m_p_o_u_n_d-_c_o_m_m_a_n_d, the function shall complete
 and execution shall resume with the next command after the function call.

 _E_x_i_t__S_t_a_t_u_s

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



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 276                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 BEGIN_RATIONALE


 3.9.5.1  Function Definition Command Rationale (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a
          _p_a_r_t _o_f _P_1_0_0_3._2)

 The description of functions in Draft 8 was based on the notion that
 functions should behave like miniature shell scripts; that is, except for
 sharing variables, most elements of an execution environment should
 behave as if it were a new execution environment, and changes to these
 should be local to the function.  For example, traps and options should
 be reset on entry to the function, and any changes to them don't affect
 the traps or options of the caller.  There were numerous objections to
 this basic idea, and the opponents asserted that functions were intended
 to be a convenient mechanism for grouping commonly executed commands that
 were to be executed in the current execution environment, similar to the
 execution of the dot special built-in.

 Opponents also pointed out that the functions described in Draft 8 did
 not scope everything a new shell script would anyway, such as the current
 working directory, or umask, but instead picked a few select properties.
 The basic argument was that if one wanted scoping of the execution
 environment, the mechanism already exists: put the commands in a new
 shell script and call it.  All traditional shells that implemented
 functions, other than the KornShell, have implemented functions that
 operate in the current execution environment.  Because of this, Draft 9
 removed any local scoping of traps or options.  Local variables within a
 function were considered and included in Draft 9 (controlled by the
 special built-in local), but were removed because they do not fit the
 simple model developed for the scoping of functions and there was some
 opposition to adding yet another new special built-in from outside
 existing practice.  Implementations should reserve the identifier local
 (as well as typeset, as used in the KornShell) in case this local
 variable mechanism is adopted in a future version of POSIX.2.

 A separate issue from the execution environment of a function is the
 availability of that function to child shells.  A few objectors,
 including the author of the original Version 7 UNIX system shell,
 maintained that just as a variable can be shared with child shells by
 exporting it, so should a function--and so this capability has been added
 to the standard.  In previous drafts, the export command therefore had a
 -f flag for exporting functions.  Functions that were exported were to be
 put into the environment as _n_a_m_e()=_v_a_l_u_e pairs, and upon invocation, the
 shell would scan the environment for these, and automatically define
 these functions.  This facility received a lot of balloting opposition
 and was removed from Draft 11.  Some of the arguments against exportable
 functions were:




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.9 Shell Commands                                                    277





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

     - There was little existing practice.  The Ninth Edition shell
       provided them, but there was controversy over how well it worked.

     - There are numerous security problems associated with functions
       appearing in a script's environment and overriding standard
       utilities or the application's own utilities.

     - There was controversy over requiring make to import functions,
       where it has historically used an _e_x_e_c function for many of its
       command line executions.

     - Functions can be big and the environment is of a limited size.
       (The counter-argument was that functions are no different than
       variables in terms of size: there can be big ones, and there can be
       small ones--and just as one does not export huge variables, one
       does not export huge functions.  However, this insight might be
       lost on the average shell-function writer, who typically writes
       much larger functions than variables.)

 As far as can be determined, the functions in POSIX.2 match those in
 System V.  The KornShell has two methods of defining functions:

       function _f_n_a_m_e { _c_o_m_p_o_u_n_d-_l_i_s_t }

 and

       _f_n_a_m_e() { _c_o_m_p_o_u_n_d-_l_i_s_t }

 The latter uses the same definition as POSIX.2, but differs in semantics,
 as described previously.  A future edition of the KornShell is planned to
 align the latter syntax with POSIX and keep the former as-is.

 The name space for functions is limited to that of a _n_a_m_e because of       1
 historical practice.  Complications in defining the syntactic rules for    1
 the function definition command and in dealing with known extensions such  1
 as the KornShell's @() prevented the name space from being widened to a    1
 _w_o_r_d, as requested by some balloters.  Using functions to support          1
 synonyms such as the C-shell's !! and % is thus disallowed to portable     1
 applications, but acceptable as an extension.  For interactive users, the  1
 aliasing facilities in the UPE should be adequate for this purpose.  It    1
 is recognized that the name space for utilities in the file system is      1
 wider than that currently supported for functions, if the portable         1
 filename character set guidelines are ignored, but it did not seem useful  1
 to mandate extensions in systems for so little benefit to portable         1
 applications.                                                              1

 The () in the function definition command consists of two operators.
 Therefore, intermixing <blank>_s with the _f_n_a_m_e, (, and ) is allowed, but
 unnecessary.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 278                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 An example of how a function definition can be used wherever a simple
 command is allowed:

       # If variable i is equal to "yes",
       # define function foo to be ls -l
       #
       [ X$i = Xyes ] && foo() {
               ls -l
       }

 END_RATIONALE



 3.10  Shell Grammar

 The following grammar describes the Shell Command Language.  Any
 discrepancies found between this grammar and the preceding description
 shall be resolved in favor of this clause.


 3.10.1  Shell Grammar Lexical Conventions

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

     (1)  A <newline> shall be returned as the token identifier NEWLINE.

     (2)  If the token is an operator, the token identifier for that
          operator shall result.

     (3)  If the string consists solely of digits and the delimiter
          character is one of < or >, the token identifier IO_NUMBER shall
          be returned.

     (4)  Otherwise, the token identifier TOKEN shall result.

 Further distinction on TOKEN is context-dependent.  It may be that the
 same TOKEN yields WORD, a NAME, an ASSIGNMENT, or one of the reserved
 words below, dependent upon the context.  Some of the productions in the
 grammar below are annotated with a rule number from the following list.
 When a TOKEN is seen where one of those annotated productions could be
 used to reduce the symbol, the applicable rule shall be applied to
 convert the token identifier type of the TOKEN to a token identifier
 acceptable at that point in the grammar.  The reduction shall then
 proceed based upon the token identifier type yielded by the rule applied.
 When more than one rule applies, the highest numbered rule shall apply

               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.10 Shell Grammar                                                    279





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 (which in turn may refer to another rule).  [Note that except in rule
 (7), the presence of an = in the token has no effect.]

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


 3.10.2  Shell Grammar Rules

     (1)  [Command Name]
          When the TOKEN is exactly a reserved word, the token identifier
          for that reserved word shall result.  Otherwise, the token WORD
          shall be returned.  Also, if the parser is in any state where     1
          only a reserved word could be the next correct token, proceed as  1
          above.                                                            1

          NOTE:  Because at this point quote marks are retained in the
          token, quoted strings cannot be recognized as reserved words.
          This rule also implies that reserved words will not be
          recognized except in certain positions in the input, such as
          after a <newline> or semicolon; the grammar presumes that if the
          reserved word is intended, it will be properly delimited by the
          user, and does not attempt to reflect that requirement directly.
          Also note that line joining is done before tokenization, as
          described in 3.2.1, so escaped newlines are already removed at
          this point.

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

     (2)  [Redirection to/from filename]
          The expansions specified in 3.7 shall occur.  As specified
          there, exactly one field can result (or the result is             1
          unspecified), and there are additional requirements on pathname
          expansion.

     (3)  [Redirection from here-document]
          Quote removal [3.7.4].  shall be applied to the word to           1
          determine the delimiter that will be used to find the end of the  1
          here-document that begins after the next <newline>.               1

     (4)  [Case statement termination]
          When the TOKEN is exactly the reserved word Esac, the token
          identifier for Esac shall result.  Otherwise, the token WORD
          shall be returned.

     (5)  [NAME in for]
          When the TOKEN meets the requirements for a name [3.1.5], the


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 280                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

          token identifier NAME shall result.  Otherwise, the token WORD
          shall be returned.

     (6)  [Third word of for and case]
          When the TOKEN is exactly the reserved word In, the token
          identifier for In shall result.  Otherwise, the token WORD shall
          be returned.

     (7)  [Assignment preceding command name]                               1

           (a)  [When the first word]
                If the TOKEN does not contain the character =, rule (1)
                shall be applied.  Otherwise, apply (7)(b).

           (b)  [Not the first word]
                If the TOKEN contains the equals-sign character:

                 - If it begins with =, the token WORD shall be returned.

                 - If all the characters preceding = form a valid name
                   [3.1.5], the token ASSIGNMENT_WORD shall be returned.
                   (Quoted characters cannot participate in forming a
                   valid name.)

                 - Otherwise, it is unspecified whether it is
                   ASSIGNMENT_WORD or WORD that is returned.

          Assignment to the NAME shall occur as specified in 3.9.1.

     (8)  [NAME in function]
          When the TOKEN is exactly a reserved word, the token identifier
          for that reserved word shall result.  Otherwise, when the TOKEN
          meets the requirements for a name [3.1.5], the token identifier
          NAME shall result.  Otherwise, rule (7) shall apply.

     (9)  [Body of function]
          Word expansion and assignment shall never occur, even when
          required by the rules above, when this rule is being parsed.
          Each TOKEN that might either be expanded or have assignment
          applied to it shall instead be returned as a single WORD
          consisting only of characters that are exactly the token
          described in 3.3.

 /*       -------------------------------------------------------
          The grammar symbols
          ------------------------------------------------------- */





               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.10 Shell Grammar                                                    281





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 %token   WORD
 %token   ASSIGNMENT_WORD
 %token   NAME
 %token   NEWLINE
 %token   IO_NUMBER

 /*       The following are the operators mentioned above.        */

 %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   complete_command

 %%

 complete_command    : list separator
                     | list                                                 1
                     ;

 list                : list separator_op and_or




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 282                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

                     |                   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       :              term
                     | newline_list term
                     |              term separator
                     | newline_list term separator
                     ;

 term                : term separator and_or
                     |                and_or
                     ;

 for_clause          : For name                            do_group
                     | For name In wordlist sequential_sep do_group
                     ;




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.10 Shell Grammar                                                    283





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 name                : NAME                     /* Apply rule (5) */        2
                     ;

 in                  : In                       /* Apply rule (6) */
                     ;

 wordlist            : wordlist WORD
                     |          WORD
                     ;

 case_clause         : Case WORD In linebreak case_list Esac
                     | Case WORD In linebreak           Esac
                     ;

 case_list           : case_list case_item
                     |           case_item
                     ;

 case_item           :     pattern ')' linebreak     DSEMI linebreak
                     |     pattern ')' compound_list DSEMI linebreak
                     | '(' pattern ')' linebreak     DSEMI linebreak        2
                     | '(' pattern ')' compound_list DSEMI linebreak        2
                     ;

 pattern             :            WORD          /* Apply rule (4) */
                     | pattern '|' WORD         /* Do not apply rule (4) */ 1
                     ;

 if_clause           : If compound_list Then compound_list else_part Fi
                     | If compound_list Then compound_list           Fi
                     ;

 else_part           : Elif compound_list Then 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) */




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 284                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

                     ;

 fname               : NAME                            /* Apply rule (8) */ 2
                     ;

 brace_group         : Lbrace compound_list Rbrace
                     ;

 do_group            : Do compound_list Done
                     ;

 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 (7)(a) */
                     ;

 cmd_word            : WORD                   /* Apply rule (7)(b) */
                     ;

 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
                     ;





               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.10 Shell Grammar                                                    285





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 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
                     ;

 BEGIN_RATIONALE


 3.10.3  Shell Grammar Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f
         _P_1_0_0_3._2)

 There are several subtle aspects of this grammar where conventional usage
 implies rules about the grammar that in fact are not true.




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 286                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 For compound_list, only the forms that end in a separator allow a
 reserved word to be recognized, so usually only a separator can be used    1
 where a compound list precedes a reserved word (such as Then, Else, Do,
 and Rbrace.  Explicitly requiring a separator would disallow such valid
 (if rare) statements as:

       if (false) then (echo x) else (echo y) fi

 See the NOTE under special grammar rule (1).

 Concerning the third sentence of rule (1) (``Also, if the parser ...''):   1

     - This sentence applies rather narrowly:  when a compound list is      1
       terminated by some clear delimiter (such as the closing fi of an     1
       inner if_clause) then it would apply; where the compound list might  1
       continue (as in after a ;), rule (7a) [and consequently the first    1
       sentence of rule (1)] would apply.  In many instances the two        1
       conditions are identical, but this part of rule (1) does not give    1
       license to treating a WORD as a reserved words unless it is in a     1
       place where a reserved word must appear.                             1

     - The statement is equivalent to requiring that when the LR(1)         2
       lookahead set contains exactly a reserved word, it must be           2
       recognized if it is present.  (Here ``LR(1)'' refers to the          2
       theoretical concepts, not to any real parser generator.)             2

       For example, in the construct below, and when the parser is at the   2
       point marked with ^, the only next legal token is then (this         2
       follows directly from the grammar rules).                            2

             if if....fi then ....  fi                                      2
                        ^                                                   2

       At that point, the then must be recognized as a reserved word.       2

       (Depending on the actual parser generator actually used, ``extra''   2
       reserved words may be in some lookahead sets.  It does not really    2
       matter if they are recognized, or even if any possible reserved      2
       word is recognized in that state, because if it is recognized and    2
       is not in the (theoretical) LR(1) lookahead set, an error will       2
       ultimately be detected.  In the example above, if some other         2
       reserved word (e.g., while) is also recognized, an error will occur  2
       later.                                                               2

       This is approximately equivalent to saying that reserved words are   2
       recognized after other reserved words (because it is after a         2
       reserved word that this condition will occur), but avoids the        2
       ``except for...'' list that would be required for case, for, etc.    2
       (Reserved words are of course recognized anywhere a simple_command   2


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.10 Shell Grammar                                                    287





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

       can appear, as well.  Other rules take care of the special cases of  2
       nonrecognition, such as rule (4) for case statements.)               2

 Note that the body of here-documents are handled by Token Recognition
 (see 3.3) and do not appear in the grammar directly.  (However, the
 here-document I/O redirection operator is handled as part of the
 grammar.)

 The start symbol of the grammar (complete_command) represents either
 input from the command line or a shell script.  It is repeatedly applied
 by the interpreter to its input, and represents a single ``chunk'' of
 that input as seen by the interpreter.                                     1

 The processing of here-documents is handled as part of token recognition
 (see 3.3) rather than as part of the grammar.

 END_RATIONALE



 3.11  Signals and Error Handling

 When a command is in an asynchronous list, the shell shall prevent
 SIGQUIT and SIGINT signals from the keyboard from interrupting the
 command.  Otherwise, signals shall have the values inherited by the shell
 from its parent (see also 3.14.13).

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

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












               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 288                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.12  Shell Execution Environment

 A shell execution environment consists of the following:

     - Open files inherited upon invocation of the shell, plus open files
       controlled by exec.

     - Working Directory as set by cd (see 4.5).

     - File Creation Mask set by umask (see 4.67).

     - Current traps set by trap (see 3.14.13).

     - Shell parameters that are set by variable assignment (see set in
       3.14.11) or from the POSIX.1 {8} environment inherited by the shell
       when it begins (see export in 3.14.8).

     - Shell functions (see 3.9.5.)

     - Options turned on at invocation or by set.

     - Process IDs of the last commands in asynchronous lists known to      1
       this shell environment; see 3.9.3.1.                                 1

 Utilities other than the special built-ins (see 3.14) shall be invoked in
 a separate environment that consists of the following.  The initial value
 of these objects shall be the same as that for the parent shell, except
 as noted below.

     - Open files inherited on invocation of the shell, open files
       controlled by the exec special built-in (see 3.14.6), plus any
       modifications and additions specified by any redirections to the
       utility.

     - Current working directory.

     - File creation mask.

     - If the utility is a shell script, traps caught by the shell shall
       be set to the default values and traps ignored by the shell shall
       be set to be ignored by the utility.  If the utility is not a shell
       script, the trap actions (default or ignore) shall be mapped into
       the appropriate signal handling actions for the utility.

     - Variables with the export attribute, along with those explicitly
       exported for the duration of the command, shall be passed to the
       utility as POSIX.1 {8} environment variables.




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.12 Shell Execution Environment                                      289





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

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

 A subshell environment shall be created as a duplicate of the shell
 environment, except that signal traps set by that shell environment shall  1
 be set to the default values.  Changes made to the subshell environment    1
 shall not affect the shell environment.  Command substitution, commands
 that are grouped with parentheses, and asynchronous lists shall be
 executed in a subshell environment.  Additionally, each command of a
 multicommand pipeline is in a subshell environment; as an extension,
 however, any or all commands in a pipeline may be executed in the current
 environment.  All other commands shall be executed in the current shell
 environment.

 BEGIN_RATIONALE


 3.12.0.1  Shell Execution Environment Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a
           _p_a_r_t _o_f _P_1_0_0_3._2)

 Some systems have implemented the last stage of a pipeline in the current
 environment so that commands such as

       _c_o_m_m_a_n_d | read foo

 set variable foo in the current environment.  It was decided to allow
 this extension, but not require it; therefore, a shell programmer should
 consider a pipeline to be in a subshell environment, but not depend on
 it.

 The previous description of execution environment failed to mention that
 each command in a multiple command pipeline could be in a subshell
 execution environment.  For compatibility with some existing shells, the
 wording was phrased to allow an implementation to place any or all
 commands of a pipeline in the current environment.  However, this means
 that a POSIX application must assume each command is in a subshell
 environment, but not depend on it.

 The wording about shell scripts is meant to convey the fact that
 describing ``trap actions'' can only be understood in the context of the
 shell command language.  Outside this context, such as in a C-language
 program, signals are the operative condition, not traps.

 END_RATIONALE






               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 290                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.13  Pattern Matching Notation

 The pattern matching notation described in this clause 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 in 2.8.  For this reason, the description
 of the rules for this pattern matching notation are based on the
 description of regular expression notation.

 BEGIN_RATIONALE


 3.13.0.1  Pattern Matching Notation Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a
           _p_a_r_t _o_f _P_1_0_0_3._2)

 Pattern matching is a simpler concept and has a simpler syntax than
 regular expressions, as the former is generally used for the manipulation
 of file names, which are relatively simple collections of characters,
 while the latter is generally used to manipulate arbitrary text strings
 of potentially greater complexity.  However, some of the basic concepts
 are the same, so this clause points liberally to the detailed
 descriptions in 2.8.

 END_RATIONALE


 3.13.1  Patterns Matching a Single Character

 The following _p_a_t_t_e_r_n_s _m_a_t_c_h_i_n_g _a _s_i_n_g_l_e-_c_h_a_r_a_c_t_e_r match a single
 character:  _o_r_d_i_n_a_r_y _c_h_a_r_a_c_t_e_r_s, _s_p_e_c_i_a_l _p_a_t_t_e_r_n _c_h_a_r_a_c_t_e_r_s, and _p_a_t_t_e_r_n
 _b_r_a_c_k_e_t _e_x_p_r_e_s_s_i_o_n_s.  The pattern bracket expression also shall match a
 single collating element.

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

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

    ?     A question-mark is a pattern that shall match any character.

    *     An asterisk is a pattern that shall match multiple characters,
          as described in 3.13.2.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.13 Pattern Matching Notation                                        291





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

    [     The open bracket shall introduce a pattern bracket expression.

 The description of basic regular expression bracket expressions in
 2.8.3.2 also shall apply to the pattern bracket expression, except that
 the exclamation-mark character (!) shall replace the circumflex character
 (^) in its role in a _n_o_n_m_a_t_c_h_i_n_g _l_i_s_t in the regular expression notation.
 A bracket expression starting with an unquoted circumflex character
 produces unspecified results.

 When pattern matching is used where shell quote removal is not performed   1
 [such as in the argument to the find -name primary when find is being      1
 called using an _e_x_e_c function, or in the _p_a_t_t_e_r_n argument to the           1
 _f_n_m_a_t_c_h() function], special characters can be escaped to remove their     1
 special meaning by preceding them with a <backslash>.  This escaping       1
 <backslash> shall be discarded.  The sequence \\ shall represent one       1
 literal backslash.  All of the requirements and effects of quoting on      1
 ordinary, shell special, and special pattern characters shall apply to     1
 escaping in this context.                                                  1

 BEGIN_RATIONALE                                                            1


 3.13.1.1  Patterns Matching a Single Character Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e
           _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Both ``quoting'' and ``escaping'' are described here because pattern       1
 matching must work in three separate circumstances:                        1

     - Calling directly upon the shell, such as in pathname expansion or    1
       in a case statement.  All of the following will match the string or  1
       file abc:  abc, "abc", a"b"c, a\bc, a[b]c, a["b"]c, a[\b]c, a?c,     1
       a*c.  The following will not:  "a?c", a\*c, a\[b]c, a["\b"]c.        1

     - Calling a utility or function without going through a shell, as      1
       described for find and _f_n_m_a_t_c_h().                                    1

     - Calling utilities such as find or pax through the shell command      1
       line.  (Although find and pax are the only instances of this in the  1
       standard utilities, describing it globally here is useful for        1
       future utilities that may use pattern matching internally.)  In      1
       this case, shell quote removal is performed before the utility sees  1
       the argument.  For example, in                                       1

             find /bin -name "e\c[\h]o" -print                              1

       after quote removal, the backslashes are presented to find and it    1
       treats them as escape characters.  Both precede ordinary             1
       characters, so the c and h represent themselves and echo would be    1
       found on many historical systems (that have it in /bin).  To find a  1
       filename that contained shell special characters or pattern          1

               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 292                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

       characters, both quoting and escaping are required, such as          1

             pax -r ... "*a\(\?"                                            1

       to extract a filename ending with ``a(?''.                           1

 Conforming applications are required to quote or escape the shell special  1
 characters (called ``metacharacters'' in some historical documentation).   1
 If used without this protection, syntax errors can result or               1
 implementation extensions can be triggered.  For example, the KornShell    1
 supports a series of extensions based on parentheses in patterns.          1

 The restriction on circumflex in a bracket expression is to allow
 implementations that support pattern matching using circumflex as the
 negation character in addition to the exclamation-mark.                    1

 END_RATIONALE                                                              1


 3.13.2  Patterns Matching Multiple Characters

 The following rules are used to construct _p_a_t_t_e_r_n_s _m_a_t_c_h_i_n_g _m_u_l_t_i_p_l_e
 _c_h_a_r_a_c_t_e_r_s from _p_a_t_t_e_r_n_s _m_a_t_c_h_i_n_g _a _s_i_n_g_l_e _c_h_a_r_a_c_t_e_r:

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

     (2)  The concatenation of _p_a_t_t_e_r_n_s _m_a_t_c_h_i_n_g _a _s_i_n_g_l_e _c_h_a_r_a_c_t_e_r is a
          valid pattern that shall match the concatenation of the single
          characters or collating elements matched by each of the
          concatenated patterns.

     (3)  The concatenation of one or more _p_a_t_t_e_r_n_s _m_a_t_c_h_i_n_g _a _s_i_n_g_l_e
          _c_h_a_r_a_c_t_e_r with one or more asterisks is a valid pattern.  In
          such patterns, each asterisk shall match a string of zero or
          more characters, matching the greatest possible number of
          characters that still allows the remainder of the pattern to
          match the string.

 BEGIN_RATIONALE


 3.13.2.1  Patterns Matching Multiple Characters Rationale. (_T_h_i_s
           _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Since each asterisk matches ``zero or more'' occurrences, the patterns
 a*b and a**b have identical functionality.




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.13 Pattern Matching Notation                                        293





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 _E_x_a_m_p_l_e_s:

    a[bc]       matches the strings ab and ac.

    a*d         matches the strings ad, abd, and abcd, but not the string
                abc.

    a*d*        matches the strings ad, abcd, abcdef, aaaad, and adddd;

    *a*d        matches the strings ad, abcd, efabcd, aaaad, and adddd.

 END_RATIONALE


 3.13.3  Patterns Used for Filename Expansion

 The rules described so far in 3.13.1 and 3.13.2 are qualified by the
 following rules that apply when pattern matching notation is used for
 filename expansion.

     (1)  The slash character in a pathname shall be explicitly matched by
          using one or more slashes in the pattern; it cannot be matched
          by the asterisk or question-mark special characters or by a
          bracket expression.  Slashes in the pattern are identified
          before bracket expressions; thus, a slash cannot be included in
          a pattern bracket expression used for filename expansion.

     (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:

           - The asterisk or question-mark special characters, or

           - A bracket expression containing a nonmatching list (such as
             [!a]), a range expression (such as [%-0]), or a character
             class expression (such as [[:punct:]]).

          It is unspecified whether an explicit period in a bracket
          expression matching list (such as [.abc]) can match a leading
          period in a filename.

     (3)  Specified patterns are matched against existing filenames and
          pathnames, as appropriate.  Each component that contains a        2
          pattern character requires read permission in the directory       2
          containing that component.  Any component that does not contain   2
          a pattern character requires search permission.  For example,     2
          given the pattern                                                 2



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 294                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

                /foo/bar/x*/bam                                             2

          search permission is needed for directory /foo, search and read   2
          permissions are needed for directory bar, and search permission   2
          is needed for each x* directory.  If the pattern matches any      2
          existing filenames or pathnames, the pattern shall be replaced
          with those filenames and pathnames, sorted according to the
          collating sequence in effect in the current locale.  If the
          pattern contains an invalid bracket expression or does not match
          any existing filenames or pathnames, the pattern string shall be
          left unchanged.

 BEGIN_RATIONALE


 3.13.3.1  Patterns Used for File Name Expansion Rationale. (_T_h_i_s
           _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 The caveat about a slash within a bracket expression is derived from
 historical practice.  The pattern a[b/c]d will not match such pathnames
 as abd or a/d.  It will only match a pathname of literally a[b/c]d.

 Filenames beginning with a period historically have been specially
 protected from view on UNIX systems.  A proposal to allow an explicit
 period in a bracket expression to match a leading period was considered;
 it is allowed as an implementation extension, but a conforming
 application cannot make use of it.  If this extension becomes popular in
 the future, it will be considered for a future version of POSIX.2.

 Historical systems have varied in their permissions requirements.  To      2
 match f*/bar has required read permissions on the f* directories in the    2
 System V shell, but this standard, the C-shell, and KornShell require      2
 only search permissions.                                                   2

 END_RATIONALE                                                              2


 3.14  Special Built-in Utilities

 The following _s_p_e_c_i_a_l _b_u_i_l_t-_i_n utilities shall be supported in the shell
 command language.  The output of each command, if any, shall be written
 to standard output, subject to the normal redirection and piping possible
 with all commands.

 The term _b_u_i_l_t-_i_n implies that the shell can execute the utility directly
 and does not need to search for it.  An implementation can choose to make
 any utility a built-in; however, the special built-in utilities described
 here differ from regular built-in utilities in two respects:



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       295





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

     (1)  A syntax error in a special built-in utility may cause a shell
          executing that utility to abort, while a syntax error in a
          regular built-in utility shall not cause a shell executing that
          utility to abort.  (See 3.8.1 for the consequences of errors on
          interactive and noninteractive shells.)  If a special built-in
          utility encountering a syntax error does not abort the shell,
          its exit value shall be nonzero.

     (2)  Variable assignments specified with special built-in utilities
          shall remain in effect after the built-in completes; this shall   1
          not be the case with a regular built-in or other utility.         1

 As described in 2.3, the special built-in utilities in this clause need
 not be provided in a manner accessible via the POSIX.1 {8} _e_x_e_c family of
 functions.

 Some of the special built-ins are described as conforming to the utility
 argument syntax guidelines in 2.10.2.  For those that are not, the
 requirement in 2.11.3 that "--" be recognized as a first argument to be
 discarded does not apply and a conforming application shall not use that
 argument.


 3.14.1  break - Exit from for, while, or until loop

       break [_n]

 Exit from the smallest enclosing for, while, or until loop, if any; or
 from the _nth enclosing loop if _n is specified.  The value of _n is an       1
 unsigned decimal integer _> 1.  The default is equivalent to _n=1.  If _n is
 greater than the number of enclosing loops, the last enclosing loop shall
 be exited from.  Execution continues with the command immediately
 following the loop.

 _E_x_i_t__S_t_a_t_u_s

     0    Successful completion.                                            2

    >0    The _n value was not an unsigned decimal integer _> 1.              2

 BEGIN_RATIONALE


 3.14.1.1  break Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Example:





               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 296                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

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

 Consideration was given to expanding the syntax of the break and continue
 to refer to a label associated with the appropriate loop, as a preferable
 alternative to the [_n] method.  This new method was proposed late in the
 development of the standard and adequate consensus could not be formed to
 include it.  However, POSIX.2 does reserve the namespace of command names
 ending with a colon.  It is anticipated that a future implementation
 could take advantage of this and provide something like:

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

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

 END_RATIONALE


 3.14.2  colon - Null utility

       : [_a_r_g_u_m_e_n_t ...]

 This utility shall only expand command _a_r_g_u_m_e_n_ts.

 _E_x_i_t__S_t_a_t_u_s

 Zero.

 BEGIN_RATIONALE









               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       297





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 3.14.2.1  colon Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 The colon (:), or null utility, is used when a command is needed, as in
 the then condition of an if command, but nothing is to be done by the
 command.

 Example:

       : ${X=abc}
       if      false
       then    :
       else    echo $X
       fi
       abc

 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 variable x to the value y (so that it persists after the null
 utility ``completes'') and creates or truncates file z.

 END_RATIONALE


 3.14.3  continue - Continue for, while, or until loop

       continue [_n]

 The continue utility shall return to the top of the smallest enclosing
 for, while, or until, loop, or to the top of the _nth enclosing loop, if _n
 is specified.  This involves repeating the condition list of a while or
 until loop or performing the next assignment of a for loop, and
 reexecuting the loop if appropriate.

 The value of _n is a decimal integer _> 1.  The default is equivalent to
 _n=1.  If _n is greater than the number of enclosing loops, the last
 enclosing loop is used.

 _E_x_i_t__S_t_a_t_u_s

     0    Successful completion.                                            2

    >0    The _n value was not an unsigned decimal integer _> 1.              2

 BEGIN_RATIONALE




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 298                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.14.3.1  continue Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Example:

       for i in *
       do
               if test -d "$i"
               then continue
               fi
       done

 END_RATIONALE


 3.14.4  dot - Execute commands in current environment

       . _f_i_l_e

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

 If _f_i_l_e does not contain a slash, the shell shall use the search path
 specified by PATH to find the directory containing _f_i_l_e. Unlike normal
 command search, however, the file searched for by the dot utility need
 not be executable.  If no readable file is found, a noninteractive shell
 shall abort; an interactive shell shall write a diagnostic message to
 standard error, but this condition shall not be considered a syntax
 error.

 _E_x_i_t__S_t_a_t_u_s

 Returns the value of the last command executed, or a zero exit status if
 no command is executed.

 BEGIN_RATIONALE


 3.14.4.1  dot Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Some older implementations searched the current directory for the _f_i_l_e,
 even if the value of PATH disallowed it.  This behavior was omitted from
 POSIX.2 due to concerns about introducing the susceptibility to trojan
 horses that the user might be trying to avoid by leaving dot out of PATH.

 The KornShell version of dot takes optional arguments that are set to the  1
 positional parameters.  This is a valid extension that allows a dot        1
 script to behave identically to a function.




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       299





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 Example:

       cat foobar
       foo=hello bar=world
       . foobar
       echo $foo $bar
       hello world

 END_RATIONALE


 3.14.5  eval - Construct command by concatenating arguments

       eval [_a_r_g_u_m_e_n_t ...]

 The eval utility shall construct a command by concatenating _a_r_g_u_m_e_n_ts
 together, separating each with a <space>.  The constructed command shall
 be read and executed by the shell.

 _E_x_i_t__S_t_a_t_u_s

 If there are no _a_r_g_u_m_e_n_ts, or only null arguments, eval shall return a
 zero exit status; otherwise, it shall return the exit status of the
 command defined by the string of concatenated _a_r_g_u_m_e_n_ts separated by
 spaces.

 BEGIN_RATIONALE


 3.14.5.1  eval Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Example:

       foo=10 x=foo
       y='$'$x
       echo $y
       $foo
       eval y='$'$x
       echo $y
       10

 END_RATIONALE









               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 300                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.14.6  exec - Execute commands and open, close, and/or copy file
         descriptors

       exec [_c_o_m_m_a_n_d [_a_r_g_u_m_e_n_t ...]]

 The exec utility opens, closes, and/or copies file descriptors as
 specified by any redirections as part of the command.

 If exec is specified without _c_o_m_m_a_n_d or _a_r_g_u_m_e_n_t_s, and any file
 descriptors with numbers > 2 are opened with associated redirection
 statements, it is unspecified whether those file descriptors remain open
 when the shell invokes another utility.

 If exec is specified with _c_o_m_m_a_n_d, it shall replace the shell with
 _c_o_m_m_a_n_d without creating a new process.  If _a_r_g_u_m_e_n_ts are specified, they
 are arguments to _c_o_m_m_a_n_d.  Redirection shall affect the current shell
 execution environment.

 _E_x_i_t__S_t_a_t_u_s

 If _c_o_m_m_a_n_d is specified, exec shall not return to the shell; rather, the   2
 exit status of the process shall be the exit status of the program         2
 implementing _c_o_m_m_a_n_d, which overlaid the shell.  If _c_o_m_m_a_n_d is not found,  2
 the exit status shall be 127.  If _c_o_m_m_a_n_d is found, but it is not an       1
 executable utility, the exit status shall be 126.  If a redirection error  1
 occurs (see 3.8.1), the shell shall exit with a value in the range 1-125.  1
 Otherwise, exec shall return a zero exit status.

 BEGIN_RATIONALE


 3.14.6.1  exec Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Most historical implementations are not conformant in that

       foo=bar exec cmd

 does not pass foo to cmd.

 Earlier drafts stated that ``If specified without _c_o_m_m_a_n_d or _a_r_g_u_m_e_n_t,
 the shell sets to close-on-exec file numbers greater than 2 that are
 opened in this way, so that they will be closed when the shell invokes
 another program.''  This was based on the behavior of one version of the
 KornShell and was made unspecified when it was realized that some
 existing scripts relied on the more generally historical behavior
 (leaving all file descriptors open).  Furthermore, since the application
 should have no cognizance of whether a new shell is simply _f_o_r_k()ed,
 rather than _e_x_e_c()ed, it could not consistently rely on the automatic
 closing behavior anyway.  Scripts concerned that child shells could
 misuse open file descriptors can always close them explicitly, as shown

               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       301





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 in one of the following examples.

 Examples:

 Open readfile as file descriptor 3 for reading:

       exec 3< readfile

 Open writefile as file descriptor 4 for writing:

       exec 4> writefile

 Make unit 5 a copy of unit 0:

       exec 5<&0

 Close file unit 3:

       exec 3<&-

 Cat the file maggie by replacing the current shell with the cat utility:

       exec cat maggie

 END_RATIONALE


 3.14.7  exit - Cause the shell to exit

       exit [_n]

 The exit utility shall cause the shell to exit with the exit status
 specified by the unsigned decimal integer _n.  If _n is specified, but its   1
 value is not between 0 and 255 inclusively, the exit status is undefined.  1

 A trap on EXIT shall be executed before the shell terminates, except when
 the exit utility is invoked in that trap itself, in which case the shell
 shall exit immediately.

 _E_x_i_t__S_t_a_t_u_s

 The exit status shall be _n, if specified.  Otherwise, the value shall be
 the exit value of the last command executed, or zero if no command was
 executed.  When exit is executed in a trap action (see 3.14.13), the
 ``last command'' is considered to be the command that executed
 immediately preceding the trap action.

 BEGIN_RATIONALE



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 302                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 3.14.7.1  exit Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 As explained in other clauses, certain exit status values have been        1
 reserved for special uses and should be used by applications only for      1
 those purposes:                                                            1

     126  A file to be executed was found, but it was not an executable     1
          utility.                                                          1

     127  A utility to be executed was not found.                           1

    >128  A command was interrupted by a signal.                            1

 Examples:

 Exit with a _t_r_u_e value:

       exit 0

 Exit with a _f_a_l_s_e value:

       exit 1

 END_RATIONALE


 3.14.8  export - Set export attribute for variables

       export _n_a_m_e[=_w_o_r_d]...
       export -p

 The shell shall give the export attribute to the variables corresponding
 to the specified _n_a_m_es, which shall cause them to be in the environment
 of subsequently executed commands.

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

       "export %s=%s\n", <_n_a_m_e>, <_v_a_l_u_e>

 The shell shall format the output, including the proper use of quoting,
 so that it is suitable for re-input to the shell as commands that achieve
 the same exporting results.

 The export special built-in shall conform to the utility argument syntax
 guidelines described in 2.10.2.





               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       303





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 _E_x_i_t__S_t_a_t_u_s

 Zero.

 BEGIN_RATIONALE


 3.14.8.1  export Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 When no arguments are given, the results are unspecified.  Some
 historical shells use the no-argument case as the functional equivalent
 of what is required here with -p.  This feature was left unspecified
 because it is not existing practice in all shells and some scripts may
 rely on the now-unspecified results on their implementations.  Attempts
 to specify the -p output as the default case were unsuccessful in
 achieving consensus.  The -p option was added to allow portable access to
 the values that can be saved and then later restored using, for instance,
 a dot script.

 Examples:

 Export PWD and HOME variables:

       export PWD HOME

 Set and export the PATH variable:

       export PATH=/local/bin:$PATH

 Save and restore all exported variables:

       export -p > _t_e_m_p-_f_i_l_e
       unset _a _l_o_t _o_f _v_a_r_i_a_b_l_e_s
       ... _p_r_o_c_e_s_s_i_n_g
       . _t_e_m_p-_f_i_l_e

 END_RATIONALE


 3.14.9  readonly - Set read-only attribute for variables                   1

       readonly _n_a_m_e[=_w_o_r_d]...
       readonly -p

 The variables whose _n_a_m_es are specified shall be given the readonly
 attribute.  The values of variables with the read-only attribute cannot
 be changed by subsequent assignment, nor can those variables be unset by
 the unset utility.



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 304                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 When -p is specified, readonly shall write to the standard output the
 names and values of all read-only variables, in the following format:      1

       "readonly %s=%s\n", <_n_a_m_e>, <_v_a_l_u_e>

 The shell shall format the output, including the proper use of quoting,
 so that it is suitable for re-input to the shell as commands that achieve
 the same attribute-setting results.

 The readonly special built-in shall conform to the utility argument
 syntax guidelines described in 2.10.2.

 _E_x_i_t__S_t_a_t_u_s

 Zero.

 BEGIN_RATIONALE


 3.14.9.1  readonly Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Example:

       readonly HOME PWD

 Some versions of the shell exist that preserve the read-only attribute
 across separate invocations.  POSIX.2 allows this behavior, but does not
 require it.

 See the rationale for export (3.14.8.1) for a description of the no-
 argument and -p output cases.

 In a previous draft, read-only functions were considered, but they were
 omitted as not being existing practice or particularly useful.
 Furthermore, functions must not be readonly across invocations to
 preclude _s_p_o_o_f_i_n_g (spoofing is the term for the practice of creating a
 program that acts like a well-known utility with the intent of subverting
 the user's real intent) of administrative or security-relevant (or
 -conscious) shell scripts.

 END_RATIONALE


 3.14.10  return - Return from a function

       return [_n]

 The return utility shall cause the shell to stop executing the current
 function or dot script (see 3.14.4).  If the shell is not currently
 executing a function or dot script, the results are unspecified.

               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       305





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 _E_x_i_t__S_t_a_t_u_s

 The value of the special parameter ? shall be set to _n, an unsigned
 decimal integer, or to the exit status of the last command executed if _n
 is not specified.  If the value of _n is greater than 255, the results are
 undefined.  When return is executed in a trap action (see 3.14.13), the
 ``last command'' is considered to be the command that executed
 immediately preceding the trap action.

 BEGIN_RATIONALE


 3.14.10.1  return Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 The behavior of return when not in a function or dot script differs
 between the System V shell and the KornShell.  In the System V shell this
 is an error, whereas in the KornShell, the effect is the same as exit.

 The results of returning a number greater than 255 are undefined because
 of differing practices in the various historical implementations.  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 in 3.14.7.1.          1

 END_RATIONALE                                                              1


 3.14.11  set - Set/unset options and positional parameters

       set [-aCefnuvx] [_a_r_g_u_m_e_n_t ...]
       set [+aCefnuvx] [_a_r_g_u_m_e_n_t ...]
       set -- [_a_r_g_u_m_e_n_t ...]

       _O_b_s_o_l_e_s_c_e_n_t _v_e_r_s_i_o_n:

       set - [_a_r_g_u_m_e_n_t ...]

 If no options or _a_r_g_u_m_e_n_ts are specified, set shall write the names and
 values of all shell variables in the collation sequence of the current
 locale.  Each _n_a_m_e shall start on a separate line, using the format:

       "%s=%s\n", <_n_a_m_e>, <_v_a_l_u_e>

 The _v_a_l_u_e string shall be written with appropriate quoting so that it is
 suitable for re-input to the shell, (re)setting, as far as possible, the   1
 variables that are currently set.  Readonly variables cannot be reset.     1
 See the description of shell quoting in 3.2.



               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 306                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

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

 The set utility shall conform to the utility argument syntax guidelines
 described in 2.10.2, except that options can be specified with either a
 leading hyphen (meaning enable the option) or plus-sign (meaning disable
 it).

 The implementation shall support the options in the following list in
 both their hyphen and plus-sign forms.  These options can also be
 specified as options to sh; see 4.56.

    -a          When this option is on, the export attribute shall be set
                for each variable to which an assignment is performed.
                (See 3.1.15.)  If the assignment precedes a utility name
                in a command, the export attributes shall not persist in    1
                the current execution environment after the utility         1
                completes, with the exception that preceding one of the     1
                special built-in utilities shall cause the export
                attribute to persist after the built-in has completed.  If
                the assignment does not precede a utility name in the
                command, or if the assignment is a result of the operation
                of the getopts or read utilities (see 4.27 and 4.52), the
                export attribute shall persist until the variable is
                unset.

    -C          (Uppercase C.)  Prevent existing files from being
                overwritten by the shell's > redirection operator (see
                3.7.2); the >| redirection operator shall override this
                ``noclobber'' option for an individual file.

    -e          When this option is on, if a simple command fails for any   1
                of the reasons listed in 3.8.1 or returns an exit status    1
                value >0, and is not part of the compound list following a  1
                while, until, or if keyword, and is not a part of an AND    1
                or OR list, and is not a pipeline preceded by the !
                reserved word, then the shell immediately shall exit.

    -f          The shell shall disable pathname expansion.

    -n          The shell shall read commands but not execute them; this
                can be used to check for shell script syntax errors.  An
                interactive shell may ignore this option.




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       307





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

    -u          The shell shall write a message to standard error when it
                tries to expand a variable that is not set and immediately
                exit.  An interactive shell shall not exit.

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

 The default for all these options is off (unset) unless the shell was
 invoked with them on (see sh in 4.56).  All the positional parameters
 shall be unset before any new values are assigned.

 The remaining arguments shall be assigned in order to the positional
 parameters.  The special parameter # shall be set to reflect the number
 of positional parameters.

 The special argument "--" immediately following the set command name can
 be used to delimit the arguments if the first argument begins with + or
 -, or to prevent inadvertent listing of all shell variables when there
 are no arguments.  The command set -- without _a_r_g_u_m_e_n_ts shall unset all
 positional parameters and set the special parameter # to zero.

 In the obsolescent version, the set command name followed by - with no
 other arguments shall turn off the -v and -x options without changing the
 positional parameters.  The set command name followed by - with other
 arguments shall turn off the -v and -x options and assign the arguments
 to the positional parameters in order.

 _E_x_i_t__S_t_a_t_u_s

 Zero.

 BEGIN_RATIONALE


 3.14.11.1  set Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 The set -- form is listed specifically in the Synopsis even though this
 usage is implied by the utility syntax guidelines.  The explanation of
 this feature removes any ambiguity about whether the set -- form might be
 misinterpreted as being equivalent to set without any options or
 arguments.  The functionality of this form has been adopted from the
 KornShell.  In System V, set -- only unsets parameters if there is at
 least one argument; the only way to unset all parameters is to use shift.
 Using the KornShell version should not affect System V scripts because
 there should be no reason to deliberately issue it without arguments; if
 it were issued as, say:

               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 308                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

       set -- "$@"                                                          1

 and there were in fact no arguments resulting from $@, unsetting the       1
 parameters would be a no-op anyway.

 The set + form in earlier drafts was omitted as being an unnecessary
 duplication of set alone and not widespread historical practice.

 The noclobber option was changed to -C from the set -o noclobber option
 in previous drafts.  The set -o is used in the KornShell to accept word-
 length option names, duplicating many of the single-letter names.  The
 noclobber option was changed to a single letter so that the historical $-
 paradigm would not be broken; see 3.5.2.

 The following set flags were intentionally omitted with the following
 rationale:

    -h    This flag is related to command name hashing, which is not
          required for an implementation.  It is primarily a performance
          issue, which is outside the scope of this standard.

    -k    The -k flag was originally added by Bourne to make it easier for
          users of prerelease versions of the shell.  In early versions of
          the Bourne shell the construct set name=value, had to be used to
          assign values to shell variables.  The problem with -k is that
          the behavior affects parsing, virtually precluding writing any
          compilers.  To explain the behavior of -k, it is necessary to
          describe the parsing algorithm, which is implementation defined.
          For example,

                set -k; echo name=value

          and

                set -k
                echo name=value

          behave differently.  The interaction with functions is even more
          complex.  What is more, the -k flag is never needed, since the
          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 with ksh and sh differ.  The man page says that it
          exits after reading and executing one command.  What is one
          command?  If the input is date;date, sh executes both date
          commands, ksh does only the first.




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       309





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 Consideration was given to rewriting set to simplify its confusing
 syntax.  A specific suggestion was that the unset utility should be used
 to unset options instead of using the non-_g_e_t_o_p_t()-able +_o_p_t_i_o_n syntax.
 However, the conclusion was reached that people were satisfied with the
 existing practice of using +_o_p_t_i_o_n and there was no compelling reason to
 modify such widespread existing practice.

 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 of x, even if x begins with - or +:

       set -- "$x"

 Set the positional parameters to the expansion of x, even if x expands
 with a leading - or +:

       set -- $x

 END_RATIONALE


 3.14.12  shift - Shift positional parameters

       shift [_n]

 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 forth.  The parameters represented
 by the numbers $# down to $#-_n+1 shall be unset, and the parameter #
 shall be updated to reflect the new number of positional parameters.

 The value _n shall be an unsigned decimal integer less than or equal to
 the value of the special parameter #.  If _n is not given, it shall be


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 310                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 assumed to be 1.  If _n is 0, the positional and special parameters shall
 not be changed.

 _E_x_i_t__S_t_a_t_u_s

 The exit status shall be >0 if _n>$#; otherwise, it shall be zero.

 BEGIN_RATIONALE


 3.14.12.1  shift Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Example:

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

 END_RATIONALE


 3.14.13  trap - Trap signals

       trap [_a_c_t_i_o_n _c_o_n_d_i_t_i_o_n ...]

 If _a_c_t_i_o_n is -, the shell shall reset each _c_o_n_d_i_t_i_o_n to the default
 value.  If _a_c_t_i_o_n is null (''), the shell shall ignore each of the
 specified _c_o_n_d_i_t_i_o_ns if they arise.  Otherwise, the argument _a_c_t_i_o_n shall
 be read and executed by the shell when one of the corresponding
 conditions arises.  The action of the trap shall override a previous
 action (either default action or one explicitly set).  The value of $?
 after the trap action completes shall be the value it had before the trap
 was invoked.

 The condition can be EXIT, 0 (equivalent to EXIT), or a signal specified
 using a symbolic name, without the SIG prefix, as listed in Required       1
 Signals and Job Control Signals (Table 3-1 and Table 3-2 in POSIX.1 {8}).
 (For example:  HUP, INT, QUIT, TERM).  Setting a trap for SIGKILL or
 SIGSTOP produces undefined results.

 The environment in which the shell executes a trap on EXIT shall be
 identical to the environment immediately after the last command executed
 before the trap on EXIT was taken.

 Each time the trap is invoked, the _a_c_t_i_o_n argument shall be processed in
 a manner equivalent to:

       eval "$action"


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       311





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

 Signals that were ignored on entry to a noninteractive shell cannot be
 trapped or reset, although no error need be reported when attempting to
 do so.  An interactive shell may reset or catch signals ignored on entry.
 Traps shall remain in place for a given shell until explicitly changed
 with another trap command.

 The trap command with no arguments shall write to standard output a list
 of commands associated with each condition.  The format is:

       "trap -- %s %s ...\n", <_a_c_t_i_o_n>, <_c_o_n_d_i_t_i_o_n> ...                     1

 The shell shall format the output, including the proper use of quoting,
 so that it is suitable for re-input to the shell as commands that achieve
 the same trapping results.

 An implementation may allow numeric signal numbers for the conditions as
 an extension, if and only if the following map of signal numbers to names
 is true:

                  Signal   Signal        Signal   Signal
                  Number    Name         Number    Name
                  ______   _______       ______   _______
                    1      SIGHUP           9     SIGKILL
                    2      SIGINT          14     SIGALRM
                    3      SIGQUIT         15     SIGTERM
                    6      SIGABRT

 Otherwise, it shall be an error for the application to use numeric signal
 numbers.

 The trap special built-in shall conform to the utility argument syntax
 guidelines described in 2.10.2.

 _E_x_i_t__S_t_a_t_u_s

 If the trap name or number is invalid, a nonzero exit status shall be
 returned; otherwise, zero shall be returned.  For both interactive and
 noninteractive shells, invalid signal names or numbers shall not be
 considered a syntax error and shall not cause the shell to abort.

 BEGIN_RATIONALE

 3.14.13.1  trap Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Implementations may permit lowercase signal names as an extension.         1
 Implementations may also accept the names with the SIG prefix; no known    1
 historical shell does so.  The trap and kill utilities in POSIX.2 are now  1
 consistent in their omission of the SIG prefix for signal names.  Some     1
 kill implementations do not allow the prefix and kill -l lists the         1


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 312                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

 signals without prefixes.                                                  1

 As stated previously, when a subshell is entered, traps are set to the     1
 default actions.  This does not imply that the trap command cannot be      1
 used within the subshell to set new traps.                                 1

 Trapping SIGKILL or SIGSTOP is accepted by some historical
 implementations, but it does not work.  Portable POSIX.2 applications
 cannot try it.

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

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

 The KornShell uses an ERR trap that is triggered whenever set -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 shells which, e.g., close the
 standard input before executing a trap on 0.  For example, in some
 historical interactive shell sessions the following trap on 0 would
 always print --:

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

 Examples:

 Write out a list of all traps and actions:

       trap

 Set a trap so the logout utility in the HOME directory will execute when
 the shell terminates:

       trap '$HOME/logout' EXIT

       _o_r
       trap '$HOME/logout' 0

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




               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       313





 P1003.2/D11.2                               INFORMATION TECHNOLOGY--POSIX

       trap - INT QUIT TERM EXIT

 END_RATIONALE


 3.14.14  unset - Unset values and attributes of variables and functions

       unset  [-fv] _n_a_m_e ...                                                1

 Each variable or function specified by _n_a_m_e shall be unset.

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

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

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

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

 The unset special built-in shall conform to the utility argument syntax
 guidelines described in 2.10.2.

 _E_x_i_t__S_t_a_t_u_s

     0    All _n_a_m_es were successfully unset.

    >0    At least one _n_a_m_e could not be unset.

 BEGIN_RATIONALE


 3.14.14.1  unset Rationale. (_T_h_i_s _s_u_b_c_l_a_u_s_e _i_s _n_o_t _a _p_a_r_t _o_f _P_1_0_0_3._2)

 Note that

       VARIABLE=

 is not equivalent to an unset of VARIABLE; in the example, VARIABLE is
 set to "".  Also, the ``variables'' that can be unset should not be
 misinterpreted to include the special parameters (see 3.5.2).

 Consideration was given to omitting the -f option in favor of an
 unfunction utility, but decided to retain existing practice.


               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 314                                              3 Shell Command Language





 Part 2: SHELL AND UTILITIES                                 P1003.2/D11.2

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

 Examples:

 Unset the VISUAL variable:

       unset -v VISUAL                                                      1

 Unset the functions foo and bar:

       unset -f foo bar

 END_RATIONALE

































               Copyright c 1991 IEEE.  All rights reserved.
      This is an unapproved IEEE Standards Draft, subject to change.





 3.14 Special Built-in Utilities                                       315







































































