SH(1)

NAME
sh - command language interpreter

SYNOPSIS
sh [-abCefhimnuvx] [-o option] [-c string | -s | file]

DESCRIPTION
The sh utility is a command language interpreter: it reads one or more commands, either from the command line or from a file (a shell script), and then sets about executing those commands. Thus it is the main interface between the user and the operating system.

This version of sh is actually ksh in disguise. As such, it also supports the features described in ksh(1). This manual page describes only the parts relevant to a POSIX compliant sh. If portability is a concern, use only those features described in this page.

The shell receives input as follows:

-c string
    Read commands from string.
-s  Read commands from standard input (the default).
file
    Read commands from file.

The options below can be specified with a ‘+’ rather than ‘-’, meaning to unset the option. They can also be set or unset using the set command. Some options have equivalent long names, indicated at the start of the description, which can be used with the -o option.

-a  Allexport. Variable assignments are exported to all child processes of the running shell. If the assignment precedes a command it does not persist after that command has finished running, unless the command is a special builtin or one of the builtins getopts or read makes the assignment.

-b  Notify. The user is given notice asynchronously when background jobs complete.

-C  Noclobber. Do not permit the redirection operator (‘>’) to clobber (overwrite) existing files.

-e  Errexit. Exit the shell immediately should an error occur or a command fail. For pipelines and && and || constructs, only exit if the last component fails. Errexit is ignored for while, until, if, and elif lists and pipelines beginning ‘’!.

-f  Noglob. Do not expand file name patterns.

-h  When a utility is first executed, hash (record) its location so that future invocations do not need to search for it.

-i  Enable behaviour convenient for an interactive shell. This option is set by default if the session is attached to a terminal.

-m  Monitor. Fully enable job control: enable the bg and fg builtins; report completion status when jobs finish; report when a foreground process stops; and report when a job changes status. The processes of a job share their own process group. This option is set by default for interactive shells.

-n  Noexec. Read commands but do not execute them – useful for checking syntax errors in scripts. This option is ignored for interactive shells.

-o option
    Specify an option by its long name. Those described below have no equivalent option letter:

    ignoreeof
        Ignore an end-of-file (‘^D’). EOF normally logs a user out, so setting this can prevent accidental logouts (the user will need to explicitly use the exit command).
    nolog
        Do not enter function definitions into command history.
    posix
        Enable POSIX mode (see STANDARDS).
    vi  Enable vi(1) command line editing.

-u  Nounset. If a command references an unset parameter, write an error to standard output instead of executing the command. This option is ignored for the special parameters ‘*’ and ‘@’. If the shell is not interactive, immediately exit.

-v  Verbose. Write input to standard error after reading it.

-x  Xtrace. Write a trace for each command to standard error after expanding it, and before executing it.

BUILTINS
The shell has a number of built-ins available: utilities that are included as part of the shell. The shell does not need to search for them and can execute them directly.

A number of built-ins are special in that a syntax error can cause a running shell to abort, and, after the built-in completes, variable assignments remain in the current environment. The following built-ins are special: .,:, break, continue, eval, exec, exit, export, readonly, return, set, shift, times, trap, and unset.

The built-ins available to sh are listed below. Unless otherwise indicated, they exit 0 on success, and >0 if an error occurs.

. file
    Execute the commands in file, in the current environment. The actual file need not be executable, and its location is determined by searching PATH if there are no slashes in the filename. The exit status is that of the last command returned, or zero if no commands were executed. If no readable file can be found, a non-interactive shell will abort; an interactive shell writes an error message and returns a non-zero exit status.

: [arg ...]
    The: command does nothing – it is a placeholder for when a command is required. Its exit status is always zero.

alias [name[=value] ...]
    Define an alias name to value; when the shell encounters a command name that is an alias, its value is substituted. If value ends in a blank, the next word is checked for alias substitution too. If only a name is specified, display the value of that alias; if no arguments are given, list all aliases and their values. Aliases are visible in the current environment and that of subshells, but not by the parent process of the current shell or by utilities invoked by it.

bg [id ...]
    Select a job by id (see the jobs command, below) to run in the background. The default job is "%+".

break [n]
    Exit from the innermost for, while, or until loop, or from loop level n.

cd [-L | -P] [dir]
    Change the current working directory to dir, or $HOME by default. If dir is set to ‘-’, change to the previous working directory and print the (now current) working directory. If dir does not begin with a slash or dot, CDPATH is searched for the directory.

    The options to the cd command are as follows:

    -L  Do not resolve symbolic links before processing ".." components.
    -P  Resolve symbolic links before processing ".." components.

