SH(1)

SH(1) | General Commands Manual | SH(1)

# NAME

`sh` — command interpreter (shell)

# SYNOPSIS

`sh` | [`-abCEeFfhIiLlmnpqruVvXx`] [`+abCEeFfhIiLlmnpqruVvXx`] [`-o` option_name] [`+o` option_name] [command_file [argument ...]]

`sh` | `-c` [`-s`] [`-abCEeFfhIiLlmnpqruVvXx`] [`+abCEeFfhIiLlmnpqruVvXx`] [`-o` option_name] [`+o` option_name] command_string [command_name [argument ...]]

`sh` | `-s` [`-abCEeFfhIiLlmnpqruVvXx`] [`+abCEeFfhIiLlmnpqruVvXx`] [`-o` option_name] [`+o` option_name] [argument ...]

# DESCRIPTION

`sh` is the standard command interpreter for the system. It is a re-implementation and extension of the Bourne shell. This version has many features which make it appear similar in some respects to the Korn shell, but it is not a Korn shell clone (see ksh(1)). This man page is not intended to be a tutorial or a complete specification of the shell.

## Overview

The shell is a command that reads lines from either a file or the terminal, interprets them, and generally executes other commands. A shell is the program that is running when a user logs into the system. (Users can select which shell is executed for them at login with the chsh(1) command). The shell implements a language that has flow control constructs, a macro facility that provides a variety of features in addition to data storage, along with built in history and line editing capabilities. It incorporates many features to aid interactive use and has the advantage that the interpretative language is common to both interactive and non-interactive use (shell scripts). That is, commands can be typed directly to the running shell or can be put into a file and the file can be executed directly by the shell.

## Invocation

If the `-r` option is present on the command line, alone, or following other (valid) options, the `sh` immediately prints its version information to standard output and exits. This allows invocations like

``sh` `-version``
as the (preceding) `-v` and `-e` are valid options, then when the `-r` is encountered, the version information is printed, and no more processing is attempted. Whether the remaining (apparent) options after the `-r` would have been valid or not is immaterial.

If no arguments are present and if the standard input, and standard error output, of the shell are connected to a terminal (or terminals, or if the `-i` flag is set), and the `-c` option is not present, the shell is considered an interactive shell. An interactive shell generally prompts before each command and handles programming and command errors differently (as described below). When first starting, if neither the `-l` nor `+l` options were given on the command line, the shell inspects argument 0, and if it begins with a dash ‘-’, or if the `-l` option was given, the shell is also considered a login shell. Beginning argument 0 with a dash is normally done automatically by the system when the user first logs in. A login shell first reads commands (as if by using the ‘`.`’ command) from the files /etc/profile and .profile in the user's home directory (`$HOME`), if they exist. If the environment variable `ENV` is set on entry to a shell, or is set in the .profile of a login shell, and either the shell is interactive, or the `posix` option is not set, the shell then performs parameter and arithmetic expansion on the value of `ENV`, (these are described later) and if no errors occurred, then reads commands from the file name that results. Note that no error messages result from these expansions, to verify that `ENV` is correct, as desired, use:

`eval printf '%s\\n' "${ENV}"`
Otherwise if `ENV` appears to contain a command substitution, which is never performed here, or if there were no expansions to expand, the value of `ENV` is used as the file name.

Therefore, a user should place commands that are to be executed only at login time in the .profile file, and commands that are executed for every shell inside the `ENV` file. To set the `ENV` variable to some file, place the following line in your .profile of your home directory

`ENV=$HOME/.shinit; export ENV`

substituting for .shinit any filename you wish. Since the `ENV` file can be read for every invocation of the shell, including shell scripts and non-interactive shells, the following paradigm is useful for restricting commands in the `ENV` file to interactive invocations. Place commands within the “`case`” and “`esac`” below (these commands are described later):

    case $- in *i*)
            # commands for interactive use only
            ...
    esac

If command line arguments besides the options have been specified, and neither `-c` nor `-s` was given, then the shell treats the first argument as the name of a file from which to read commands (a shell script). This also becomes `$0` and the remaining arguments are set as the positional parameters of the shell (`$1`, `$2`, etc). Otherwise, if `-c` was given, then the first argument, which must exist, is taken to be a string of `sh` commands to execute. Then if any additional arguments follow the command string, those arguments become `$0`, `$1`, ... Otherwise, if additional arguments were given (which implies that `-s` was set) those arguments become `$1`, `$2`, ... If `$0` has not been set by the preceding processing, it will be set to argv[0] as passed to the shell, which will usually be the name of the shell itself. If `-s` was given, or if neither `-c` nor any additional (non-option) arguments were present, the shell reads commands from its standard input.

## Argument List Processing

Currently, all of the single letter options that can meaningfully be set using the `set` built-in, have a corresponding name that can be used as an argument to the `-o` option. The `set` `-o` name is provided next to the single letter option in the description below. Some options have only a long name, and are used with `-o` or `+o` only, either on the command line, or with the `set` built-in command. Those are listed in the table below after the options with a one letter, flag, equivalent.

Other options described are for the command line only. Specifying using a dash (or minus) “`-`” turns the option on, while using a plus “`+`” disables the option. This may seem counter-intuitive, but is in line with the common practice where `cmd` `-x` runs `cmd` with the ‘x’ option set.

The following options can be set from the command line and, unless otherwise stated, with the `set` built-in (described later).

`-a` allexport
  Automatically export any variable to which a value is assigned while this flag is set, unless the variable has been marked as not for export.
`-b` notify
  Enable asynchronous notification of background job completion. (Not implemented.)
`-C` noclobber
  Don't overwrite existing files with “>”.
`-c`
  Read commands from the command_string operand instead of, or in addition to, from the standard input. Special parameter `0` will be set from the command_name operand if given, and the positional parameters (`1`, `2`, etc.) set from the remaining argument operands, if any. `-c` is only available at invocation, it cannot be `set`, and there is no form using “`+`”.
`-E` emacs
  Enable the built-in emacs style command line editor (disables `-V` if it had been set). (See the Command Line Editing section below.)
`-e` errexit
  If not interactive, exit immediately if any untested command fails. If interactive, and an untested command fails, cease all processing of the current command and return to prompt for a new command. The exit status of a command is considered to be explicitly tested if the command is used to control an `if`, `elif`, `while`, or `until`, or if the command is the left hand operand of an “&&” or “||” operator, or if it is a pipeline (or simple command) preceded by the “!” operator. With pipelines, only the status of the entire pipeline (usually generated by the last command it contains) is tested when `-e` is set to determine if the shell should exit.
`-F` fork
  Cause the shell to always use fork(2) instead of attempting vfork(2) when it needs to create a new process. This should normally have no visible effect, but can slow execution. The `sh` can be compiled to always use fork(2) in which case altering the `-F` flag has no effect.
`-f` noglob
  Disable pathname expansion.
`-h` trackall
  Functions defined while this option is set will have paths bound to commands to be executed by the function at the time of the definition. When off when a function is defined, the file system is searched for commands each time the function is invoked. (Obsolete and not implemented.)
`-I` ignoreeof
  Ignore EOFs from input when interactive. (After a large number of consecutive EOFs the shell will exit anyway.)
`-i` interactive
  Force the shell to behave interactively. If not set on the command line, this option is set automatically at shell startup if the shell is reading from standard input (no `-c`, or command_file given at invocation of `sh`), and standard input and standard error refer to terminal type devices.
`-L` local_lineno
  When set, before a function is defined, causes the variable `LINENO` when used within the function, to refer to the line number defined such that first line of the function is line 1. When reset, `LINENO` in a function refers to the line number within the file within which the definition of the function occurs. This option defaults to “on” in this shell. For more details see the section Using `LINENO` below.
`-l` login
  When set on the command line, the shell will be considered a login shell. When reset on the command line (`+l` or `+o` login), the shell will not be considered a login shell, even if the command name parameter (argv[0]) begins with a dash (‘-’). See Invocation for the effects of this. Changing the value of this option while the shell is running has no effect.
`-m` monitor
  Turn on job control (set automatically at shell startup, if not mentioned on the command line, when interactive).
`-n` noexec
  Read and parse commands, but do not execute them. This is useful for checking the syntax of shell scripts. If `-n` becomes set in an interactive shell, it will automatically be cleared just before the next time the command line prompt (`PS1`) is written.
`-p` nopriv
  Do not attempt to reset effective UID if it does not match UID. The same applies to effective and real GIDs. This is not set by default to help avoid incorrect usage by setuid root programs via system(3) or popen(3). This option is effective only when set on the command line, but can be reset to drop privileges, once, at any time. If `-p` is cleared, those privileges can never be regained, however much the `-p` option is manipulated.
`-q` quietprofile
  If the `-v` or `-x` options have been set, temporarily disable them before reading initialization files, these being /etc/profile, .profile, and the file specified by the `ENV` environment variable.
`-r`
  Print `sh` version information and exit. It is immaterial whether the option follows `-` or `+`. See Invocation above. This option is valid only on the command line.
`-s` stdin
  Read commands from standard input (set automatically if neither `-c` nor file arguments are present). If after processing a command_string with the `-c` option, the shell has not exited, and the `-s` option is set, it will continue reading more commands from standard input. This option has no effect when set or reset after the shell has already started reading from the command_file, or from standard input. Note that the `-s` flag being set does not, of itself, cause the shell to be interactive.
`-u` nounset
  Write a message to standard error when attempting to obtain a value from a variable that is not set, and if the shell is not interactive, exit immediately. For interactive shells, instead return immediately to the command prompt and read the next command. Note that expansions (described later, see Word Expansions below) using the ‘+’, ‘-’, ‘=’, or ‘?’ operators test if the variable is set, before attempting to obtain its value, and hence are unaffected by `-u`.
`-V` vi
  Enable the built-in vi(1) command line editor (disables `-E` if it had been set). (See the Command Line Editing section below.)
`-v` verbose
  The shell writes its input to standard error as it is read. Perhaps occasionally useful for some debugging.
`-X` xlock
  Cause output from the `xtrace` (`-x`) option to be sent to standard error as it exists when the `-X` option is enabled (regardless of its previous state.) For example:

              set -X 2>/tmp/trace-file

  will arrange for tracing output to be sent to the file named, instead of wherever it was previously being sent, until the X option is set again, or cleared.

  Each change (set or clear) to `-X` is also performed upon `-x`, but not the converse.

`-x` xtrace
  Write each command to standard error (preceded by the expanded value of `$PS4`) before it is executed. Unless `-X` is set, “standard error” means that which existed immediately before any redirections to be applied to the command are performed. Useful for debugging.

The following options have no one letter variant, and are used only in conjunction with `-o` or `+o`, either on the command line, or via the `set` built-in command.

cdprint
  Make an interactive shell always print the new directory name when changed by the `cd` command. If the posix option is set, this option also applies to non-interactive shells. However, cdprint is an extension to POSIX, so these two options should rarely be set at the same time.
nolog
  Prevent the entry of function definitions into the command history (see `fc` in the Built-ins section.) (Not implemented.)
pipefail
  If set when a pipeline is created, the way the exit status of the pipeline is determined is altered. See Pipelines below for the details.
posix
  Enables closer adherence to the POSIX shell standard. This option will default set at shell startup if the environment variable `POSIXLY_CORRECT` is present. That can be overridden (set or reset) by the `-o` option on the command line. Currently this option controls whether (!posix) or not (posix) the file given by the `ENV` variable is read at startup by a non-interactive shell. It also controls whether file descriptors greater than 2 opened using the `exec` built-in command are passed on to utilities executed (“yes” in posix mode, though the POSIX standard does not actually require this), whether a colon (:) terminates the user name in tilde (~) expansions other than in assignment statements (“no” in posix mode), the format of the output of the `kill` `-l` command, where posix mode causes the names of the signals be separated by either a single space or newline, and where otherwise sufficient spaces are inserted to generate nice looking columns, and whether the shell treats an empty brace-list compound statement as a syntax error (expected by POSIX) or permits it. Such statements “{ }” can be useful when defining dummy functions. Lastly, in posix mode, only one “!” is permitted before a pipeline.
promptcmds
  Allows command substitutions (as well as parameter and arithmetic expansions, which are always performed) upon the prompt strings `PS1`, `PS2`, and `PS4` each time, before they are output. This option should not be set until after the prompts have been set (or verified) to avoid accidentally importing unwanted command substitutions from the environment.
tabcomplete
  Enables filename completion in the command line editor. Typing a tab character will extend the current input word to match a filename. If more than one filename matches it is only extended to be the common prefix. Typing a second tab character will list all the matching names. One of the editing modes, either `-E` or `-V`, must be enabled for this to work.

## Lexical Structure

The shell reads input in terms of lines from a file (or its standard input, or an argument string), removes comments, and then breaks it up into words at whitespace (blanks and tabs), and at certain sequences of characters that are special to the shell called “operators”. Unquoted whitespace is removed as part of this, after serving to separate words or operators. There are two types of operators: control operators and redirection operators (their meaning is discussed later). The following is a list of operators:

Control operators:
  `& && ( ) ; ;; ;& | || <newline>`
Redirection operators:
  `< > >| << >> <& >& <<- <>`

The shell will detect an operator, which must be entirely unquoted, at any point in the input line (other than in comments, which have already been removed), and sometimes other than immediately after an unquoted dollar (‘$’) character, see Word Expansions below for defined sequences starting with (‘$’) which always form (part of) a word, even if some of the following characters would otherwise appear to be operators.

For future proofing, it is advisable to precede and follow all operators with either line endings or whitespace. When recognizing an operator the longest sequence of characters present which form a valid operator are detected as that operator rather than shorter alternative sequences, so, for example, the sequence

`>&`
is always recognized as the two character redirection operator “`>&`” rather than the “`>`” redirection operator followed by control operator “`&`”. So while currently the sequence
`;)`
is recognized as the two control operators “`;`” followed by “`)`”, a future extension could create a new operator “`;)`” in which case that would be detected instead. Writing the sequence as
`; )`
(note the space between the semicolon and parenthesis) guarantees that it will be recognized as two operators. Note that this does happen, the “`;&`” control operator shown above is relatively new (by shell standards) and would once have been parsed as two operators.