command [-p | -V | -v] command [arg ...]
    Invoke command (and any optional arguments), overriding any functions with the same name, and without any of the properties that special built-ins have.

    The options to command are as follows:

    -p  Use a default value for PATH to search for the command.
    -V  Do not invoke command, but identify how the shell will interpret it (such as a function or special built-in).
    -v  Do not invoke command, but identify the pathname the shell will use to run it. For aliases, a command to define that alias is printed. For shell reserved words, shell functions, and built-in utilities, just the name is printed.

    The exit status is that of command, or 126 if command could not be invoked, or 127 if an error occurred in command itself or command could not be found. If the options -V or -v are given, the exit status is 0 on success, or >0 if an error occurs.

continue [n]
    Go directly to the next iteration of the innermost for, while, or until loop, or from loop level n.

eval [arg ...]
    Concatenate the arguments given and interpret them as a command. The exit status is that of the resulting command, zero if no arguments are given, or >0 if the resulting command could not be correctly parsed.

exec [command [arg ...]]
    Replace the shell with command (and any optional arguments), without creating a new process. The exit status is that of command, or 126 if command could not be invoked, or 127 if command could not be found. If no command is given but a redirection happens, the exit status is 1–125; otherwise exec returns 0.

exit [n]
    Exit the shell with exit status n, or that of the last command executed.

export [-p] name[=value] ...
    Make the variable name visible to subsequently run commands, optionally setting it to value.

    The options to the export command are as follows:

    -p  List all exported variables in a manner that can be reinput to the shell.

false
    Return a false (non-zero) value.

    fc [-lnr] [-e editor] [-s [old=new]] [first [last]] Edit commands from command history using ed(1). After editing, the new commands are executed by the shell.

    The options to the fc command are as follows:

    -e editor
        Edit commands using editor. See also FCEDIT.
    -l  List the command history.
    -ln List the command history without command numbers.
    -r  Edit or list (-lr) commands in reverse order.
    -s [old=new]
        Reexecute a single command without invoking an editor. The first occurrence of the string old in the command is replaced by new.

    A range of commands can be specified, first to last. Their format can be numerical, to select by command number; ‘-n’, to select a command executed that number of commands previous; or a string which matches the beginning of the command. If no range is given, the last command in command history is edited, or reexecuted (-s), or the previous 16 commands in command history are listed (-l). If first is newer than last, commands are processed in reverse order (as if -r had been given); if either are out of range, the oldest or newest values are used.

fg [id ...]
    Select a job by id (see the jobs command, below) to run in the foreground. The default job is "%+".

getopts optstring name [arg ...]
    When invoked, getopts processes the positional parameters (or any arg passed to it) as a list of options and option arguments. getopts sets the variable name to the option found, OPTARG to its argument, and OPTIND to the index of the next variable to be processed.

    The string optstring contains a list of acceptable options; a colon following an option indicates it requires an argument. If an option not recognised by optstring is found, name is set to ‘’?; if the first character of optstring is a colon, OPTARG is set to the unsupported option, otherwise an error message is displayed.

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

        while getopts ao: name
        do
        	case $name in
        	a)	flag=1 ;;
        	o)	oarg=$OPTARG ;;
        	?)	echo "Usage: ..."; exit 2 ;;
        	esac
        done
        shift $(($OPTIND - 1))
        echo "Non-option arguments: " "$@"

hash [-r | utility]
    Add utility to the hash list or remove (-r) all utilities from the hash list. Without arguments, show the utilities currently hashed.

jobs [-l | -p] [id ...]
    Display the status of all jobs in the current shell environment, or those selected by id.

    The options to the jobs command are as follows:

    -l  Additionally display the process group ID.
    -p  Display only the process group ID.

    Job id can be selected in one of the following ways:

    %%  The current job.
    %+  The current job.
    %-  The previous job.
    %n  Job number n.
    %string
        Job with command matching string.
    %?string
        Job with command containing string.

    kill [-l [signal]] [-s signal] [- signal] pid ... Send a signal, by default SIGTERM, to the process with ID pid.

    The options to the kill command are as follows:

    -l [signal]
        List all supported signals, or the signal name corresponding to signal number or the exit status of a command killed by a signal.
    -s signal
        Send the process signal name.
    - signal
        Send the process signal name or number.
    pid A process ID, process group ID, or a job ID (see jobs, above). The process ID 0 signals all processes in the current process group.

    The supported signal numbers are:

    0   Do not signal a process, but determine whether an ID exists.
    1   SIGHUP: Terminal line hangup.
    2   SIGINT: Interrupt a program.
    3   SIGQUIT: Quit a program.
    6   SIGABRT: Call abort(3).
    9   SIGKILL: Kill a program. Cannot be caught or ignored.
    14  SIGALRM: Real-time timer expired.
    15  SIGTERM: Software termination signal.

pwd [-L | -P]
    Print the current working directory.

    The options to the pwd command are as follows:

    -L  Print the logical path to the current working directory i.e. display symbolic links followed.
    -P  Print the physical path to the current working directory i.e. display symbolic links resolved.

    If both options are given, the last specified is used; if none are given, the default is -L.

read [-r] name ...
    Read a line from standard input. The line is split into fields, with each field assigned to a variable, name, in turn (first field assigned to first variable, and so on). If there are more fields than variables, the last variable will contain all the remaining fields. If there are more variables than fields, the remaining variables are set to empty strings. A backslash in the input line causes the shell to prompt for further input.

    The options to the read command are as follows:

    -r  Ignore backslash sequences.

readonly [-p] name[=value]
    Mark variable name as readonly, and optionally set it to value. Readonly variables cannot be later assigned values or unset.

    The options to the readonly command are as follows:

    -p  Display the names and values of all readonly variables in a manner which can be reinput to the shell.

return [n]
    Exit the current function or. script with exit status n, or that of the last command executed.

    set [-abCefhmnuvx] [-o [option]] [arg ...] Set options and positional parameters. Without options or arguments, display the names and values of all shell variables.

    The options are described in the options description at the beginning of this manual. The sequence ‘set -o’ displays the current option settings; the sequence ‘set +o’ displays, in a format suitable to be reinput to the shell, a command suitable to achieve the current option settings.

    Any arguments are assigned to the positional parameters, with the special parameter ‘#’ set to the number of positional parameters. The sequence ‘set --’ indicates an end to option processing (i.e. only arguments follow); ‘set --’ by itself unsets all positional parameters and sets ‘#’ to zero.

shift [n]
    Shift the positional parameters n times (by default once). Parameter 1 takes the value of parameter ‘1+n’, parameter 2 takes ‘2+n’, and so on. Parameters ‘#’ down to ‘(#-n)+1’ are unset and ‘#’ is updated to the new number of positional parameters. If n is 0, no change occurs.

times
    Display accumulated process times for the shell (user and system) and all child processes (user and system).

trap [action signal ...]
    Perform action whenever signal is caught. Without arguments, display a list of all traps and actions, in a format suitable to be reinput to the shell.

    If action is ‘-’ or an integer, reset signal to its default value; if it is empty (""), ignore signal. If signal is "EXIT" or 0, perform action when the shell exits; otherwise signal should be a signal name (without the SIG prefix) or number.

true
    Return a true (zero) value.

type command ...
    For each command, show how the shell would interpret it.

ulimit [-f n]
    Limit the maximum size of a file that can be created to n blocks. Without arguments, display the current file size limit.

umask [-S] [mask]
    Set the file mode creation mask to mask. The creation mask determines the default permissions a newly created file or directory will have. If mask is not specified, display the current creation mask.

    The options to the umask command are as follows:

    -S  Display symbolic output.

    See chmod(1) for the format of mask.

unalias [-a] name ...
    Remove the alias definition of alias name.

    The options to the unalias command are as follows:

    -a  Remove all alias definitions.

unset [-fv] name ...
    Unset variable or function name.

    The options to the unset command are as follows:

    -f  Treat name as a function.
    -v  Treat name as a variable (the default).

wait [pid ...]
    Wait until all the processes specified by process or job ID pid have terminated. If no pid is specified, wait until all processes have terminated. The exit status is 0 on success, 1–126 if an error occurs, or 127 if pid was unknown.

COMMAND HISTORY AND COMMAND LINE EDITING
When a shell is interactive, it keeps a record of commands run in a command history, either internally in memory or in a file, as determined by HISTFILE. When vi command line editing mode is enabled (set -o vi), the command line and all the commands in command history can be edited using commands similar to those of vi(1).

There are two modes, interactive and command. The shell starts in interactive mode. In this mode text is entered normally. A <newline> executes the current command line. The command line, unless empty, is entered into command history. The <ESC> key is used to enter command mode, where commands similar to those used by vi(1) are available. A Ctrl-L sequence (^L) can be used in this mode to redraw the current command line.

Where noted, some commands may be preceded by a numerical count, which causes the command to be repeated that number of times. The term word is used to denote a sequence of letters, digits, or underscores; bigword denotes a sequence of whitespace delineated characters.

The commands for command mode:

=   Display the possible shell word expansion.

\   Perform pathname expansion on the current word, matching the largest possible unique expansion, then enter insert mode.

*   Perform pathname expansion on the current word, substituting every possible expansion, then enter insert mode.

@c  Perform the commands defined by the alias _c, where c is a single letter alphabetical character.

[count]~
    Convert the character from lowercase to upper or vice versa.