Also note that any of the redirection operators listed above may be immediately preceded by a digit sequence, with no intervening whitespace. Those digits form part of the redirection operator. See Redirections below for more details.

## Comments

A shell comment begins with a ‘`#`’ character at the beginning of a word, that is, at the beginning of the line, or after unquoted whitespace or an operator. All characters, without interpretation, from (and including) the ‘`#`’, until the end of the current line (or EOF), but excluding the line ending ‘`\n`’, are removed from the input. Note that it is not possible to continue a line containing a comment. Also note that a ‘`#`’ character at any other place within a word is simply a character, and is sometimes required to implement specific shell operations.

## Quoting

Quoting is used to remove the special meaning of certain characters or words to the shell, such as operators, whitespace, or keywords. Beginning or ending a quoted sequence does not end a shell word. There are four types of quoting: matched single quotes, matched double quotes, backslash, and dollar preceding matched single quotes (enhanced C style strings.)

## Backslash

An unquoted backslash quotes, and so preserves the literal meaning of, the following character, with the exception of ⟨newline⟩. That is, the quoted character just means itself, and is not considered as an operator, or whitespace, or the beginning of a comment, or any other special meaning it may otherwise have had. It may be joined with adjacent characters (along with the quoting backslash, which is removed much later) to form part of a word. An unquoted backslash preceding a ⟨newline⟩ is treated as a line continuation, the two characters are simply removed.

## Single Quotes

Enclosing characters in a pair of single quotes preserves the literal meaning of all the characters between them (except single quotes, making it impossible to put single quotes in a single-quoted string).

## Double Quotes