[count].
    Repeat the most recent non-motion command. If no count is given, use that of the repeated command, if any.

[n]v
    Use vi(1) to edit command number n in command history, or the current command if none given.

    [count]l, [count]<space> Move right.

[count]h
    Move left.

[count]w
    Move to the start of the next word.

[count]W
    Move to the start of the next big word.

[count]e
    Move to the end of the current word, or the end of the next word if the cursor is currently at the end of a word.

[count]E
    Move to the end of the current bigword, or the end of the next bigword if the cursor is currently at the end of a bigword.

[count]b
    Move to the start of the current word, or the start of the next word if the cursor is currently at the start of a word.

[count]B
    Move to the start of the current bigword, or the start of the next bigword if the cursor is currently at the start of a bigword.

^   Move to the first non-blank character.

$   Move to the end of the current line.

0   Move to the beginning of the current line.

[count]|
    Move to the beginning of the current line or the character position specified by count.

[count]fc
    Move to the next instance of the character c.

[count]Fc
    Move to the last instance of the character c.

[count]tc
    Move to the character before the next instance of the character c.

[count]Tc
    Move to the character after the last instance of the character c.

[count];
    Repeat the last f, F, t, or T command. Ignore any count specified with the last command.

[count],
    Repeat the last f, F, t, or T command, but in the opposite direction. Ignore any count specified with the last command.

a   Enter insert mode after the current cursor position.

A   Enter insert mode after the end of the current line.

i   Enter insert mode at the current cursor position.

I   Enter insert mode at the beginning of the current line.

R   Enter insert mode at the current cursor position, replacing any characters thereafter.

[count]cmotion
    Delete the characters between the cursor and the motion command specified, then enter insert mode. A special motion command, c, may be used to delete the entire line. The count argument is ignored for the commands 0, ^, $, and c. If the motion moves towards the beginning of the line, the character under the cursor is not deleted; if it moves towards the end of the line, it is deleted.

C   Delete the characters between the cursor and the line end, then enter insert mode.

S   Clear the entire line, then enter insert mode.

[count]r
    Replace the character under the cursor with the next typed character. With a count, replace the current character and the corresponding number of following characters.

[count]_
    After the cursor, append a <space> and the countth bigword (by default the last entered) from the previous input line, then enter insert mode.

[count]x
    Delete the character under the cursor, placing it in the save buffer.

[count]X
    Delete the character before the cursor, placing it in the save buffer.

[count]dmotion
    Delete the characters between the cursor and the motion command specified, placing them in the save buffer. A special motion command, d, may be used to delete the entire line. If the motion moves towards the beginning of the line, the character under the cursor is not deleted.

[count]D
    Delete the characters between the cursor and the line end, placing them in the save buffer.

[count]ymotion
    Yank (copy) the characters between the cursor and the motion command specified, placing them in the save buffer. A special motion command, y, may be used to yank the entire line. If the motion moves towards the beginning of the line, the character under the cursor is not yanked.

[count]Y
    Yank (copy) the characters between the cursor and the line end, placing them in the save buffer.

[count]p
    Paste the contents of the save buffer after the cursor.

[count]P
    Paste the contents of the save buffer before the cursor.

[count]u
    Undo the last change to the edit line.

[count]U
    Undo all changes to the edit line.

    [count]k, [count]- Replace the current command line with the previous entry in history.

    [count]j, [count]+ Replace the current command line with the next entry in history.

[n]G
    Replace the current command line with command number n in command history, or the oldest command if none given.

/pattern
    Moving backwards through history, replace the current command line with the first that matches pattern. A ‘^’ at the beginning of the pattern searches only for entries beginning with pattern. An empty pattern matches the last search.

?pattern
    As above, but searching forwards.

n   Repeat the most recent pattern search.

N   Repeat the most recent pattern search, but in the opposite direction.

SHELL GRAMMAR
The shell reads its input as described above. After that it follows a fairly simple chain of operations to parse that input:

-   The shell breaks the input into words and operators. Words are the command text the user wishes run; operators are special characters which describe how the shell should interact with the commands.

-   The shell expands the command text according to the rules of expansion.

-   Words are subject to field splitting, where the command text is separated into commands and arguments to commands.

-   The shell performs any redirection.

-   The shell runs the commands. Argument names are assigned to positional parameters, with the command name itself assigned parameter 0.

-   If the command is not being run in the background, the shell waits for it to complete and collects its exit status.

  Quoting
Some characters have special meaning to the shell and need quoting if the user wants to indicate to the shell not to interpret them as such. The following characters need quoting if their literal meaning is desired:

    | & ; < > ( ) $ ` \ " ' <space> <tab> <newline>
    * ? [ # ~ = %

A backslash (\) can be used to quote any character except a newline. If a newline follows a backslash the shell removes them both, effectively making the following line part of the current one.

A group of characters can be enclosed within single quotes (') to quote every character within the quotes.

A group of characters can be enclosed within double quotes (") to quote every character within the quotes except a backquote (`) or a dollar sign ($), both of which retain their special meaning. A backslash (\) within double quotes retains its special meaning, but only when followed by a backquote, dollar sign, double quote, newline, or another backslash. An at sign (@) within double quotes has a special meaning (see SPECIAL PARAMETERS, below).

Similarly command words need to be quoted if they are not to be interpreted as such.

  Expansion
Shell variables are arbitrary names assigned values using the ‘=’ operator; the values can be retrieved using the syntax $variable. Shell parameters are variable names, numbers, or any of the characters listed in SPECIAL PARAMETERS.

The shell is able to expand certain elements of its syntax, allowing for a more concise notation and providing a convenience to the user.

Firstly, tilde expansion occurs on words beginning with the ‘~’ character. Any characters following the tilde, up to the next colon, slash, or blank, are taken as a login name and substituted with that user's home directory, as defined in passwd(5). A tilde by itself is expanded to the contents of the variable HOME. This notation can be used in variable assignments, in the assignment half, immediately after the equals sign or a colon, up to the next slash or colon, if any.

    PATH=~alice:~bob/jobs

Parameter expansion happens after tildes have been expanded, with the value of the parameter being substituted. The basic format is:

    ${parameter}

The braces are optional except for positional parameters 10 and higher, or where the parameter name is followed by other characters that would prevent it from being expanded. If parameter expansion occurs within double quotes, neither pathname expansion nor field splitting happens afterwards.

Some special forms of parameter expansion are available. In the formats below, word itself is subject to expansion, and, if omitted, the empty string is used. If the colon is omitted, word is substituted only if parameter is unset (not if it is empty).

${parameter:-[word]}
    Substitute parameter. If parameter is unset or empty, substitute word.

${parameter:=[word]}
    Substitute parameter. If parameter is unset or empty, first assign the value of word to parameter.

${parameter:?[word]}
    Substitute parameter. If parameter is unset or empty, the result of the expansion of word is written to standard error and the shell exits with a non-zero exit status. If word is omitted, the string "parameter null or not set" is used.

${parameter:+[word]}
    Substitute word. If parameter is unset or empty, substitute the empty string.