Enclosing characters within double quotes preserves the literal meaning of all characters except dollar sign (`$`), backquote (```), backslash (`\`), and itself (`"`). The backslash inside double quotes is historically weird, and serves to quote only the following characters (and these not in all contexts):

`$ ` " \ <newline>`
, where a backslash newline is a line continuation as above. Otherwise it remains literal. The dollar sign and backquote characters, inside a double quoted string, if not escaped by a backslash, retain the meaning they would have if unquoted, however the results of any expansion(s) they eventually generate are treated as quoted in this case.

## Dollar Single Quotes (`$'...'`)

Enclosing characters in a matched pair of single quotes, with the first immediately preceded by an unquoted dollar sign (`$`) provides a quoting mechanism similar to single quotes, except that within the sequence of characters, any backslash (`\`), is an escape character, which causes the following character to be treated specially. Only a subset of the characters that can occur in the string are defined after a backslash, others are reserved for future definition, and currently generate a syntax error if used. The escape sequences are modeled after the similar sequences in strings in the C programming language, with some extensions.

The following characters are treated literally when following the escape character (backslash):

`\ ' "`
The sequence “`\\`” allows the escape character (backslash) to appear in the string literally. “`\'`” allows a single quote character into the string, such an escaped single quote does not terminate the quoted string. “`\"`” is for compatibility with C strings, the double quote has no special meaning in a shell C-style string, and does not need to be escaped, but may be.

A newline following the escape character is treated as a line continuation, like the same sequence in a double quoted string, or when not quoted – the two characters, the backslash escape and the newline, are removed from the input string.

The following characters, when escaped, are converted in a manner similar to the way they would be in a string in the C language:

`a b e f n r t v`
An escaped ‘a’ generates an alert (or ‘BEL’) character, that is, control-G, or 0x07. In a similar way, ‘b’ is backspace (0x08), ‘e’ (an extension to C) is escape (0x1B), ‘f’ is form feed (0x0C), ‘n’ is newline (or line feed, 0x0A), ‘r’ is return (0x0D), ‘t’ is horizontal tab (0x09), and ‘v’ is vertical tab (0x13).

In addition to those there are 5 forms that need additional data, which is obtained from the subsequent characters. An escape (`\`) followed by one, two or three, octal digits (‘0’..‘7’) is processed to form an 8 bit character value. If only one or two digits are present, the following character must be something other than an octal digit. It is safest to always use all 3 digits, with leading zeros if needed. If all three digits are present, the first must be one of ‘0’..‘3’.

An escape followed by ‘x’ (lower case only) can be followed by one or two hexadecimal digits (‘0’..‘9’, ‘A’..‘F’, or ‘a’..‘f’.) As with octal, if only one hex digit is present, the following character must be something other than a hex digit, so always giving 2 hex digits is best. However, unlike octal, it is unspecified in the standard how many hex digits can be consumed. This `sh` takes at most two, but other shells will continue consuming characters as long as they remain valid hex digits. Consequently, users should ensure that the character following the hex escape sequence is something other than a hex digit. One way to achieve this is to end the `$'...'` string immediately after the final hex digit, and then, immediately start another, so

`$'\x33'$'4...'`
always gives the character with value 0x33 (‘3’), followed by the character ‘4’, whereas
`$'\x334'`
in some other shells would be the hex value 0x334 (10, or more, bits).

There are two escape sequences beginning with ‘`\u`’ or ‘`\U`’. The former is followed by from 1 to 4 hex digits, the latter by from 1 to 8 hex digits. Leading zeros can be used to pad the sequences to the maximum permitted length, to avoid any possible ambiguity problem with the following character, and because there are some shells that insist on exactly 4 (or 8) hex digits. These sequences are evaluated to form the value of a Unicode code point, which is then encoded into UTF-8 form, and entered into the string. (The code point should be converted to the appropriate code point value for the corresponding character in the character set given by the current locale, or perhaps the locale in use when the shell was started, but is not... currently.) Not all values that are possible to write are valid, values that specify (known) invalid Unicode code points will be rejected, or simply produce ‘?’.

Lastly, as another addition to what is available in C, the escape character (backslash), followed by ‘c’ (lower case only) followed by one additional character, which must be an alphabetic character (a letter), or one of the following:

`@ [ \ ] ^ _ ?`
Other than ‘`\c?`’ the value obtained is the least significant 5 bits of the ASCII value of the character following the ‘`\c`’ escape sequence. That is what is commonly known as the “control” character obtained from the given character. The escape sequence ‘`\c?`’ yields the ASCII DEL character (0x7F). Note that to obtain the ASCII FS character (0x1C) this way, (that is control-\) the trailing ‘`\`’ must be escaped itself, and so for this one case, the full escape sequence is “`\c\\`”. The sequence “`\c\`X” where ‘X’ is some character other than ‘`\`’ is reserved for future use, its meaning is unspecified. In this `sh` an error is generated.

If any of the preceding escape sequences generate the value ‘\0’ (a NUL character) that character, and all that follow in the same `$'...'` string, are omitted from the resulting word.

After the `$'...'` string has had any included escape sequences converted, it is treated as if it had been a single quoted string.

## Reserved Words

Reserved words are words that have special meaning to the shell and are recognized, if completely unquoted, at the beginning of a line, after a control operator, and where the syntax of a command specifically requires a reserved word. The following are reserved words:

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

Their meanings are discussed later.

## Aliases

An alias is a name and corresponding value set using the `alias` built-in command. Whenever a reserved word (see above) may occur, and after checking for reserved words, the shell checks the word to see if it matches an alias. If it does, the alias word is replaced by its value in the input stream, as if the value had been entered instead. For example, if there is an alias called “lf” with the value “ls -F”, then the input:

`lf foobar ⟨return⟩`

would become

`ls -F foobar ⟨return⟩`

Aliases provide a convenient way for naive users to create shorthands for commands without having to learn how to create functions with arguments. They can also be used to create lexically obscure code. This use is strongly discouraged.

## Commands

The shell interprets the words it reads according to a language, the specification of which is outside the scope of this man page (refer to the BNF in the POSIX 1003.2 document). Essentially though, a line is read and if the first word of the line (or after a control operator) is not a reserved word, then the shell has recognized a simple command. Otherwise, a complex command or some other special construct may have been recognized.

## Simple Commands

If a simple command has been recognized, the shell performs the following actions:

1. Leading words of the form “name`=`value” are stripped off, the value is expanded, as described below, and the results are assigned to the environment of the simple command. Redirection operators and their arguments (as described below) are stripped off and saved for processing in step 3 below.
2. The remaining words are expanded as described in the Word Expansions section below. The first remaining word is considered the command name and the command is located. Any remaining words are considered the arguments of the command. If no command name resulted, then the “name`=`value” variable assignments recognized in item 1 affect the current shell, but are not automatically added to the environment (are not exported).
3. Redirections are performed, from first to last, in the order given, as described in the next section.

## Redirections

Redirections are used to change where a command reads its input or sends its output. In general, redirections open, close, or duplicate an existing reference to a file. The overall format used for redirection is:

`[n]redir-op file`

where redir-op is one of the redirection operators mentioned previously. A list of the possible redirections, and their meanings, follows.

The [n] is an optional number, as in ‘`3`’ (not ‘`[3]`’), that refers to a file descriptor. If present it must occur unquoted, immediately before the redirection operator, with no intervening white space, and becomes a part of that operator. If not explicitly present, n will be 0 (standard input) or 1 (standard output) depending upon the redirection operator used. If file descriptor n was open prior to the redirection, its previous use is closed.

All redirections have a single word file argument following the operator (white space is allowed between the redirection operator and file), though it is sometimes expressed as n2. That argument is expanded (see Word Expansions below) using tilde expansion, parameter expansion, arithmetic expansion, command substitution and quote removal to produce the path name (or file descriptor) to be used. No field splitting or pathname expansion takes place. In the list below, where the file is given as n2 the result of the expansions must be a number which refers to a suitable open file descriptor.

[n]`>` file
  Redirect standard output (or n) to file.
[n]`>|` file
  The same, but override the `-C` option.
[n]`>>` file
  Append standard output (or n) to file.
[n]`<` file
  Redirect standard input (or n) from file.
[n1]`<&` n2
  Redirect standard input (or n1) from a duplicate of file descriptor n2.
[n]`<& −`
  Close standard input (or n). Note that the ‘−’ is minus sign (or hyphen) given literally or resulting from the expansion of file (or n2) for this format. When given literally there is usually no space between the redirection operator and the ‘−’, though that is just a convention.
[n1]`>&` n2
  Redirect standard output (or n1) to be a duplicate of n2.
[n]`>& −`
  Close standard output (or n).
[n]`<>` file
  Open file for reading and writing on standard input (or n).

The following redirection is often called a “here-document”.

    [n]<< delimiter
    ... here-doc-text ...
    delimiter

The “here-doc-text” starts immediately after the next unquoted newline character following the here-document redirection operator. If there is more than one here-document redirection on the same line, then the text for the first (from left to right) is read first, and subsequent here-doc-text for later here-document redirections follows immediately after, until all such redirections have been processed.

All the text on successive lines up to the delimiter, which must appear on a line by itself, with nothing other than an immediately following newline, is saved away and made available to the command on standard input, or file descriptor n if it is specified. If the delimiter as specified on the initial line is quoted, then the here-doc-text is treated literally; otherwise, the text is treated much like a double quoted string, except that ‘`"`’ characters have no special meaning, and are not escaped by ‘`\`’, and is subjected to parameter expansion, command substitution, and arithmetic expansion as described in the Word Expansions section below. If the operator is `<<-` instead of `<<`, then leading tabs in all lines in the here-doc-text, including before the end delimiter, are stripped. If the delimiter is not quoted, lines in here-doc-text that end with an unquoted `\` are joined to the following line, the `\` and following newline are simply removed while reading the here-document, which thus guarantees that neither of those lines can be the end delimiter.

It is a syntax error for the end of the input file (or string) to be reached before the delimiter is encountered.

## Search and Execution

There are three types of commands: shell functions, built-in commands, and normal programs — and the command is searched for (by name) in that order. A command that contains a slash ‘/’ in its name is always a normal program. They each are executed in a different way.

When a shell function is executed, all of the shell positional parameters (note: excluding `0`, which is a special, not positional, parameter, and remains unchanged) are set to the arguments of the shell function. The variables which are explicitly placed in the environment of the command (by placing assignments to them before the function name) are made local to the function and are set to the values given, and exported for the benefit of programs executed within the function. Then the command given in the function definition is executed. The positional parameters, and local variables, are restored to their original values when the command completes. This all occurs within the current shell, and the function can alter variables, or other settings, of the shell, but not the positional parameters nor their related special parameters.

Shell built-ins are executed internally to the shell, without spawning a new process.

Otherwise, if the command name doesn't match a function or built-in, the command is searched for as a normal program in the file system (as described in the next section). When a normal program is executed, the shell runs the program, passing the arguments and the environment to the program. If the program is not a normal executable file, and if it does not begin with the “magic number” whose ASCII representation is “`#!`”, so execve(2) returns `ENOEXEC` then) the shell will interpret the program in a sub-shell. The child shell will reinitialize itself in this case, so that the effect will be as if a new shell had been invoked to handle the ad-hoc shell script, except that the location of hashed commands located in the parent shell will be remembered by the child.

Note that previous versions of this document and the source code itself misleadingly and sporadically refer to a shell script without a magic number as a “shell procedure”.

## Path Search

When locating a command, command names containing a slash (‘/’) are simply executed without performing any searches.

If there is no slash in the name, the shell first looks to see if it is a special built-in command, if not it looks to see if there is a shell function by that name. If that fails it looks for an ordinary built-in command. If a none of these searches located the command the shell searches each entry in `PATH` in turn for the command. The value of the `PATH` variable should be a series of entries separated by colons. Each entry consists of a directory name. The current directory may be indicated implicitly by an empty directory name, or explicitly by a single period. If a directory searched contains an executable file with the same name as the command given, the search terminates, and that program is executed.

## Command Exit Status

Each command has an exit status that can influence the behavior of other shell commands. The paradigm is that a command exits with zero in normal cases, or to indicate success, and non-zero for failure, error, or a false indication. The man page for each command should indicate the various exit codes and what they mean. Additionally, the built-in commands return exit codes, as does an executed shell function.

If a command consists entirely of variable assignments then the exit status of the command is that of the last command substitution if any, otherwise 0.

If redirections are present, and any fail to be correctly performed, any command present is not executed, and an exit status of 2 is returned.

## Complex Commands

Complex commands are combinations of simple commands with control operators or reserved words, together creating a larger complex command. Overall, a shell program is a:

list
  Which is a sequence of one or more AND-OR lists.
AND-OR list
  is a sequence of one or more pipelines.
pipeline
  is a sequence of one or more commands.
command
  is one of a simple command, a compound command, or a function definition.
simple command
  has been explained above, and is the basic building block.
compound command
  provides mechanisms to group lists to achieve different effects.
function definition
  allows new simple commands to be created as groupings of existing commands.

Unless otherwise stated, the exit status of a list is that of the last simple command executed by the list.

## Pipelines

A pipeline is a sequence of one or more commands separated by the control operator ‘`|`’, and optionally preceded by the “`!`” reserved word. Note that ‘`|`’ is an operator, and so is recognized anywhere it appears unquoted, it does not require surrounding white space or other syntax elements. On the other hand “`!`” being a reserved word, must be separated from adjacent words by white space (or other operators, perhaps redirects) and is only recognized as the reserved word when it appears in a command word position (such as at the beginning of a pipeline.)

The standard output of all but the last command in the sequence is connected to the standard input of the next command. The standard output of the last command is inherited from the shell, as usual, as is the standard input of the first command.

The format for a pipeline is:

`[!] command1 [`| command2` ...]`

The standard output of command1 is connected to the standard input of command2. The standard input, standard output, or both of each command is considered to be assigned by the pipeline before any redirection specified by redirection operators that are part of the command are performed.

If the pipeline is not in the background (discussed later), the shell waits for all commands to complete.

The commands in a pipeline can either be simple commands, or one of the compound commands described below. The simplest case of a pipeline is a single simple command.

If the `pipefail` option was set when a pipeline was started, the pipeline status is the status of the last (lexically last, i.e.: rightmost) command in the pipeline to exit with non-zero exit status, or zero, if, and only if, all commands in the pipeline exited with a status of zero. If the `pipefail` option was not set, which is the default state, the pipeline status is the exit status of the last (rightmost) command in the pipeline, and the exit status of any other commands in the pipeline is ignored.

If the reserved word “`!`” precedes the pipeline, the exit status becomes the logical NOT of the pipeline status as determined above. That is, if the pipeline status is zero, the exit status is 1; if the pipeline status is other than zero, the exit status is zero. If there is no “`!`” reserved word, the pipeline status becomes the exit status.

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.

Note that unlike some other shells, each process in the pipeline is a child of the invoking shell, except in the case where the pipeline is a single simple command (no ‘`|`’ characters appear.)

A pipeline is a simple case of an AND-OR-list (described below.) A `;` or ⟨newline⟩ terminator causes the preceding pipeline, or more generally, the preceding AND-OR-list to be executed sequentially; that is, the shell executes the commands, and waits for them to finish before proceeding to following commands. An `&` terminator causes asynchronous (background) execution of the preceding AND-OR-list (see the next paragraph below). The exit status of an asynchronous AND-OR-list is zero. The actual status of the commands, after they have completed, can be obtained using the `wait` built-in command described later.

## Background Commands — `&`

If a command, pipeline, or AND-OR-list is terminated by the control operator ampersand (`&`), the shell executes the command asynchronously — that is, the shell does not wait for the command to finish before executing the next command.

The format for running a command in background is:

`command1 & [`command2 &` ...]`

If the shell is not interactive, the standard input of an asynchronous command is set to /dev/null. The process identifier of the most recent command started in the background can be obtained from the value of the special parameter “`!`” (see Special Parameters) provided it is accessed before the next asynchronous command is started.

## Lists — Generally Speaking

A list is a sequence of one or more commands separated by newlines, semicolons, or ampersands, and optionally terminated by one of these three characters. A shell program, which includes the commands given to an interactive shell, is a list. Each command in such a list is executed when it is fully parsed. Another use of a list is as a complete-command, which is parsed in its entirety, and then later the commands in the list are executed only if there were no parsing errors.

The commands in a list are executed in the order they are written. If command is followed by an ampersand, the shell starts the command and immediately proceeds to the next command; otherwise it waits for the command to terminate before proceeding to the next one. A newline is equivalent to a ‘`;`’ when no other operator is present, and the command being input could syntactically correctly be terminated at the point where the newline is encountered, otherwise it is just whitespace.

## AND-OR Lists (Short-Circuit List Operators)

“`&&`” and “`||`” are AND-OR list operators. After executing the commands that precede the “`&&`” the subsequent command is executed if and only if the exit status of the preceding command(s) is zero. “`||`” is similar, but executes the subsequent command if and only if the exit status of the preceding command is nonzero. If a command is not executed, the exit status remains unchanged and the following AND-OR list operator (if any) uses that status. “`&&`” and “`||`” both have the same priority. Note that these operators are left-associative, so

`true || echo bar && echo baz`
writes “baz” and nothing else. This is not the way it works in C.

## Flow-Control Constructs — `if`, `while`, `until`, `for`, `case`

These commands are instances of compound commands. The syntax of the `if` command is

    if list
    then list
    [elif list
    then list] ...
    [else list]
    fi

The first list is executed, and if the exit status of that list is zero, the list following the `then` is executed. Otherwise the list after an `elif` (if any) is executed and the process repeats. When no more `elif` reserved words, and accompanying lists, appear, the list after the `else` reserved word, if any, is executed.

The syntax of the `while` command is

    while list
    do list
    done

The two lists are executed repeatedly while the exit status of the first list is zero. The `until` command is similar, but has the word `until` in place of `while`, which causes it to repeat until the exit status of the first list is zero.

The syntax of the `for` command is

    for variable [in word ...]
    do list
    done

The words are expanded, or `"$@"` if `in` (and the following words) is not present, and then the list is executed repeatedly with the variable set to each word in turn. If `in` appears after the variable, but no words are present, the list is not executed, and the exit status is zero. `do` and `done` may be replaced with ‘`{`’ and ‘`}`’, but doing so is non-standard and not recommended.

The syntax of the `break` and `continue` commands is

    break [num]
    continue [num]

`break` terminates the num innermost `for`, `while`, or `until` loops. `continue` breaks execution of the num-1 innermost `for`, `while`, or `until` loops, and then continues with the next iteration of the enclosing loop. These are implemented as special built-in commands. The parameter num, if given, must be an unsigned positive integer (greater than zero). If not given, 1 is used.

The syntax of the `case` command is

    case word in
    [(] pattern) [list] ;&
    [(] pattern) [list] ;;
    ...
    esac

The pattern can actually be one or more patterns (see Shell Patterns described later), separated by “|” characters.

word is expanded (tilde, variable, arithmetic, and command substitution only, then quote removal, no pathname expansion or field splitting is performed) and matched against each pattern in turn, from first to last, with each pattern being expanded (as for word) with quoting escaping characters special to pattern matching, just before the match is attempted. When a match is found, pattern comparisons cease, and the associated list, if given, is evaluated. If the list is terminated with “`;&`” execution then falls through to the following list, if any, without evaluating its pattern, or attempting a match. When a list terminated with “`;;`” has been executed, or when `esac` is reached, execution of the `case` statement is complete. The exit status is that of the last command executed from the last list evaluated, if any, or zero otherwise.

## Grouping Commands Together

Commands may be grouped by writing either

``(`list`)``
or
``{` list`; }``
These also form compound commands.

Note that while parentheses are operators, and do not require any extra syntax, braces are reserved words, so the opening brace must be followed by white space (or some other operator), and the closing brace must occur in a position where a new command word might otherwise appear.

The first of these executes the commands in a sub-shell. Built-in commands grouped into a `(`list) will not affect the current shell. The second form does not fork another shell so is slightly more efficient, and allows for commands which do affect the current shell. Grouping commands together this way allows you to redirect their output as though they were one program:

    { echo -n "hello " ; echo "world" ; } > greeting

Note that “`}`” must follow a control operator (here, “`;`”) so that it is recognized as a reserved word and not as another command argument.

## Functions

The syntax of a function definition is

`name`()` command [redirect ...]`

A function definition is an executable statement; when executed it installs a function named name and returns an exit status of zero. To be portable, and standards compliant, the name must use the same syntax as a variable name, (see Variables and Parameters below). As an extension, this shell allows almost all characters in name (the exception is slash (‘/’) as there is no way to invoke a function with a name containing a slash). Including quoting, whitespace, and operator characters requires that the word be quoted. The name is subject to quote removal, but no other expansions. Because of implementation issues, unquoted dollar signs (‘$’) and backquotes (‘`’) are prohibited, but can be included in a function name by use of quoting.

The command is normally a list enclosed between “{” and “}”. The standard syntax also allows the command to be any of the other compound commands, including a sub-shell, all of which are supported. As an extension, this shell also allows a simple command (or even another function definition) to be used, though users should be aware this is non-standard syntax. This means that

`l() ls "$@"`
works to make “l” an alternative name for the `ls` command.

If the optional redirect, (see Redirections), which may be of any of the normal forms, is given, it is applied each time the function is called. This means that a simple “Hello World” function might be written (in the extended syntax) as:

    hello() cat <<EOF
    Hello World!
    EOF

To be correctly standards conforming this should be re-written as:

    hello() { cat; } <<EOF
    Hello World!
    EOF

Note the distinction between those forms, and

    hello() { cat <<EOF
    Hello World!
    EOF
    }

which reads and processes the here-document each time the shell executes the function, and which applies that input only to the cat command, not to any other commands that might appear in the function.

Variables may be declared to be local to a function by using the `local` command. This should usually appear as the first statement of a function, though `local` is an executable command which can be used anywhere in a function. See Built-ins below for its definition.

The function completes after having executed command with exit status set to the status returned by command. If command is a compound-command it can use the `return` command (see Built-ins below) to finish before completing all of command.

## Variables and Parameters

The shell maintains a set of parameters. A parameter denoted by a name is called a variable. When starting up, the shell turns all the environment variables into shell variables, and exports them. New variables can be set using the form

`name`=`value`

Variables set by the user must have a name consisting solely of alphabetics, numerics, and underscores — the first of which must not be numeric. A parameter can also be denoted by a number or a special character as explained below.

## Positional Parameters

A positional parameter is a parameter denoted by a number (n > 0). The shell sets these initially to the values of its command line arguments that follow the name of the shell script. The `set` built-in can also be used to set or reset them, and `shift` can be used to manipulate the list.

To refer to the 10th (and later) positional parameters, the form `${`n`}` must be used. Without the braces, a digit following “$” can only refer to one of the first 9 positional parameters, or the special parameter `0`. The word “`$10`” is treated identically to “`${1}0`”.

## Special Parameters

A special parameter is a parameter denoted by one of the following special characters. The value of the parameter is listed next to its character.

`*`
  Expands to the positional parameters, starting from one. When the expansion occurs in a situation where field splitting is never performed, such as within a double-quoted string, it expands to a single field with the value of each parameter separated by the first character of the `IFS` variable (possibly nothing if `IFS` has a null value), 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 argument. If the expansion happens in other situations where field splitting is not performed, whether double quoted or not, the results are undefined. In most shells, including this one, `$@` is treated as `$*` in such a context, but this is not universally true. If there are no positional parameters, the expansion of @ generates zero arguments, even when `$@` is double-quoted. What this basically means, for example, is if `$1` is “abc” and `$2` is “def ghi”, then `"$@"` expands to the two arguments:

  `"abc" "def ghi"`
`#`
  Expands to the number of positional parameters.
`?`
  Expands to the exit status of the most recent pipeline.
`-` (dash, hyphen, or minus)
  Expands to the current option flags (the single-letter option names concatenated into a string) as specified on invocation, by the set built-in command, or implicitly by the shell.
`$`
  Expands to the process ID of the invoked shell. A sub-shell retains the same value of `$` as its parent.
`!`
  Expands to the process ID of the most recent background command executed from the current shell. For a pipeline, the process ID is that of the last command in the pipeline. If no background commands have yet been started by the shell, then “`!`” will be unset. Once set, the value of “`!`” will be retained until another background command is started.
`0` (zero)
  Expands to the name of the shell or shell script.

## Word Expansions

This section describes the various expansions that are performed on words. Not all expansions are performed on every word, as explained later.

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 was described above.

The order of word expansion is:

1. Tilde Expansion, Parameter Expansion, Command Substitution, Arithmetic Expansion (these all occur at the same time, and the result of any of these expansions is not rescanned for further instances of the expansion, or any of the others).
2. Unless the `IFS` variable has an empty value, Field Splitting is performed on the text resulting from the expansions in step (1) except for Tilde Expansion.
3. Pathname Expansion (unless set `-f` is in effect).
4. Quote Removal.

The $ character is used to introduce parameter expansion, command substitution, or arithmetic evaluation.

## Tilde Expansion (substituting a user's home directory)

A word beginning with an unquoted tilde character (~) is subjected to tilde expansion. Provided all of the subsequent characters in the word are unquoted up to an unquoted slash (/) or when in an assignment or not in posix mode, an unquoted colon (:), or if neither of those appear, the end of the word, they are treated as a user name and are replaced with the pathname of the named user's home directory. If the user name is missing (as in ~/foobar), the tilde is replaced with the value of the `HOME` variable (the current user's home directory).

In variable assignments, an unquoted tilde immediately after the assignment operator (=), and each unquoted tilde immediately after an unquoted colon in the value to be assigned is also subject to tilde expansion as just stated.

## Parameter Expansion

The format for parameter expansion is as follows:

`${expression`}``

where expression consists of all characters until the matching ‘`}`’. Any ‘`}`’ escaped by a backslash or within a quoted string, and characters in embedded arithmetic expansions, command substitutions, and variable expansions, are not examined in determining the matching ‘`}`’.

The simplest form for parameter expansion is:

`${parameter`}``

The value, if any, of parameter is substituted.

The parameter name or symbol can be enclosed in braces, which are optional in this simple case, except for positional parameters with more than one digit or when parameter is followed by a character that could be interpreted as part of the name. If a parameter expansion occurs inside double quotes:

1. pathname expansion is not performed on the results of the expansion;
2. field splitting is not performed on the results of the expansion. Note that the special rules for `@` can result in multiple fields being produced, but this is not because of field-splitting. If unquoted, each field produced by `$@` is subject to field splitting.

In addition, a parameter expansion where braces are used, can be modified by using one of the following formats. If the ‘`:`’ is omitted in the following modifiers, then the test in the expansion applies only to unset parameters, not null ones.

`${`parameter`:-`word`}`
  Use Default Values. If parameter is unset or null, the expansion of word is substituted; otherwise, the value of parameter is substituted.
`${`parameter`:=`word`}`
  Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. In all cases, the final value of parameter is substituted. Only variables, not positional parameters or special parameters, can be assigned in this way.
`${`parameter`:?`[word]`}`
  Indicate Error if Null or Unset. If parameter is unset or null, the expansion of word (or a message indicating it is unset if word is omitted) is written to standard error and a non-interactive shell exits with a nonzero exit status. An interactive shell will not exit, but any associated command(s) will not be executed. If the parameter is set, its value is substituted.
`${`parameter`:+`word`}`
  Use Alternative Value. If parameter is unset or null, null is substituted; otherwise, the expansion of word is substituted. The value of parameter is not used in this expansion.
`${``#`parameter`}`
  String Length. The length in characters of the value of parameter.

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

`${`parameter`%`word`}`
  Remove Smallest Suffix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the suffix matched by the pattern deleted. If the word is to start with a ‘`%`’ character, it must be quoted.
`${`parameter`%%`word`}`
  Remove Largest Suffix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the largest portion of the suffix matched by the pattern deleted. The “`%%`” pattern operator only produces different results from the “`%`” operator when the pattern contains at least one unquoted ‘`*`’.
`${`parameter`#`word`}`
  Remove Smallest Prefix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted. If the word is to start with a ‘`#`’ character, it must be quoted.
`${`parameter`##`word`}`
  Remove Largest Prefix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the largest portion of the prefix matched by the pattern deleted. This has the same relationship with the “`#`” pattern operator as “`%%`” has with “`%`”.

## Command Substitution

Command substitution allows the output of a command to be substituted in place of the command (and surrounding syntax). Command substitution occurs when a word contains a command list enclosed as follows:

``$(`list`)``

or the older (“backquoted”) version, which is best avoided:

````list````

See the section Complex Commands above for the definition of `list`.

The shell expands the command substitution by executing the list in a sub-shell environment and replacing the command substitution with the standard output of the list after removing any sequence of one or more ⟨newline⟩s from the end of the substitution. (Embedded ⟨newline⟩s before the end of the output are not removed; however, during field splitting, they may be used to separate fields (as spaces usually are) depending on the value of `IFS` and any quoting that is in effect.)

Note that if a command substitution includes commands to be run in the background, the sub-shell running those commands will only wait for them to complete if an appropriate `wait` command is included in the command list. However, the shell in which the result of the command substitution will be used will wait for both the sub-shell to exit and for the file descriptor that was initially standard output for the command substitution sub-shell to be closed. In some circumstances this might not happen until all processes started by the command substitution have finished.

## Arithmetic Expansion

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

``$((`expression`))``

The expression in an arithmetic expansion is treated as if it were in double quotes, except that a double quote character inside the expression is just a normal character (it quotes nothing.) The shell expands all tokens in the expression for parameter expansion, command substitution, and quote removal (the only quoting character is the backslash ‘\’, and only when followed by another ‘\’, a dollar sign ‘$’, a backquote ‘`’ or a newline.)

Next, the shell evaluates the expanded result as an arithmetic expression and substitutes the calculated value of that expression.

Arithmetic expressions use a syntax similar to that of the C language, and are evaluated using the ‘`intmax_t`’ data type (this is an extension to POSIX, which requires only ‘`long`’ arithmetic.) Shell variables may be referenced by name inside an arithmetic expression, without needing a “$” sign. Variables that are not set, or which have an empty (null string) value, used this way evaluate as zero (that is, “x” in arithmetic, as an R-Value, is evaluated as “${x:-0}”) unless the `sh` `-u` flag is set, in which case a reference to an unset variable is an error. Note that unset variables used in the ${var} form expand to a null string, which might result in syntax errors. Referencing the value of a variable which is not numeric is an error.

All of the C expression operators applicable to integers are supported, and operate as they would in a C expression. Use white space, or parentheses, to disambiguate confusing syntax, otherwise, as in C, the longest sequence of consecutive characters which make a valid token (operator, variable name, or number) is taken to be that token, even if the token designated cannot be used and a different interpretation could produce a successful parse. This means, as an example, that “a+++++b” is parsed as the gibberish sequence “a ++ ++ + b”, rather than as the valid alternative “a ++ + ++ b”. Similarly, separate the ‘,’ operator from numbers with white space to avoid the possibility of confusion with the decimal indicator in some locales (though fractional, or floating-point, numbers are not supported in this implementation.)

It should not be necessary to state that the C operators which operate on, or produce, pointer types, are not supported. Those include unary “*” and “&” and the struct and array referencing binary operators: “.”, “->” and “[”.

## Field Splitting

After parameter expansion, command substitution, and arithmetic expansion the shell scans the results of expansions and substitutions that did not occur in double quotes, for field splitting and multiple fields can result.

The shell treats each character of the `IFS` as a delimiter and uses the delimiters to split the results of parameter expansion and command substitution into fields.

Non-whitespace characters in `IFS` are treated strictly as parameter separators. So adjacent non-whitespace `IFS` characters will produce empty parameters. On the other hand, any sequence of whitespace characters that occur in `IFS` (known as `IFS` whitespace) can occur, leading and trailing `IFS` whitespace, and any `IFS` whitespace surrounding a non whitespace `IFS` delimiter, is removed. Any sequence of `IFS` whitespace characters without a non-whitespace `IFS` delimiter acts as a single field separator.

If `IFS` is unset it is assumed to contain space, tab, and newline, all of which are `IFS` whitespace characters. If `IFS` is set to a null string, there are no delimiters, and no field splitting occurs.

## Pathname Expansion (File Name Generation)

Unless the `-f` flag is set, file name generation is performed after word splitting is complete. Each word is viewed as a series of patterns, separated by slashes. The process of expansion replaces the word with the names of all existing files whose names can be formed by replacing each pattern with a string that matches the specified pattern. There are two restrictions on this: first, a pattern cannot match a string containing a slash, and second, a pattern cannot match a string starting with a period unless the first character of the pattern is a period. The next section describes the patterns used for both Pathname Expansion and the `case` command.

## Shell Patterns

A pattern consists of normal characters, which match themselves, and meta-characters. The meta-characters are “!”, “*”, “?”, and “[”. These characters lose their special meanings if they are quoted. When command or variable substitution is performed and the dollar sign or backquotes are not double-quoted, the value of the variable or the output of the command is scanned for these characters and they are turned into meta-characters.

An asterisk (“*”) matches any string of characters. A question mark (“?”) matches any single character. A left bracket (“[”) introduces a character class. The end of the character class is indicated by a right bracket (“]”); if this “]” is missing then the “[” matches a “[” rather than introducing a character class. A character class matches any of the characters between the square brackets. A named class of characters (see wctype(3)) may be specified by surrounding the name with (“[:”) and (“:]”). For example, (“[[:alpha:]]”) is a shell pattern that matches a single letter. A range of characters may be specified using a minus sign (“−”). The character class may be complemented by making an exclamation mark (“!”) the first character of the character class.

To include a “]” in a character class, make it the first character listed (after the “!”, if any). To include a “−”, make it the first (after !) or last character listed. If both “]” and “−” are to be included, the “]” must be first (after !) and the “−” last, in the character class.

## Built-ins

This section lists the built-in commands which are built in because they need to perform some operation that can't be performed by a separate process. Or just because they traditionally are. In addition to these, there are several other commands that may be built in for efficiency (e.g. printf(1), echo(1), test(1), etc). Most built-in commands will exit with status 2 if used incorrectly (bad options, excess or insufficient number of arguments, etc). Otherwise, unless stated differently, the built-in commands exit with status 0, unless some error occurs, which would be reported to standard error.

`:` [arg ...]
  A null command that returns a 0 (true) exit value. Any arguments or redirects are evaluated just as for any other command, then ignored.

`.` file
  The dot command reads and executes the commands from the specified file in the current shell environment. The file does not need to be executable and is looked up from the directories listed in the `PATH` variable if its name does not contain a directory separator (‘/’). The `return` command (see below) can be used for a premature return from the sourced file.

  The POSIX standard has been unclear on how loop control keywords (break and continue) behave across a dot command boundary. This implementation allows them to control loops surrounding the dot command, but obviously such behavior should not be relied on. It is now permitted by the standard, but not required.

`alias` [name[`=`string ...]]
  If name`=`string is specified, the shell defines the alias name with value string. If just name is specified, the value of the alias name is printed. With no arguments, the `alias` built-in prints the names and values of all defined aliases (see `unalias`).

`bg` [job ...]
  Continue the specified jobs (or the current job if no jobs are given) in the background.

`command` [`-pVv`] command [arg ...]
  Execute the specified command but ignore shell functions when searching for it. (This is useful when you have a shell function with the same name as a command.)
  `-p`
    search for command using a `PATH` that guarantees to find all the standard utilities, but not necessarily any others.
  `-V`
    Do not execute the command but search for the command and print the resolution of the command search. This is the same as the `type` built-in.
  `-v`
    Do not execute the command but search for the command and print the absolute pathname of utilities, the name for built-ins or the expansion of aliases.

`cd` [`-Pe`] [directory [replace]]
  Switch to the specified directory (default `$HOME`). If replace is specified, then the new directory name is generated by replacing the first occurrence of the string directory in the current working directory name with replace. Otherwise if directory is ‘`-`’, then the current working directory is changed to the previous current working directory as set in `OLDPWD`. Otherwise if an entry for `CDPATH` appears in the environment of the `cd` command or the shell variable `CDPATH` is set and the directory name does not begin with a slash, and its first (or only) component isn't dot or dot dot, then the directories listed in `CDPATH` will be searched for the specified directory. The format of `CDPATH` is the same as that of `PATH`.

  The `-P` option (which is the unalterable default in this `sh`) instructs the shell to change to the directory specified (or determined) and if successful update `PWD` with the new physical directory path. That is the path name, not traversing any symbolic links, of the altered working directory of the shell.

  The `-e` option alters the interpretation of the exit status. `cd` will exit with status 0 if successful. If the directory was successfully changed, but `PWD` was unable to be updated, `cd` will exit with status 1 if the `-e` option was given, and status 0 otherwise. Upon any other error, including usage errors, and failing to successfully change directory, `cd` will exit with status 2.

  When the directory changes, and `PWD` is updated, the variable `OLDPWD` is set to the working directory ($`PWD`) as it was before the change.

  Some shells also support a `-L` option, which instructs the shell to update `PWD` with the logical path using string manipulation, and then to change the current directory accordingly. This is not supported.

  In an interactive shell, or if the `posix` option is set, the `cd` command will print out the name of the directory that it actually switched to; (that is, the pathname passed to the successful chdir(2) system call) if this is different from the name that the user gave, or if the `cdprint` option is set. The destination may be different because a non-empty element of the `CDPATH` mechanism was used, or because the replace argument was used, or because the directory parameter was specified as “-”.

`eval` string ...
  Concatenate all the string arguments with intervening spaces. Then parse and execute the resulting command. The exit status from `eval` is the exit status of the command executed, or 0 if there was none.

`exec` [command [arg ...]]
  Unless command is omitted, the shell process is replaced with the specified program (which must be a real program, not a shell built-in or function). Any redirections on the `exec` command are marked as permanent, so that they are not undone when the `exec` command finishes, which only happens if no command was given.

  When the `posix` option is not set, file descriptors created via such redirections, when no command is present, are marked close-on-exec (see open(2) `O_CLOEXEC` or fcntl(2) `F_SETFD /` `FD_CLOEXEC`), unless the descriptors refer to the standard input, output, or error (file descriptors 0, 1, 2). Traditionally Bourne-like shells (except ksh(1) and its close relatives), made those file descriptors available to exec'ed processes. To be assured the close-on-exec setting is off, redirect the descriptor to (or from) itself, either when invoking a command for which the descriptor is wanted open, or by using `exec` (perhaps the same `exec` as opened it, after the open) to leave the descriptor open in the shell and also pass it to all commands invoked subsequently. Alternatively, see the `fdflags` built-in command below, which can set, or clear, this, and other, file descriptor flags.

  If there is a usage, or redirection, error, `exec` will not exit from an interactive shell, but will restore all modified file descriptors to the state they had before the `exec` command was issued. But note that side effects of any redirections that succeeded, such as creating or truncating files, cannot be reversed. However if a command cannot be executed for any reason, even an interactive shell will exit. Non-interactive shells will exit on any error, as `exec` is a special built-in utility.

`exit` [exitstatus]
  Terminate the shell process. If exitstatus is given it is used as the exit status of the shell; otherwise the exit status of the preceding command (the current value of $?) is used.

`export` [`-nx`] name[=value] ...
`export` [`-x`] [`-p` [name ...]]
`export` `-q` [`-x`] name ...
  With no options, but one or more names, the specified names are exported so that they will appear in the environment of subsequent commands. With `-n` the specified names are un-exported. Variables can also be un-exported using the `unset` built in command. With `-x` (exclude) the specified names are marked not to be exported, and any that had been exported, will be un-exported. Later attempts to export the variable will be refused. Note this does not prevent explicitly exporting a variable to a single command, script or function by preceding that command invocation by a variable assignment to that variable, provided the variable is not also read-only. That is

      export -x FOO # FOO will now not be able to be exported
      export FOO    # this command will fail (non-fatally)

  But with

      FOO=some_value my_command

  `sh` still passes the value (`FOO=some_value`) to `my_command` through the environment.

  The shell allows the value of a variable to be set at the same time it is exported (or unexported, etc) by writing

  `export [-nx] name=value`

  Note that in such a usage, the “name=value” argument often needs to be quoted, more often than is required of an assignment statement, as, like with any other command, the command name and arguments are all subject to the various expansions, including filename expansion and field splitting, before the `export` command is invoked. With the default value for `IFS`:

      X='a b c'
      export Y=$X

  the command invoked would be
  `export Y=a b c`
  exporting `Y`, with the value “a” and also exporting the variables named “b” and “c”, which is probably not as intended.

  With no arguments the export command lists the names of all set exported variables, or if `-x` was given, all set variables marked not for export. With the `-p` option specified, the output will be formatted suitably for non-interactive use, and unset variables are included. When `-p` is given, variable names, but not values, may also be given, in which case output is limited to the variables named.

  With `-q` and a list of variable names, the `export` command will exit with status 0 if all the named variables have been marked for export, or 1 if any are not so marked. If `-x` is also given, the test is instead for variables marked not to be exported.

  Other than with `-q`, the `export` built-in exits with status 0, unless an attempt is made to export a variable which has been marked as unavailable for export, in which cases it exits with status 1. In all cases if an invalid option, or option combination, is given, or an invalid variable name is present, `export` will write a message to the standard error output, and exit with a non-zero status. A non-interactive shell will terminate.

  Note that there is no restriction upon exporting, or un-exporting, read-only variables. The no-export flag can be reset by unsetting the variable and creating it again – provided the variable is not also read-only.

`fc` [`-e` editor] [first [last]]
`fc` `-l` [`-nr`] [first [last]]
`fc` `-s` [old=new] [first]
`fc` `-z`

  The `fc` built-in lists, or edits and re-executes, commands previously entered to an interactive shell.

  `-e` editor
    Use the editor named by editor to edit the commands. The editor string is a command name, subject to search via the `PATH` variable. The value in the `FCEDIT` variable is used as a default when `-e` is not specified. If `FCEDIT` is null or unset, the value of the `EDITOR` variable is used. If `EDITOR` is null or unset, ed(1) is used as the editor.
  `-l` (ell)
    List the commands rather than invoking an editor on them. The commands are written in the sequence indicated by the first and last operands, as affected by `-r`, with each command preceded by the command number.
  `-n`
    Suppress command numbers when listing with `-l`.
  `-r`
    Reverse the order of the commands listed (with `-l`) or edited (with neither `-l` nor `-s`).
  `-s`
    Re-execute the command without invoking an editor.
  `-z`
    Clear the history buffer. No other options or arguments are permitted.
  first
  last
    Select the commands to list or edit. The number of previous commands that can be accessed are determined by the value of the `HISTSIZE` variable. The value of first or last or both are one of the following:
    [`+`]number
      A positive number representing a command number; command numbers can be displayed with the `-l` option.
    `-`number
      A negative decimal number representing the command that was executed number of commands previously. For example, -1 is the immediately previous command.
  string
    A string indicating the most recently entered command that begins with that string. If the old`=`new operand is not also specified with `-s`, the string form of the first operand cannot contain an embedded equal sign.

  The following environment variables affect the execution of `fc`:

  `FCEDIT`
    Name of the editor to use. If `FCEDIT` is not set, `EDITOR` is used, if set. If neither is used the `ed` utility is used.
  `HISTSIZE`
    The number of previous commands that are accessible.

`fg` [job]
  Move the specified job or the current job to the foreground. A foreground job can interact with the user via standard input, and receive signals from the terminal.

`fdflags` [`-v`] [fd ...]
`fdflags` [`-v`] `-s` flags fd [...]
  Get or set file descriptor flags. The `-v` argument enables verbose printing, printing flags that are also off, and the flags of the file descriptor being set after setting. The `-s` flag interprets the flags argument as a comma separated list of file descriptor flags, each preceded with a “+” or a “−” indicating to set or clear the respective flag. Valid flags are: `append`, `async`, `sync`, `nonblock`, `fsync`, `dsync`, `rsync`, `direct`, `nosigpipe`, and `cloexec`. Unique abbreviations of these names, of at least 2 characters, may be used on input. It is not permitted to set `cloexec` on file descriptors 0, 1, or 2 (standard input, standard output, and standard error). See fcntl(2) and open(2) for more information.

`getopts` optstring var
  The POSIX `getopts` command, not to be confused with the Bell Labs–derived getopt(1).

  The first argument should be a series of letters, each of which may be optionally followed by a colon (:) to indicate that the option requires an argument. The variable specified is set to the parsed option.

  The `getopts` command deprecates the older getopt(1) utility due to its handling of arguments containing whitespace.

  The `getopts` built-in may be used to obtain options and their arguments from a list of parameters. When invoked, `getopts` places the value of the next option from the option string in the list in the shell variable specified by var and its index in the shell variable `OPTIND`. When the shell is invoked, `OPTIND` is initialized to 1. For each option that requires an argument, the `getopts` built-in will place it in the shell variable `OPTARG`. If an option is not allowed for in the optstring, then `OPTARG` will be unset.

  optstring is a string of recognized option letters (see getopt(3)). If a letter is followed by a colon (:), the option is expected to have an argument which may or may not be separated from the option by whitespace. If an option character is not found where expected, `getopts` will set the variable var to ‘`?`’; `getopts` will then unset `OPTARG` and write an error to standard error.

  By specifying a colon (:) as the first character of optstring, the error handling behavior changes: no errors will be written to standard error; unknown option characters will set var to ‘`?`’ and set `OPTARG` to the unknown option character (instead of unset `OPTARG`); and missing option arguments will set var to ‘`:`’ and set `OPTARG` to the option character with the missing argument.

  A nonzero value is returned when the last option is reached. If there are no remaining arguments, `getopts` will set var to the special option, “`--`”, otherwise, it will set var to ‘`?`’.

  The following code fragment shows how one might process the arguments for a command that can take the options `-a` and `-b`, and the option `-c`, which requires an argument.

      while getopts abc: f
      do
      	case $f in
      	a | b)	flag=$f;;
      	c)	carg=$OPTARG;;
      	\?)	echo $USAGE; exit 1;;
      	esac
      done
      shift $((OPTIND - 1))

  This code will accept any of the following as equivalent:

      cmd -acarg file file
      cmd -a -c arg file file
      cmd -carg -a file file
      cmd -a -carg -- file file

`hash` [`-befqrsuv`] [command ...]
  The shell maintains a hash table which remembers the locations and types of commands. With the `-r` option given, the `hash` command begins by clearing all commands, except special built-in commands and functions, from this table. Commands, other than functions, are added to the table as described below, or as they are encountered through normal execution, or for functions, when they are defined. Functions are removed with the `unset` built-in command. Special built-in commands are added at shell startup, and never removed. Utilities can also be removed when `PATH` is altered.

  With no command arguments the `hash` command then prints out the contents of this table. Note that this is a hash table, the order of the contents is unpredictable, and meaningless.

  The `-b`, `-f`, `-s`, and `-u` options control which entries are printed. With `-f` functions are printed; with `-b` or `-s` regular, or special, built-in commands are listed; and with `-u` normal utilities (those commands found in the filesystem by searching `PATH`) are printed. For compatibility with some older versions of the `hash` command, `-c` is accepted as an alternative of `-u`.

  Some normal command entries which have not been verified since the last `cd` command are marked with an asterisk; it is possible for these entries to be invalid.

  The `-v` option causes more verbose output to be included, indicating the type of the command, rather than simply its name. For functions, the body of the function is included.

  If none of the above options is given, the default is to show normal commands only. With `-v` and no other options, the whole table (all types) will be shown.

  Unless there is an error writing the output, the `hash` command will exit with status 0 in this usage.

  With command arguments, the `hash` command removes the specified commands from the hash table (unless they are functions or special built-in commands) and then locates and reinstalls them. With the `-v` option, `hash` prints the locations of the commands as it finds them. The `-bfsu` options control which types of commands will be affected. If any of those options is given, and a command found to already be in the hash table is not one of the designated types, that entry, and the command argument, will simply be silently skipped. If none of those flags is given, any command type can be affected.

  If a command is not located, then unless `-q` was given, a “not found” error message will be printed.

  The `-e` option implies `-q` if that option was not given, and also causes the exit status of the `hash` command to ignore the unfound command. Otherwise if any command is not found, the `hash` command will exit with status 1.

  To allow a method to permit backwards compatibility with the way that the `hash` command worked before NetBSD 10.0, if both the `-e` and `-q` options are given, then an error message will be printed about commands unable to be found, but the exit status will remain 0. This is not considered useful.

`inputrc` file
  Read the file to set key bindings as defined by editrc(5).

`jobid` [`-g`|`-j`|`-p`] [job]
  With no flags, print the process identifiers of the processes in the job. If the job argument is omitted, the current job is used. Any of the ways to select a job may be used for job, including the ‘`%`’ forms, or the process id of the job leader (“`$!`” if the job was created in the background.)

  If one of the flags is given, then instead of the list of process identifiers, the `jobid` command prints:

  `-g`
    the process group, if one was created for this job, or nothing otherwise (the job is in the same process group as the shell.)
  `-j`
    the job identifier (using “`%`n” notation, where n is a number) is printed.
  `-p`
    only the process id of the process group leader is printed.

  These flags are mutually exclusive.

  `jobid` exits with status 2 if there is an argument error, status 1, if with `-g` the job had no separate process group, or with `-p` there is no process group leader (should not happen), and otherwise exits with status 0.

`jobs` [`-l`|`-p`] [job ...]
`jobs` `-Z` [title]
  Without job arguments, this command lists out all the background processes which are children of the current shell process. With job arguments, the listed jobs are shown instead. Without flags, the output contains the job identifier (see Job Control below), an indicator character if the job is the current or previous job, the current status of the job (running, suspended, or terminated successfully, unsuccessfully, or by a signal) and a (usually abbreviated) command string.

  With the `-l` flag the output is in a longer form, with the process identifiers of each process (run from the top level, as in a pipeline), and the status of each process, rather than the job status.

  With the `-p` flag, the output contains only the process identifier of the lead process (which is also the process group identifier). Note that this is not necessarily the same process identifier as reported in the special parameter `!` when a background job is started.

  With the `-Z` flag, the process command line is set using setproctitle(3). If title is omitted or a null string, setproctitle(3) is called with a `NULL` format.

  These options are mutually exclusive, the last specified is used.

  In an interactive shell, each job shown as completed in the output from the jobs command is implicitly waited for, and is removed from the jobs table, never to be seen again. In an interactive shell, when a background job terminates, the `jobs` command (with that job as an argument) is implicitly run just before outputting the next PS1 command prompt, after the job terminated. This indicates that the job finished, shows its status, and cleans up the job table entry for that job. Non-interactive shells need to execute `wait` commands to clean up terminated background jobs.

`local` [`-INx`] [variable | -] ...
  Define local variables for a function. Local variables have their attributes, and values, as they were before the `local` declaration, restored when the function terminates.

  With the `-N` flag, variables made local, are unset initially inside the function. Unless the `-x` flag is also given, such variables are also unexported. The `-I` flag, which is the default in this shell, causes the initial value and exported attribute of local variables to be inherited from the variable with the same name in the surrounding scope, if there is one. If there is not, the variable is initially unset, and not exported. The `-N` and `-I` flags are mutually exclusive, if both are given, the last specified applies. The read-only and unexportable attributes are always inherited, if a variable with the same name already exists.

  The `-x` flag (lower case) causes the local variable to be exported, while the function runs, unless it has the unexportable attribute. This can also be accomplished by using the `export` command, giving the same variable names, after the `local` command.

  Making an existing read-only variable local is possible, but pointless. If an attempt is made to assign an initial value to such a variable, the `local` command fails, as does any later attempted assignment. If the `readonly` command is applied to a variable that has been declared local, the variable cannot be (further) modified within the function, or any other functions it calls, however when the function returns, the previous status (and value) of the variable is returned.

  Values may be given to local variables on the `local` command line in a similar fashion as used for `export` and `readonly`. These values are assigned immediately after the initialization described above. Note that any variable references on the command line will have been expanded before `local` is executed, so expressions like

      local -N X="${X}"

  are well defined, first $X is expanded, and then the command run is

  `local -N X='old-value-of-X'`
  See the description of the `export` built-in command for notes on why quoting the value is required.

  After arranging to preserve the old value and attributes, of `X` (“old-value-of X”) `local` unsets `X`, unexports it, and then assigns the “old-value-of-X” to `X`.

  The shell uses dynamic scoping, so that if you make the variable `x` local to function `f`, which then calls function `g`, references to the variable `x` made inside `g` will refer to the variable `x` declared inside `f`, not to the global variable named `x`.

  Another way to view this, is as if the shell just has one flat, global, namespace, in which all variables exist. The `local` command conceptually copies the variable(s) named to unnamed temporary variables, and when the function ends, copies them back again. All references to the variables reference the same global variables, but while the function is active, after the `local` command has run, the values and attributes of the variables might be altered, and later, when the function completes, be restored.

  Note that the positional parameters `1`, `2`, ... (see Positional Parameters), and the special parameters `#`, `*` and `@` (see Special Parameters), are always made local in all functions, and are reset inside the function to represent the options and arguments passed to the function. Note that `$0` however retains the value it had outside the function, as do all the other special parameters.

  The only special parameter that can optionally be made local is “`-`”. Making “`-`” local causes any shell options that are changed via the set command inside the function to be restored to their original values when the function returns. If `-X` option is altered after “`-`” has been made local, then when the function returns, the previous destination for `xtrace` output (as of the time of the `local` command) will also be restored. If any of the shell's magic variables (those which return a value which may vary without the variable being explicitly altered, e.g.: `SECONDS` or `HOSTNAME`) are made local in a function, they will lose their special properties when set within the function, including by the `local` command itself (if not to be set in the function, there is little point in making a variable local) but those properties will be restored when the function returns.

  It is an error to use `local` outside the scope of a function definition. When used inside a function, it exits with status 0, unless an undefined option is used, or an attempt is made to assign a value to a read-only variable.

  Note that either `-I` or `-N` should always be used, or variables made local should always be given a value, or explicitly unset, as the default behavior (inheriting the earlier value, or starting unset after `local`) differs amongst shell implementations. Using “`local -`” is an extension not implemented by most shells.

  See the section Using `LINENO` below for details of the effects of making the variable `LINENO` local.

`pwd` [`-LP`]
  Print the current directory. If `-L` is specified the cached value (initially set from `PWD`) is checked to see if it refers to the current directory; if it does the value is printed. Otherwise the current directory name is found using getcwd(3).

  The default is `pwd` `-L`, but note that the built-in `cd` command doesn't support the `-L` option and will cache (almost) the absolute path. If `cd` is changed (as unlikely as that is), `pwd` may be changed to default to `pwd` `-P`.

  If the current directory is renamed and replaced by a symlink to the same directory, or the initial `PWD` value followed a symbolic link, then the cached value may not be the absolute path.

  The built-in command may differ from the program of the same name because the program will use `PWD` and the built-in uses a separately cached value.

`read` [`-br`] [`-d` delim] [`-n` max] [`-p` prompt] variable [...]

  The `read` command reads a record (by default one line) from its standard input, splits that record as if by field splitting, and assigns the results to the named variable arguments, as detailed below.

  The options are:

  `-b`
    Do buffered reads, rather than reading one byte at a time. This option is ignored if reading from a pipe. Use of this option might result in reading more bytes from standard input than the `read` utility actually processes, causing some data from standard input to be unavailable to any subsequent utility that expects to obtain them, though this will be avoided wherever possible.
  `-d` delim
    End the read when the first byte of delim is obtained from standard input. The default end delimiter is ⟨newline⟩ (‘\n’). Specifying "" as delim causes the nul character (‘\0’) to be the end delimiter. If the delimiter is set to ⟨backslash⟩ (‘\’) then neither line continuation nor escaping are available. The input will end when the first ⟨backslash⟩ is read.
  `-n` max
    `read` will read no more than max bytes from standard input. The default is unlimited. If the end delim has not been encountered within max bytes, and EOF has not been reached, `read` will act as if the delimiter immediately followed the max'th byte, without attempting to obtain it. However, even if the `-r` option is not given and the final byte actually read were the escape character (not itself escaped), no more bytes will be read, and that escape character would simply be removed as described below.
  `-p` prompt
    If the standard input is a terminal, then prompt is written to standard error before the read commences. If more lines of data are required in that case, the normal `PS2` prompt is written as each subsequent line is to be obtained.
  `-r`
    Reduced processing of the input. No escape characters are recognised, and line continuation is not performed. See below.

  If the read is from a terminal device, and the `-p` option was given, prompt is printed on standard error. Then a record, terminated by the first character of delim if the `-d` option was given, or a ⟨newline⟩ (‘\n’) character otherwise, but no longer than max bytes if the `-n` option was given, is read from the standard input. If the `-b` option is not given, no data from standard input beyond the end delimiter, or the max bytes that may be read, whichever occurs first, are obtained. Any nul characters (‘\0’) encountered in the input stream, other than when being the delimiter if `-d` "" was used, are simply ignored, even if escaped (in which case the preceding ‘\’ is also ignored) though these ignored characters are included in the byte count for the purposes of the `-n` option.

  If the `-r` option was not given, and the two character sequence ‘\’ ‘\n’ is encountered, those two characters are simply deleted, and provided that max bytes have not yet been obtained, and the end delimiter has yet to be encountered, more input is obtained, with the first character of the following line placed in the input where the deleted ‘\’ had been. This allows logical lines longer than the maximum line length permitted for text files to be processed. The two removed characters are still counted for the purposes of the max input limit.

  If the `-r` flag was not given, the ⟨backslash⟩ character (‘\’) character is then treated as an escape character, the character following it, if not ‘\0’, is always treated as a normal, insignificant, data character, and is never treated as the end delimiter nor as an IFS character for field splitting.

  After field splitting has completed, but before data has been assigned to any variables, all escape characters are removed. Note that the two character sequence ‘\’ ‘\’ can be used to enter the escape character as data, the first acts as the escape character, the second becomes just a normal data character.

  The ending delimiter, if encountered, and not escaped, is deleted from the record which is then split as described in the field splitting section of the Word Expansions section above. The pieces (fields) are assigned to the variables in order. If there are more pieces than variables, the remaining pieces (along with the characters in `IFS` that separated them) are all assigned to the last variable. If there are more variables than pieces, the remaining variables are assigned the null string.

  The `read` built-in utility will indicate success (exit status 0) unless EOF, or a read error, is encountered on input, before encountering the delimiter, or having read max bytes. In this case any data previously read will be assigned to the variables, as if the delimiter had been located at that point, and `read` will exit with status 1. If there is a usage error (unknown option, etc) no variables will be altered, `read` will issue a diagnostic to standard error, and exit with a status greater than 1.

  The `-b` and `-n` options are not available in SMALL shells.

`readonly` name[=value] ...
`readonly` [`-p` [name ...]]
`readonly` `-q` name ...
  With no options, the specified names are marked as read only, so that they cannot be subsequently modified or unset. The shell allows the value of a variable to be set at the same time it is marked read only by writing

  `readonly name=value`

  where the value often needs to be quoted, as explained for the `export` command.

  With no arguments the `readonly` command lists the names of all set read only variables. With the `-p` option specified, the output will be formatted suitably for non-interactive use, and unset variables are included. When the `-p` option is given, a list of variable names (without values) may also be specified, in which case output is limited to the named variables.

  With the `-q` option, the `readonly` command tests the read-only status of the variables listed and exits with status 0 if all named variables are read-only, or with status 1 if any are not read-only.

  Other than as specified for `-q` the `readonly` command normally exits with status 0. In all cases, if an unknown option, or an invalid option combination, or an invalid variable name, is given; or a variable which was already read-only is attempted to be set; the exit status will not be zero, a diagnostic message will be written to the standard error output, and a non-interactive shell will terminate.

`return` [n]
  Stop executing the current function or a dot command with return value of n or the value of the last executed command, if not specified. For portability, n should be in the range from 0 to 255.

  The POSIX standard says that the results of `return` outside a function or a dot command are unspecified. This implementation treats such a return as a no-op with a return value of 0 (success, true). Use the `exit` command instead, if you want to return from a script or exit your shell.

`set`
`set` { `-o` | `+o` }
`set` { `-options` | `+options` | `-o` opt | `+o` opt } ... [`--`] [arg ...]
`set --` [arg ...]

  The `set` command performs four different functions.

  With no arguments, `set` lists the names and values of all set shell variables.

  With a single option of either “`-o`” or “`+o`” `set` outputs the current values of the options. In the `-o` form, all options are listed, with their current values. In the `+o` form, the shell outputs a string that can later be used as a command to reset all options to their current values.

  If options are given, `sh` sets the specified option flags, or clears them as described in the Argument List Processing section. Note that not all options available on the command line are available to the `set` built-in command. However, in addition to the options listed there, when the “option name” (opt) given to `set` `-o` is `default` all of the options are reset to the values they had immediately after `sh` initialization, before any startup scripts, or other input, had been processed. While this may be of use to users or scripts, its primary purpose is for use in the output of “`set` `+o`”, to avoid that command needing to list every available option. There is no `+o default`.

  The fourth use of the `set` command is to set the values of the shell's positional parameters to the specified arguments. To change the positional parameters with no possibility of changing any options, use “--” as the first argument to `set`. If no following args are present, the `set` command will clear all the positional parameters (equivalent to executing “`shift $#`”.) Otherwise the following args become `$1`, `$2`, ..., and `$#` is set to the number of args present. The third and fourth forms may be combined, to set options, and the positional parameters, in one operation. Note that if it is possible that no arguments might be present, or if the first arg might begin with a minus (‘-’) then the “--” is required to distinguish this case from the first and third variants of this command, and an arg beginning with ‘-’ from being an attempt to set options.

`setvar` variable value
  Assigns value to variable. (In general it is better to write `variable=value` rather than using `setvar`. `setvar` is intended to be used in functions that assign values to variables whose names are passed as parameters.)

`shift` [n]
  If n, which must be a decimal integer, is omitted, 1 is assumed.

  If n is unsigned (or omitted) shift the positional parameters n times. Each `shift` sets the value of `$1` to the previous value of `$2`, the value of `$2` to the previous value of `$3`, and so on, decreasing the value of `$#` by one. The shift count (n) must be less than or equal to the number of positional parameters (“`$#`”) before the shift. A shift of `$#` positions is equivalent to “`set` `-``-`” and results in unsetting all of the positional parameters and setting `$#` to zero. The command “`shift 0`” does not alter `$#` or any of the positional parameters.

  If n is negative, then the `shift` becomes a clockwise rotation, -n times. The absolute value of n must be less than or equal to `$#` (the number of set positional parameters). Each rotation sets the value of `$1` to the previous value of `${$#}` (if that were valid syntax) – the previous last positional parameter, sets `$2` to the previous value of `$1`, the value of `$3` to the previous value of `$2`, and so on, with the new last positional parameter becoming what was previously the penultimate positional parameter. The value of `$#` is not altered. Shifts of `-0` and `-$#` are no-ops. The command sequence:

  `shift -n; shift n`
  unsets the final n positional parameters.

  An anti-clockwise rotation of n places (0 <= n <= $#) can be achieved using “`shift -$(($# - n))`”. The command “`shift -$(($# - 1))`” is equivalent to, but much faster than:

  `set `--` “$@” “$1”; shift 1`

  The exit status is 0 if no error occurs, otherwise greater than 0.

`specialvar` variable ...
  For each variable name given, if the variable named is one which, in this `sh`, could be treated as a special variable, then cause that variable to be made special, undoing any effects of an earlier `unset` or assignment to the variable. If all variables given are recognized special variables in this `sh` the `specialvar` command will exit with status 0, otherwise 1. Invalid usage will result in an exit status of 2.

  Note that all variables capable of being special are created that way, this command is not required to cause that to happen. However should such a variable be imported from the environment, that will cause (for those special variables so designated) the special effects for that variable to be lost. Consequently, as the contents of the environment cannot be controlled, any script which desires to make use of the properties of most of the special variables should use this command, naming the variables required, to ensure that their special properties are available.

`suspend` [`-fg`] [`-s` sig] [pid|job ...]
  Causes the processes or jobs indicated to be suspended, if possible. If no pid or job arguments are given, or if a pid argument refers to the shell itself, and if the `suspend` command is issued in a shell that is not a login shell, has job control enabled, and is not executing in a subshell environment, then the shell will suspend itself. The `-f` (force) option causes those checks to be ignored, the shell, when instructed to suspend itself with force, will always attempt to do so, which may result in a subshell environment becoming suspended.

  The `-g` option indicates that each pid argument is to be treated as a process group identifier, or if no targets are given, the current process group of the shell, and that process group will be suspended, instead of just the process identified. This option is implied, for the one argument only, by use of a job specifier. Note that, unlike other built-in commands, use of a pid argument causes only that process to be suspended, even if that pid happens to be the process leader of a job, or another process in a job.

  The `-s` sig option cause the signal sig to be used to suspend the process, or process group. Only the signals that, by default, cause processes to be suspended (`STOP` `TSTP` `TTIN` and `TTOU`) are permitted. The default is `SIGTSTP`. Note that except when `SIGSTOP` is sent, the target process can arrange to catch or ignore the signal, and perhaps not become suspended, if it so desires. Interactive processes that support job control (eg: shells) generally ignore those signals.

  The `suspend` command exits with status 0, except if an error occurs, in which case it exits with a status greater than 0. Possible errors include usage errors; attempting to suspend the shell itself, when not permitted and without the `-f` option; a target process or job not existing; insufficient privileges to signal the target process or job; and more. It is not an error if the target process decides not to comply with a request to suspend itself.

`times`
  Prints two lines to standard output. Each line contains two accumulated time values, expressed in minutes and seconds (including fractions of a second.) The first value gives the user time consumed, the second the system time.

  The first output line gives the CPU and system times consumed by the shell itself. The second line gives the accumulated times for children of this shell (and their descendants) which have exited, and then been successfully waited for by the relevant parent. See times(3) for more information.

  `times` has no parameters, and exits with an exit status of 0 unless an attempt is made to give it an option.

`trap` action signal ...
`trap -`
`trap` [`-l`]
`trap` `-p` [signal ...]
`trap` `-P` signal ...
`trap` N signal ...

  Cause the shell to parse and execute action when any of the specified signals are received. The signals are specified by signal number or as the name of the signal. If signal is `0` or its equivalent, `EXIT`, the action is executed when the shell exits. The action may be a null (empty) string, which causes the specified signals to be ignored. With action set to ‘`-`’ the specified signals are set to their default actions. If the first signal is specified in its numeric form, then action can be omitted to achieve the same effect. This archaic, but still standard, form should not be relied upon, use the explicit ‘`-`’ action. If no signals are specified with an action of ‘`-`’, all signals are reset.

  When the shell forks off a sub-shell, it resets trapped (but not ignored) signals to the default action. On non-interactive shells, the `trap` command has no effect on signals that were ignored on entry to the shell. On interactive shells, the `trap` command will catch or reset signals ignored on entry.

  Issuing `trap` with option `-l` will print a list of valid signal names. `trap` without any arguments causes it to write a list of signals and their associated non-default actions to the standard output in a format that is suitable as an input to the shell that achieves the same trapping results. With the `-p` flag, trap prints the same information for the signals specified, or if none are given, for all signals, including those where the action is the default. The `-P` flag is similar, but prints only the action(s) associated with the named signals, at least (and usually only) one of which must be given. Nothing is printed if the action is the default, an empty line is printed for ignored signals. These variants of the trap command may be executed in a sub-shell (such as in a command substitution), provided they appear as the initial sequence of commands in that sub-shell, in which case the state of traps from the parent of that sub-shell is reported.

  Examples:

  `trap`

  List trapped signals and their corresponding actions.

  `trap -l`

  Print a list of valid signals.

  `trap '' INT QUIT tstp 30`

  Ignore signals INT QUIT TSTP USR1.

  `trap date INT`

  Run the “date” command (print the date) upon receiving signal INT.

  `trap HUP INT`

  Run the “HUP” command, or function, upon receiving signal INT.

  ``eval` "$( trap -P QUIT )"`

  Parse and execute the action that would be invoked were a `SIGQUIT` received.

  `trap 1 2`

  Reset the actions for signals 1 (HUP) and 2 (INT) to their defaults.

      traps=$(trap -p)
         # more commands ...
      trap 'action' SIG
         # more commands ...
      eval "$traps"

  Save the trap status, execute commands, changing some traps, and then reset all traps to their values at the start of the sequence. The `-p` option is required in the first command here, or any signals that were previously untrapped (in their default states) and which were altered during the intermediate code, would not be reset by the final `eval`.

`type` [name ...]
  Interpret each name as a command and print the resolution of the command search. Possible resolutions are: shell keyword, alias, shell built-in, command, tracked alias and not found. For aliases the alias expansion is printed; for commands and tracked aliases the complete pathname of the command is printed.

`ulimit` [`-H`|`-S`] [`-a` | `-btfdscmlrpnv` [value]]
  Inquire about or set the hard or soft limits on processes or set new limits. The choice between hard limit (which no process is allowed to violate, and which may not be raised once it has been lowered) and soft limit (which causes processes to be signaled but not necessarily killed, and which may be raised) is made with these flags:
  `-H`
    set or inquire about hard limits
  `-S`
    set or inquire about soft limits.

  If neither `-H` nor `-S` is specified, the soft limit is displayed or both limits are set. If both are specified, then with `-a` both are displayed, the soft followed by the hard limit, otherwise for setting, both limits are set, and for interrogating the soft limit is displayed.

  The limit to be interrogated or set, then, is chosen by specifying any one of these flags:

  `-a`
    show all the current limits (it is an error to attempt to set the limits by giving a value)
  `-b`
    the socket buffer size of a process (bytes)
  `-c`
    the largest core dump size that can be produced (512-byte blocks)
  `-d`
    the data segment size of a process (kilobytes)
  `-f`
    the largest file that can be created (512-byte blocks)
  `-l`
    how much memory a process can lock with mlock(2) (kilobytes)
  `-m`
    the total physical memory that can be in use by a process (kilobytes)
  `-n`
    the number of files a process can have open at once
  `-p`
    the number of processes this user can have at one time
  `-r`
    the number of threads this user can have at one time
  `-s`
    the stack size of a process (kilobytes)
  `-t`
    CPU time (seconds)
  `-v`
    how large a process address space can be

  If none of these is specified, it is the limit on file size that is shown or set. If value is specified, the limit is set to that number; otherwise the current limit is displayed.

  Limits of an arbitrary process can be displayed or set using the sysctl(8) utility.

`umask` [`-S`] [mask]
  Set the value of umask (see umask(2)) to the specified octal value. If the argument is omitted, the umask value is printed. With `-S` a symbolic form is used instead of an octal number.

`unalias` [`-a`] [name]
  If name is specified, the shell removes that alias. If `-a` is specified, all aliases are removed.

`unset` [`-efvx`] name ...
  If `-v` is specified, the specified variables are unset and unexported. Readonly variables cannot be unset. If `-f` is specified, the specified functions are undefined. If `-e` is given, the specified variables are unexported, but otherwise unchanged, alternatively, if `-x` is given, the exported status of the variable will be retained, even after it is unset.

  If no flags are provided `-v` is assumed. If `-f` is given with one of the other flags, then the named variables will be unset, or unexported, and functions of the same names will be undefined. The `-e` and `-x` flags both imply `-v`. If `-e` is given, the `-x` flag is ignored.

  The exit status is 0, unless an attempt was made to unset a readonly variable, in which case the exit status is 1. It is not an error to unset (or undefine) a variable (or function) that is not currently set (or defined.)

`wait` [`-n`] [`-p` var] [job ...]
  Wait for the specified jobs to complete and return the exit status of the last job in the parameter list, or 127 if that job is not a current child of the shell.

  If no job arguments are given, wait for all jobs to complete and then return an exit status of zero (including when there were no jobs, and so nothing exited.)

  With the `-n` option, wait instead for any one of the given jobs, or if none are given, any job, to complete, and return the exit status of that job. If none of the given job arguments is a current child of the shell, or if no job arguments are given and the shell has no unwaited for children, then the exit status will be 127.

  The `-p` var option allows the process (or job) identifier of the job for which the exit status is returned to be obtained. The variable named (which must not be readonly) will be unset initially, then if a job has exited and its status is being returned, set to the identifier from the arg list (if given) of that job, or the lead process identifier of the job to exit when used with `-n` and no job arguments. Note that `-p` with neither `-n` nor job arguments is useless, as in that case no job status is returned, the variable named is simply unset.

  If the wait is interrupted by a signal, its exit status will be greater than 128, and var, if given, will remain unset.

  Once waited upon, by specific process number or job-id, or by a `wait` with no arguments, knowledge of the child is removed from the system, and it cannot be waited upon again.

  Note than when a list of jobs are given, more that one argument might refer to the same job. In that case, if the final argument represents a job that is also given earlier in the list, it is not defined whether the status returned will be the exit status of the job, or 127 indicating that the child no longer existed when the wait command reached the later argument in the list. In this `sh` the exit status will be that from the job. `sh` waits for each job exactly once, regardless of how many times (or how many different ways) it is listed in the arguments to `wait`. That is

      wait 100 100 100

  is identical to

      wait 100

## Job Control

Each process (or set of processes) started by `sh` is created as a “job” and added to the jobs table. When enabled by the `-m` option (aka `-o` `monitor`) when the job is created, `sh` places each job (if run from the top level shell) into a process group of its own, which allows control of the process(es), and its/their descendants, as a unit. When the `-m` option is off, or when started from a sub-shell environment, jobs share the same process group as the parent shell. The `-m` option is enabled by default in interactive shells with a terminal as standard input and standard error.

Jobs with separate process groups may be stopped, and then later resumed in the foreground (with access to the terminal) or in the background (where attempting to read from the terminal will result in the job stopping.) A list of current jobs can be obtained using the `jobs` built-in command. Jobs are identified using either the process identifier of the lead process of the job (the value available in the special parameter “`!`” if the job is started in the background), or using percent notation. Each job is given a “job number” which is a small integer, starting from 1, and can be referenced as “`%`n” where n is that number. Note that this applies to jobs both with and without their own process groups. Job numbers are shown in the output from the `jobs` command enclosed in brackets (‘`[`’ and ‘`]`’). Whenever the job table becomes empty, the numbers begin at one again. In addition, there is the concept of a current, and a previous job, identified by “`%+`” (or “`%%`” or even just “`%`”), and a previous job, identified by “`%-`”. Whenever a background job is started, or a job is resumed in the background, it becomes the current job. The job that was the current job (prepare for a big surprise here, drum roll..., wait for it...) becomes the previous job. When the current job terminates, the previous job is promoted to be the current job. In addition the form “`%`string” finds the job for which the command starts with string and the form “`%?`string” finds the job which contains the string in its command somewhere. Both forms require the result to be unambiguous. For this purpose the “command” is that shown in the output from the `jobs` command, not the original command line.

The `bg`, `fg`, `jobid`, `jobs`, `kill`, `suspend`, and `wait` commands all accept job identifiers as arguments, in addition to process identifiers (larger integers). See the Built-ins section above, and kill(1), for more details of those commands. In addition, a job identifier (using one of the “% forms”) issued as a command, without arguments, is interpreted as if it had been given as the argument to the `fg` command.

To cause a foreground process to stop, enter the terminal's `stop` character (usually control-Z). To cause a background process to stop, use the `suspend` built in command, or send it a `STOP` signal, using the kill command. A useful function to define is

    stop() { kill -s STOP "${@:-%%}"; }

The `fg` command resumes a stopped job, placing it in the foreground, and `bg` resumes a stopped job in the background. The `jobid` command provides information about process identifiers, job identifiers, and the process group identifier, for a job.

Whenever a sub-shell is created, the jobs table becomes invalid (the sub-shell has no children.) However, to enable uses like

    PID=$(jobid -p %1)

the table is only actually cleared in a sub-shell when needed to create the first job there (built-in commands run in the foreground do not create jobs.) Note that in this environment, there is no useful current job (“`%%`” actually refers to the sub-shell itself, but is not accessible) but the job which is the current job in the parent can be accessed as “`%-`”.

## Command Line Editing

When `sh` is being used interactively from a terminal, the current command and the command history (see `fc` in the Built-ins section) can be edited using emacs-mode or vi-mode command-line editing. The command ‘`set -o emacs`’ (or `-E` option) enables emacs-mode editing. The command ‘`set -o vi`’ (or `-V` option) enables vi-mode editing and places the current shell process into vi insert mode. (See the Argument List Processing section above.)

The vi-mode uses commands similar to a subset of those described in the vi(1) man page. With vi-mode enabled, `sh` can be switched between insert mode and command mode. It's similar to `vi`: pressing the ⟨ESC⟩ key will throw you into vi command mode. Insert mode is re-entered in any of the usual vi ways, using the append (a) insert (i) substitute (s) (etc) commands. Pressing the ⟨return⟩ key in either mode will pass the line to the shell.

The emacs-mode uses commands similar to a subset available in the `emacs` editor. With emacs-mode enabled, special keys can be used to modify the text in the buffer using the control key.

`sh` uses the editline(3) library. See editline(7) for a list of the possible command bindings, and the default settings in emacs and vi modes. Also see editrc(5) for the commands that can be given to configure editline(7) in the file named by the `EDITRC` parameter, or a file used with the `inputrc` built-in command, or using editline(7)'s configuration command line.

When command line editing is enabled, the editline(7) functions control printing of the `PS1` and `PS2` prompts when required. As, in this mode, the command line editor needs to keep track of what characters are in what position on the command line, care needs to be taken when setting the prompts. Normal printing characters are handled automatically, however mode setting sequences, which do not actually display on the terminal, need to be identified to editline(7). This is done, when needed, by choosing a character that is not needed anywhere in the prompt, including in the mode setting sequences, any single character is acceptable, and assigning it to the shell parameter `PSlit`. Then that character should be used, in pairs, in the prompt string. Between each pair of `PSlit` characters are mode setting sequences, which affect the printing attributes of the following (normal) characters of the prompt, but do not themselves appear visibly, nor change the terminal's cursor position.

Each such sequence, that is `PSlit` character, mode setting character sequence, and another `PSlit` character, must currently be followed by at least one following normal prompt character, or it will be ignored. That is, a `PSlit` character cannot be the final character of `PS1` or `PS2`, nor may two `PSlit` delimited sequences appear adjacent to each other. Each sequence can contain as many mode altering sequences as are required however. Only the first character from `PSlit` will be used. When set `PSlit` should usually be set to a string containing just one character, then it can simply be embedded in `PS1` (or `PS2`) as in

`PS1="${PSlit}`mset`${PSlit}XYZ${PSlit}`mclr`${PSlit}ABC"`

The prompt visible will be “XYZABC” with the “XYZ” part shown according as defined by the mode setting characters mset, and then cleared again by mclr. See tput(1) for one method to generate appropriate mode sequences. Note that both parts, XYZ and ABC, must each contain at least one character.

If `PSlit` is unset, which is its initial state, or set to a null string, no literal character will be defined, and all characters of the prompt strings will be assumed to be visible characters (which includes spaces etc.) To allow smooth use of prompts, without needing redefinition, when editline(7) is disabled, the character chosen should be one which will be ignored by the terminal if received, as when editline(7) is not in use, the prompt strings are simply written to the terminal. For example, setting:

      PSlit="$(printf '\1')"
      PS1="${PSlit}$(tput bold blink)${PSlit}\$${PSlit}$(tput sgr0)${PSlit} "

will arrange for the primary prompt to be a bold blinking dollar sign, if supported by the current terminal, followed by an (ordinary) space, and, as the SOH (control-A) character (‘\1’) will not normally affect a terminal, this same prompt will usually work with editline(7) enabled or disabled.

# ENVIRONMENT

`CDPATH`
  The search path used with the `cd` built-in.
`EDITRC`
  Gives the name of the file containing commands for editline(7). See editrc(5) for possible content and format. The file is processed, when in interactive mode with command line editing enabled, whenever `EDITRC` is set (even with no actual value change,) and if command line editing changes from disabled to enabled, or the editor style used is changed. (See the `-E` and `-V` options of the `set` built-in command, described in Built-ins above, which are documented further above in Argument List Processing.) If unset “$HOME/.editrc” is used.
`ENV`
  Names the file sourced at startup by the shell. Unused by this shell after initialization, but is usually passed through the environment to descendant shells. See the Invocation section above for details of how `ENV` is processed and used.
`EUSER`
  Set to the login name of the effective user id running the shell, as returned by

      getpwuid(geteuid())->pw_name

  (See getpwuid(3) and geteuid(2) for more details.) This is obtained each time `EUSER` is expanded, so changes to the shell's execution identity cause updates without further action. If unset, it returns nothing. If set it loses its special properties, and is simply a variable. See the `specialvar` built-in command for remedial action.
`HISTAPPEND`
  If set to one of ‘`true`’, ‘`yes`’, ‘`on`’, or an integral value greater than zero, and if `HISTFILE` is also set, and is a valid history file, then as commands are read and added to the history buffer, they are also written to the `HISTFILE` named.
`HISTFILE`
  When assigned to in an interactive shell the contents of the file named by expanding the new value of `HISTFILE` will, if it exists, can be opened for reading, and is a suitable `sh` history file (one previously written by `sh`), be read into the history buffer, appending its contents to any existing history entries. If `HISTFILE` is set when `sh` exits, after any EXIT trap has been evaluated, and if `HISTAPPEND` is not enabled, or if `HISTFILE` is assigned when HISTAPPEND is enabled, or if `HISTAPPEND` is enabled when `HISTFILE` is set, the contents of the history buffer will be written to the file named after expanding this variable. If the file named did not previously exist, it will be created. If it did exist, it must be writable. The file will be truncated, and then if owned by the current user, the current history buffer will be written to it.

  When used for reading or writing history entries, variable and arithmetic expansions are performed, upon its value to produce a file name, and if the `HISTFILE` variable was set by this shell, rather than obtained from the environment, command substitutions will also be performed. No file will be used if an expansion error occurs, or if there is a command substitution in a value obtained from the environment.

`HISTSIZE`
  The number of lines in the history buffer for the shell. If unset, or set to an empty string, 100 lines will be used. Attempts to set HISTSIZE to anything other than a string of digits will generate an error. An invalid value found in the environment will be ignored.
`HOME`
  Set automatically by login(1) from the user's login directory in the password file (passwd(5)). This environment variable also functions as the default argument for the `cd` built-in, and as the value of a tilde expansion without a user name.
`HOSTNAME`
  Set to the current hostname of the system, as returned by gethostname(3). This is obtained each time `HOSTNAME` is expanded, so changes to the system's name are reflected without further action. If unset, it returns nothing. If set it loses its special properties, and is simply a variable. See the `specialvar` built-in command for remedial action.
`IFS`
  Input Field Separators. This is normally set to ⟨space⟩, ⟨tab⟩, and ⟨newline⟩. See the Field Splitting section for more details.
`LANG`
  The string used to specify localization information that allows users to work with different culture-specific and language conventions. See nls(7).
`LINENO`
  The current line number in the script or function. See the section Using `LINENO` below for more details.
`MAIL`
  The name of a mail file, that will be checked for the arrival of new mail. Overridden by `MAILPATH`. The check occurs just before `PS1` is written, immediately after reporting jobs which have changed status, in interactive shells only. New mail is considered to have arrived if the monitored file has increased in size since the last check.
`MAILPATH`
  A colon “:” separated list of file names, for the shell to check for incoming mail. This environment setting overrides the `MAIL` setting. There is a maximum of 10 mailboxes that can be monitored at once.
`NBSH_INVOCATION`
  When `sh` starts, after it has processed its arguments, and imported variables from the environment, this variable is set to a string of one or more characters which indicate the way the command line was processed. This is intended to be used in the startup scripts (see Invocation) to allow them to determine what actions are appropriate to take. `NBSH_INVOCATION` is marked “not to be exported”. Apart from the way it is initialized, and that it overrides any value that may have been set in the environment, there is nothing special about it. It can be unset, or altered, with no ramifications, other than whatever effect this might have on its use in the startup scripts.

  When the value of this variable remains as set at startup by `sh` the following characters may appear in the value, in the circumstances described. Any present will always appear in ASCII lexical order, as they appear below (to make testing the value easier to code).

  !
    Always present when set by `sh`, and is always first. No specific meaning is attributed to this character.
  -
    Set when the first character of argv[0] as set when the shell was invoked was a dash (‘-’).
  0
    Set when at startup, the special parameter `$#` has the value 0. That is, no arguments were given to the script in the case that there is a script.
  c
    The `-c` option was given on the command line.
  f
    Neither the `-c` nor `-s` options were present on the command line, but there is at least one non-option argument, which will then be interpreted as the name of the command_file to process.
  i
    The shell is interactive. At startup this indicates that ‘i’ will appear in the value of the special parameter $-. However, the special parameter will alter as the `-i` option is manipulated by the `set` built-in command, but `NBSH_INVOCATION` is never subsequently altered by the shell itself (unless manipulated by a regular variable operations).
  l
    The shell is a login shell. As with ‘i’ (the same operational conditions apply) this character will be present if the ‘l’ is present in $- when the shell is starting. Note that if ‘l’ is present, and ‘-’ is not, then the shell was invoked with the `-l` option on the command line (or the equivalent `-o` login). On the other hand, if ‘-’ appears, and ‘l’ does not, then the shell was invoked with the `+l` option (or its equivalent) on the command line. If both ‘-’ and ‘l’ appear, then the shell is a normal login shell, the `-l` option might have been given, but had no effect. If neither ‘-’ nor ‘l’ appear, then the shell is not a login shell, and was never intended to be. The `+l` option might have been given, but had no effect.
  p
    The shell was started as a privileged (set user id) process. This indicates that the `-p` option must have been given on the command line, or privileges would have been dropped.
  s
    The shell will read commands from standard input. The `-s` option was given, or implied. This does not imply that the shell is interactive.
`PATH`
  The default search path for executables. See the Path Search section above.
`POSIXLY_CORRECT`
  If set in the environment upon initialization of the shell, then the shell option `posix` will be set. (See the description of the `set` command in the Built-ins section.) After initialization it is unused by the shell, but is usually passed through the environment to descendant processes, including other instances of the shell, which may interpret it in a similar way.
`PPID`
  The process identified of the parent process of the current shell. This value is set at shell startup, ignoring any value in the environment, and then made readonly.
`PS1`
  The primary prompt string, which defaults to “`$` ”, unless you are the superuser, in which case it defaults to “`#` ”. This string is subject to parameter, arithmetic, and if enabled by setting the `promptcmds` option, command substitution before being output. During execution of commands used by command substitution, execution tracing, the `xtrace` (`set` `-x`) option is temporarily disabled. If `promptcmds` is not set and the prompt string uses command substitution, the prompt used will be an appropriate error string. For other expansion errors, the prompt will become an empty string, without an error message. To verify parsing of `PS1`, the method suggested for `ENV` can be used.
`PS2`
  The secondary prompt string, which defaults to “`>` ”. After expansion (as for `PS1`) it is written whenever more input is required to complete the current command.
`PS4`
  is output, after expansion as described for `PS1`, as a prefix for each line when execution trace (`set` `-x`) is enabled. `PS4` defaults to “`+` ”.
`PSc`
  Initialized by the shell, ignoring any value from the environment, to a single character string, either ‘#’ or ‘$’, depending upon whether the current user is the superuser or not. This is intended for use when building a custom `PS1`. If a privileged shell has its privileges removed by clearing the `-p` option, an attempt will be made to be reset `PSc` to “#” or “$”, as appropriate for its new privilege level.
`PSlit`
  Defines the character which may be embedded in pairs, in `PS1` or `PS2` to indicate to editline(7) that the characters between each pair of occurrences of the `PSlit` character will not appear in the visible prompt, and will not cause the terminal's cursor to change position, but rather set terminal attributes for the following prompt character(s) at least one of which must be present. See Command Line Editing above for more information.
`RANDOM`
  Returns a different pseudo-random integer, in the range [0,32767] each time it is accessed. `RANDOM` can be assigned an integer value to seed the PRNG. If the value assigned is a constant, then the sequence of values produces on subsequent references of `RANDOM` will repeat after the next time the same constant is assigned. Note, this is not guaranteed to remain constant from one version of the shell to another – the PRNG algorithm, or seeding method is subject to change. If `RANDOM` is assigned an empty value (null string) then the next time `RANDOM` is accessed, it will be seeded from a more genuinely random source. The sequence of pseudo-random numbers generated will not be able to be generated again (except by luck, whether good or bad, depends!) This is also how the initial seed is generated, if none has been assigned before `RANDOM` is first accessed after shell initialization. Should the error message “RANDOM initialisation failed” appear on standard error, it indicates that the source of good random numbers was not available, and `RANDOM` has instead been seeded with a more predictable value. The following sequence of random numbers will not be as unpredictable as they otherwise would be.
`SECONDS`
  Returns the number of seconds since the current shell was started. If unset, it remains unset, and returns nothing, unless set again. If set, it loses its special properties, and becomes a normal variable. See the `specialvar` built-in command for remedial action.
`START_TIME`
  Initialized by the shell to the number of seconds since the Epoch (see localtime(3)) when the shell was started. The value of
  `$((`START_TIME +` `SECONDS`))`
  represents the current time, if `START_TIME` has not been modified, and `SECONDS` has not been set or unset.
`TERM`
  The default terminal setting for the shell. This is inherited by children of the shell, and is used in the history editing modes.
`ToD`
  When referenced, uses the value of `ToD_FORMAT` (or “%T” if `ToD_FORMAT` is unset) as the format argument to strftime(3) to encode the current time of day, in the time zone defined by `TZ` if set, or current local time if not, and returns the result. If unset `ToD` returns nothing. If set, it loses its special properties, and becomes a normal variable. See the `specialvar` built-in command for remedial action.
`ToD_FORMAT`
  Can be set to the strftime(3) format string to be used when expanding `ToD`. Initially unset.
`TZ`
  If set, gives the time zone (see localtime(3), environ(7)) to use when formatting `ToD` and if exported, other utilities that deal with times. If unset, the system's local wall clock time zone is used.
`NETBSD_SHELL`
  Unlike the variables previously mentioned, this variable is somewhat strange, in that it cannot be set, inherited from the environment, modified, or exported from the shell. If set, by the shell, it indicates that the shell is the `sh` defined by this manual page, and gives its version information. It can also give information in additional space separated words, after the version string. If the shell was built as part of a reproducible build, the relevant date that was used for that build will be included. Finally, any non-standard compilation options, which may affect features available, that were used when building the shell will be listed. `NETBSD_SHELL` behaves like any other variable that has the read-only and un-exportable attributes set.

## Using `LINENO`

`LINENO` is in many respects a normal shell variable, containing an integer value, and can be expanded using any of the forms mentioned above which can be used for any other variable.

`LINENO` can be exported, made readonly, or unset, as with any other variable, with similar effects. Note that while being readonly prevents later attempts to set, or unset, `LINENO`, it does not prevent its value changing. References to `LINENO` (when not unset) always obtain the current line number. However, `LINENO` should normally not ever be set or unset. In this shell setting `LINENO` reverses the effect of an earlier `unset`, but does not otherwise affect the value obtained. If unset, `LINENO` should not normally be set again, doing so is not portable. If `LINENO` is set or unset, different shells act differently. The value of `LINENO` is never imported from the environment when the shell is started, though if present there, as with any other variable, `LINENO` will be exported by this shell.

`LINENO` is set automatically by the shell to be the number of the source line on which it occurs. When exported, `LINENO` is exported with its value set to the line number it would have had had it been referenced on the command line of the command to which it is exported. Line numbers are counted from 1, which is the first line the shell reads from any particular file. For this shell, standard input, including in an interactive shell, the user's terminal, is just another file and lines are counted there as well. However note that not all shells count interactive lines this way, it is not wise to rely upon `LINENO` having a useful value, except in a script, or a function.

The role of `LINENO` in functions is less clear. In some shells, `LINENO` continues to refer to the line number in the script which defines the function, in others lines count from one within the function, always (and resume counting normally once the function definition is complete) and others count in functions from one if the function is defined interactively, but otherwise just reference the line number in the script in which the function is defined. This shell gives the user the option to choose. If the `-L` flag (the `local_lineno` option, see Argument List Processing) is set, when the function is defined, then the function defaults to counting lines with one being the first line of the function. When the `-L` flag is not set, the shell counts lines in a function definition in the same continuous sequence as the lines that surround the function definition. Further, if `LINENO` is made local (see Built-ins above) inside the function, the function can decide which behavior it prefers. If `LINENO` is made local and inherited, and not given a value, as in

`local `-I` `LINENO``
then from that point in the function, `LINENO` will give the line number as if lines are counted in sequence with the lines that surround the function definition (and any other function definitions in which this is nested.) If `LINENO` is made local, and in that same command, given a value, as
`local [`-I`|`-N`] `LINENO`=value`
then `LINENO` will give the line number as if lines are counted from one from the beginning of the function. The value nominally assigned in this case is irrelevant, and ignored. For completeness, if lineno is made local and unset, as in
`local `-N` `LINENO``
then `LINENO` is simply unset inside the function, and gives no value at all.

Now for some technical details. The line on which `LINENO` occurs in a parameter expansion, is the line that contains the ‘$’ that begins the expansion of `LINENO`. In the case of nested expansions, that ‘$’ is the one that actually has `LINENO` as its parameter. In an arithmetic expansion, where no ‘$’ is used to evaluate `LINENO` but `LINENO` is simply referenced as a variable, then the value is the line number of the line that contains the ‘L’ of `LINENO`. For functions line one of the function definition (when relevant) is the line that contains the first character of the function name in the definition. When exported, the line number of the command is the line number where the first character of the word which becomes the command name occurs.

When the shell opens a new file, for any reason, it counts lines from one in that file, and then resumes its original counting once it resumes reading the previous input stream. When handling a string passed to `eval` the line number starts at the line on which the string starts, and then if the string contains internal newline characters, those characters increase the line number. This means that references to `LINENO` in such a case can produce values larger than would be produced by a reference on the line after the `eval`.

# FILES

- $HOME/.profile
- /etc/profile

# EXIT STATUS

Errors that are detected by the shell, such as a syntax error, will cause the shell to exit with a non-zero exit status. If the shell is not an interactive shell, the execution of the shell file will be aborted. Otherwise the shell will return the exit status of the last command executed, or if the exit built-in is used with a numeric argument, it will return the argument.

# SEE ALSO

csh(1), echo(1), getopt(1), ksh(1), login(1), printf(1), test(1), editline(3), getopt(3), editrc(5), passwd(5), editline(7), environ(7), nls(7), sysctl(8)

# HISTORY

A `sh` command appeared in Version 1 AT&T UNIX. It was replaced in Version 7 AT&T UNIX with a version that introduced the basis of the current syntax. That was, however, unmaintainable so we wrote this one. This NetBSD `sh` is a much modified descendant of the ash shell written by Ken Almquist.

# BUGS

Setuid shell scripts should be avoided at all costs, as they are a significant security risk.

The characters generated by filename completion should probably be quoted to ensure that the filename is still valid after the input line has been processed.

Job control of compound statements (loops, etc) is a complete mess.

The `-Z` option to the `jobs` built-in command is bizarre, but is implemented this way to be compatible with the similar option in zsh(1).

Many, many, more. (But less than there were...)

November 11, 2024 | NetBSD 11.0