${#parameter}
    The length, in characters, of parameter.

${parameter%[word]}
    Substitute parameter, deleting the smallest possible suffix matching word.

${parameter%%[word]}
    Substitute parameter, deleting the largest possible suffix matching word.

${parameter#[word]}
    Substitute parameter, deleting the smallest possible prefix matching word.

${parameter##[word]}
    Substitute parameter, deleting the largest possible prefix matching word.

Command expansion has a command executed in a subshell and the results output in its place. The basic format is:

    $(command)
or
    `command`

The results are subject to field splitting and pathname expansion; no other form of expansion happens. If command is contained within double quotes, field splitting does not happen either. Within backquotes, a backslash is treated literally unless it follows a dollar sign, backquote, or another backslash. Commands can be nested, though the backquoted version requires backslashes before the backquotes. If command is run in a subshell in the bracketed version, the syntax is identical to that of arithmetic expansion. In that case the shell attempts arithmetic expansion first, then attempts command substitution if that fails. Or a non-ambiguous version can be used:

    $( (command) )

Arithmetic expansion works similarly, with an arithmetic expression being evaluated and substituted. The format is:

    $((expression))

Where expression is an integer or parameter name, optionally combined with any of the operators described below, listed and grouped according to precedence:

()  Operators within brackets have highest precedence. Compare 3+2*4, which is 11, since multiplication has higher precedence than addition, and (3+2)*4, which is 20.

+ - ~!
    Unary plus (indicates a positive value; integers are positive by default), unary minus (indicates a negative value), bitwise NOT, and logical NOT (the result is 1 if the argument is zero, or 0 otherwise), respectively.

* / %
    Multiplication, division, and modulus (remainder), respectively.

+ - Addition and subtraction, respectively.

<< >>
    Shift left or right, respectively.

< <= > >=
    Less than, less than or equal to, greater than, and greater than or equal to, respectively. The result is 1 if true, or 0 otherwise.

== !=
    Equal (the result is 1 if both arguments are equal, and 0 otherwise) and not equal (the result is 0 if both arguments are equal, and 1 otherwise), respectively.

&   Bitwise AND.

^   Bitwise exclusive OR.

|   Bitwise inclusive OR.

&&  Logical AND. The result is 1 if both arguments are non-zero, or 0 otherwise.

||  Logical OR. The result is 1 if either argument is non-zero, or 0 otherwise.

expression?expr1:expr2
    The result is expr1 if expression is non-zero, or expr2 otherwise.

= *= /= %= += -= <<= >>= &= ^= |=
    Assignment. The notation var*=expression is equivalent to var=var*expression.

After the various types of expansion listed above have been carried out, the shell subjects everything that did not occur in double quotes to field splitting, where words are broken up according to the value of the IFS variable. Each character of IFS is used to split fields; any IFS characters at the beginning and end of input are ignored. If IFS is unset, the default value consisting of <space>, <tab> and <newline> is used; if the value of IFS is empty, no field splitting is performed.

After field splitting, the shell matches filename patterns.

?   A question mark matches any single character.

*   An asterisk matches multiple characters.

[..]
    Matches any character enclosed in the brackets. The sense is negated if the first character is ‘’!. A closing bracket can be included in the list of characters to match by listing it as the first character after the opening bracket or by quoting it. Similarly a ‘-’ should be specified last or quoted so that the shell does not think it is a character range (see below).

[[:class:]]
    Matches any character in the following character classes:

        alnum	alpha	blank	cntrl
        digit	graph	lower	print
        punct	space	upper	xdigit

[x-y]
    Matches any character in the range between x and y, inclusive.

Slashes and full stops do not match the patterns above because of their use as path and filename characters.

  Redirection
Redirection is used to open, close, or otherwise manipulate files, using redirection operators in combination with numerical file descriptors. A minimum of ten (0-9) descriptors are supported; by convention standard input is file descriptor 0, standard output file descriptor 1, and standard error file descriptor 2. In the examples given below, n represents a numerical file descriptor. The target for redirection is file and it is subject to all forms of expansion as listed above, except pathname expansion. If any part of the file descriptor or redirection operator is quoted, they are not recognised.

[n]<file
    Open file for reading on file descriptor n, by default standard input.

[n]>file
    Write to file with file descriptor n, by default standard output. If file does not exist, create it; if it does exist, truncate it to be empty before beginning to write to it.

[n]>|file
    As above, but forces clobbering (see the -C option).

[n]>>file
    Append to file with file descriptor n, by default standard output. If file does not exist, create it.

[n]<<
    This form of redirection, called a here document, is used to copy a block of lines to a temporary file until a line matching delimiter is read. When the command is executed, standard input is redirected from the temporary file to file descriptor n, or standard input by default. The basic format is:

        [n]<<delimiter
        text
        text
        ...
        delimiter

    Provided delimiter doesn't contain any quoted characters, parameter, command, and arithmetic expansions are performed on the text block, and backslashes escape the special meaning of ‘$’, ‘`’, and ‘\’. If multiple here documents are used on the same command line, they are saved and processed in order.

[n]<<-
    Same as <<, except leading tabs are stripped from lines in block.

[n]<&file
    Make file descriptor n, by default standard input, a copy of the file descriptor denoted by file. If file is ‘-’, close file descriptor n or standard input.

[n]>&file
    Make file descriptor n, by default standard output, a copy of the file descriptor denoted by file. If file is ‘-’, close file descriptor n or standard output.

[n]<>file
    Open file for reading and writing on file descriptor n, by default standard input. If file does not exist, create it.

COMMANDS
The shell first expands any words that are not variable assignments or redirections, with the first field being the command name and any successive fields arguments to that command. It sets up redirections, if any, and then expands variable assignments, if any. It then attempts to run the command.

Firstly, it determines whether the command name contains any slashes. If it does not, and the shell implements the command as a special built-in, it then invokes the built-in. If not, but it is a non POSIX standard command, implemented as a shell function, it then invokes that. If not, but it is one of the commands alias, bg, cd, command, false, fc, fg, getopts, jobs, kill, newgrp, pwd, read, true, umask, unalias, or wait, it then invokes that.

Failing that, the value of PATH is used to search for the command. If it finds a match, and it is a POSIX standard command, implemented as a built-in or function, it then invokes it. Otherwise it attempts to execute the command in an environment separate from the shell. If it is unable to execute the command, it tries to run it as a shell script.

Finally, if the command name does contain a slash, and it finds a match in PATH, it attempts to execute the command in an environment separate from the shell. If it is unable to execute the command, it tries to run it as a shell script.

A series of one or more commands separated by ‘’; constitute a sequential list, where commands are executed in the order given. The exit status of a sequential list is that of the last command executed. The format for a sequential list is:

    command; [command ...]

A series of one or more commands separated by ‘&’ constitute an asynchronous list, where the shell executes the command in a subshell and runs the next command without waiting for the previous one to finish. The exit status of an asynchronous list is always zero. The format for an asynchronous list is:

    command & [command ...]

A series of commands separated by ‘|’ constitute a pipeline, where the output of one command is used as input for the next command. The exit status of a pipeline is that of the last command; if a pipeline begins ‘’! the exit status is inverted. The format for a pipeline is:

    [!] command | command [| ...]

A series of commands separated by ‘&&’ constitute an AND list, where a command is only executed if the exit status of the previous command was zero. The exit status of an AND list is that of the last command. The format for an AND list is:

    command && command [&& ...]

A series of commands separated by ‘||’ constitute an OR list, where a command is only executed if the exit status of the previous command was non-zero. The exit status of an OR list is that of the last command. The format for an OR list is:

    command || command [|| ...]

A series of commands separated by ‘&&’ and ‘||’ constitute an AND-OR list, where ‘&&’ and ‘||’ have equal precedence and are evaluated in the order they are given. The AND-OR list can be terminated with ‘’; or ‘&’ to have them execute sequentially or asynchronously, respectively.

Command lists, as described above, can be enclosed within ‘()’ to have them executed in a subshell, or within ‘{}’ to have them executed in the current environment:

    (command ...)
    {command ...;}

Any redirections specified after the closing bracket apply to all commands within the brackets. An operator such as ‘’; or a newline are needed to terminate a command list within curly braces.

The shell has grammatical constructs which allow it to work its way (loop) through lists or evaluate things conditionally.

A for loop executes a series of commands for each item in a list. Its format is:

    for name [in [word ...]]
    do
        command
        ...
    done

Firstly word ... is expanded to generate a list of items. The variable name is set to each item, in turn, and the commands are executed for each item. The construct "in word ..." can be omitted, which is equivalent to: in "$@". The exit status is that of the last command executed. If there are no items, command is not executed and the exit status is zero.

A while loop continuously executes a set of commands as long as the command or command list being tested in condition has a zero exit status. Its format is:

    while condition
    do
        command
        ...
    done

Multiple commands may be given by grouping them in lists, as described above, or by separating them with newlines. The exit status is zero if the commands after "do" were never executed or otherwise the exit status of the last command executed.

An until loop continuously executes a set of commands as long as the command or command list being tested in condition has a non-zero exit status. Its format is:

    until condition
    do
        command
        ...
    done

Multiple commands may be given by grouping them in lists, as described above, or by separating them with newlines. The exit status is zero if the commands after "do" were never executed or otherwise the exit status is that of the last command executed.

A case conditional is used to run commands whenever a pattern is matched. Its format is:

    case word in
        (pattern [| pattern ...]) command;;
        ...
    esac

In this case pattern is matched against the string resulting from the expansion of word. Multiple commands may be given by grouping them in lists, as described above, or by separating them with newlines. The initial ‘(’ is optional, as is the terminating ‘;;’ for the final command. The exit status is zero if no patterns are matched or otherwise the exit status of the last command executed.

An if conditional is used to execute commands depending on the exit status of the command or command list being tested. Its format is:

    if conditional
    then
        command
        ...
    elif conditional
    then
        command
        ...
    else
        command
        ...
    fi

Firstly the command(s) following "if" is executed; if its exit status is zero, the commands in the "then" block are executed and the conditional completes. Otherwise the commands in the "elif" block are executed; if the exit status is zero, the commands in the "then" block are executed and the conditional completes. Otherwise the next "elif" block, if any, is tried. If nothing from an "if" or "elif" block returns zero, the commands in the "else" block are run and the conditional completes. The "elif" and "else" blocks are optional.

Multiple commands may be given by grouping them in lists, as described above, or by separating them with newlines. The exit status is zero if nothing is executed from an "if" or "elif" block or otherwise the exit status of the last command executed.

Functions allow the user to define a group of commands, executed whenever the function is invoked. Its format is:

    function() command-list

The above simply defines a function; nothing is executed until the function is invoked. Commands may specify redirections and positional parameters are changed, for the duration of the function, to those passed to it. The special parameter ‘#’ is temporarily changed too, though ‘0’ is not. After the function finishes, the positional parameters and ‘#’ are restored to their original values. The exit status of a function definition is 0 if successful or >0 otherwise. The exit status of a function is that of the last command executed by the function.

SPECIAL PARAMETERS
Some parameters have special meaning to the shell and are listed below.

0   The name of the shell or shell script.

1 ... n
    The positional parameters. These parameters are set when a shell, shell script, or shell function is invoked. Each argument passed to a shell or shell script is assigned a positional parameter, starting at 1, and assigned sequentially. When a shell function is invoked, any arguments passed to it are temporarily reassigned to the positional parameters; when the function completes, the values are restored. Positional parameters 10 and above should be enclosed in {}. Positional parameters can be reassigned using the set command.

@   All positional parameters. Within double quotes, each parameter is output as a separate field. The resulting list completely matches what was passed to the shell. So "1 2" "3" is output as two parameters, "1 2" and "3".

*   All positional parameters. Within double quotes, all parameters are output as one field, separated by the first character of IFS (by default a space). The resulting list of words is amalgamated, losing the sense of how they were passed to the shell. So "1 2" "3" is output as one parameter, "1 2 3".

#   The number of positional parameters.

?   The exit status of the most recent command.

-   The current shell options.

$   The process ID of the current shell. Subshells have the same PID as the current shell.

!   The process ID of the most recent background command.

ENVIRONMENT
The following environment variables affect the execution of sh:

CDPATH
    Colon separated list of directories used by the cd command. If unset or empty, the current working directory is used.

ENV Pathname to a file containing commands to be executed when an interactive shell is started.

FCEDIT
    Editor for the fc builtin. The default is ed(1).

HISTFILE
    Pathname to a file to be used to record command history. The default is to not write command history to a file.

HISTSIZE
    The maximum number of commands stored in history. The default is 500.

HOME
    Pathname to a user's home directory.

IFS A list of characters to be used for field splitting.

LINENO
    The current line number in a script or function, starting at 1. This variable should not be set by users.

MAIL
    Pathname to a user's mailbox file. If set, sh reports the arrival of new mail (ascertained by checking a file's modification time) every MAILCHECK seconds. MAIL is overridden by MAILPATH.

MAILCHECK
    How often, in seconds, to check for new mail in either MAIL or MAILPATH. The default is 600 (10 minutes). If set to 0, check before issuing each prompt.

MAILPATH
    Pathname to a colon separated list of mailboxes. If set, sh reports the arrival of new mail (ascertained by checking a file's modification time) every MAILCHECK seconds. The default notification message ("you have mail in $_") can be changed per mailbox by appending %message to a pathname. MAILPATH overrides MAIL.

OLDPWD
    Pathname to the previous working directory.

OPTARG
    An option argument for the getopts command.

OPTIND
    An index to the next option for the getopts command.

PATH
    Pathname to a colon separated list of directories used to search for the location of executable files. A pathname of ‘’. represents the current working directory. The default value of PATH on OpenBSD is:

        /usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin

POSIXLY_CORRECT
    Enable POSIX mode (see STANDARDS).

PPID
    The shell's parent process ID. Subshells have the same PPID as the current shell.

PS1 User prompt displayed every time an interactive shell is ready to read a command. A ‘’! in the prompt is expanded to the number of the next command in history to be typed.

PS2 Newline prompt displayed in an interactive shell when a newline has been entered before the command line completes. The default value is ‘> ’.

PS4 Trace prompt displayed in an interactive shell before each command is traced (see the -x option). The default is ‘+ ’.

PWD The absolute pathname to the current working directory.

ASYNCHRONOUS EVENTS
The following signals affect the execution of sh:

SIGINT
    If a shell is interactive and in command line editing mode, editing is terminated on the current line and the command being edited is not entered into command history. Otherwise the signal is caught but no action is taken.

SIGQUIT
    Ignored if a shell is interactive.

SIGTERM
    Ignored if a shell is interactive.

SIGTSTP
    Ignored if a shell is interactive and the monitor option (-m) is set.

SIGTTIN
    Ignored if a shell is interactive and the monitor option (-m) is set.

SIGTTOU
    Ignored if a shell is interactive and the monitor option (-m) is set.

EXIT STATUS
The sh utility exits with one of:

0   The script being executed contained only blank lines or comments.

1–125
    A non-interactive shell detected an error other than file not found.

126 A command was found but was not executable.

127 A non-interactive shell returned file not found.

Otherwise sh returns the exit status of the last command it invoked.

SEE ALSO
csh(1), ed(1), ksh(1), vi(1), script(7)

STANDARDS
The sh utility is compliant with the p1003.1-2008 specification, except where noted below:

-   The flag [-h] is documented by POSIX as hashing "utilities invoked by functions as those functions are defined"; this implementation hashes utilities after first invocation (and functions be damned).

-   POSIX says mail notifications via MAIL and MAILPATH should happen if a file is created, as well as if its modification time changes. This implementation of sh does not provide notification when these files are created.

-   The built-in newgrp is unsupported.

-   The break and continue built-ins should exit/return from the outermost loop if the argument n is greater than the level of loops.

-   The default value for the PS1 user prompt contains the machine's hostname, followed by ‘$ ’ for normal users and ‘# ’ for root; POSIX does not include the hostname.

Enabling POSIX mode changes some behaviour to make sh adhere more strictly to the p1003.1-2008 specification.