OpenBSD manual page server

Manual Page Search Parameters

SH(1) General Commands Manual SH(1)

shcommand language interpreter

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

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:

string
Read commands from string.
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.

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.
Notify. The user is given notice asynchronously when background jobs complete.
Noclobber. Do not permit the redirection operator (‘>’) to clobber (overwrite) existing files.
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 ‘!’.
Noglob. Do not expand file name patterns.
When a utility is first executed, hash (record) its location so that future invocations do not need to search for it.
Enable behaviour convenient for an interactive shell. This option is set by default if the session is attached to a terminal.
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.
Noexec. Read commands but do not execute them – useful for checking syntax errors in scripts. This option is ignored for interactive shells.
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.
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.
Verbose. Write input to standard error after reading it.
Xtrace. Write a trace for each command to standard error after expanding it, and before executing it.

The shell has a number of 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.
[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.
[id ...]
Select a job by id (see the jobs command, below) to run in the background. The default job is "%+".
[n]
Exit from the innermost for, while, or until loop, or from loop level n.
[-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:

Do not resolve symbolic links before processing ".." components.
Resolve symbolic links before processing ".." components.
[-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:

Use a default value for PATH to search for the command.
Do not invoke command, but identify how the shell will interpret it (such as a function or special built-in).
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.

[n]
Go directly to the next iteration of the innermost for, while, or until loop, or from loop level n.
[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.
[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.
[n]
Exit the shell with exit status n, or that of the last command executed.
[-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:

List all exported variables in a manner that can be reinput to the shell.
Return a false (non-zero) value.
[-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:

editor
Edit commands using editor. See also FCEDIT.
List the command history.
List the command history without command numbers.
Edit or list (-lr) commands in reverse order.
[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.

[id ...]
Select a job by id (see the jobs command, below) to run in the foreground. The default job is "%+".
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: " "$@"
[-r | utility]
Add utility to the hash list or remove (-r) all utilities from the hash list. Without arguments, show the utilities currently hashed.
[-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:

Additionally display the process group ID.
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.
[-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:

[signal]
List all supported signals, or the signal name corresponding to signal number or the exit status of a command killed by a signal.
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
: Terminal line hangup.
2
: Interrupt a program.
3
: Quit a program.
6
: Call abort(3).
9
: Kill a program. Cannot be caught or ignored.
14
: Real-time timer expired.
15
: Software termination signal.
[-L | -P]
Print the current working directory.

The options to the pwd command are as follows:

Print the logical path to the current working directory i.e. display symbolic links followed.
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.

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

Ignore backslash sequences.
[-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:

Display the names and values of all readonly variables in a manner which can be reinput to the shell.
[n]
Exit the current function or . script with exit status n, or that of the last command executed.
[-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.

[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 ‘#’ to ‘(#−n)+1’ and downwards are unset and ‘#’ is updated to the new number of positional parameters. If n is 0, no change occurs.
Display accumulated process times for the shell (user and system) and all child processes (user and system).
[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.

Return a true (zero) value.
command ...
For each command, show how the shell would interpret it.
[-f n]
Limit the maximum size of a file that can be created to n blocks. Without arguments, display the current file size limit.
[-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:

Display symbolic output.

See chmod(1) for the format of mask.

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

The options to the unalias command are as follows:

Remove all alias definitions.
[-fv] name ...
Unset variable or function name.

The options to the unset command are as follows:

Treat name as a function.
Treat name as a variable (the default).
[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.

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, 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 is used to denote a sequence of letters, digits, or underscores; 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.
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.
Enter insert mode after the current cursor position.
Enter insert mode after the end of the current line.
Enter insert mode at the current cursor position.
Enter insert mode at the beginning of the current line.
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.
Delete the characters between the cursor and the line end, then enter insert mode.
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.
Repeat the most recent pattern search.
Repeat the most recent pattern search, but in the opposite direction.

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

Some characters have special meaning to the shell and need 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.

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

The shell is able to 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, parameter name, or array reference, 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 is used to open, close, or otherwise manipulate files, using redirection operators in combination with numerical . 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 , 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.

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

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.

The following environment variables affect the execution of sh:

Colon separated list of directories used by the cd command. If unset or empty, the current working directory is used.
Pathname to a file containing commands to be executed when an interactive shell is started.
Editor for the fc builtin. The default is ed(1).
Pathname to a file to be used to record command history. The default is to not write command history to a file.
The maximum number of commands stored in history. The default is 500.
Pathname to a user's home directory.
A list of characters to be used for field splitting.
The current line number in a script or function, starting at 1. This variable should not be set by users.
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.
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.
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.
Pathname to the previous working directory.
An option argument for the getopts command.
An index to the next option for the getopts command.
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
Enable POSIX mode (see STANDARDS).
The shell's parent process ID. Subshells have the same PPID as the current shell.
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.
Newline prompt displayed in an interactive shell when a newline has been entered before the command line completes. The default value is ‘> ’.
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.

The following signals affect the execution of sh:

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.
Ignored if a shell is interactive.
Ignored if a shell is interactive.
Ignored if a shell is interactive and the monitor option (-m) is set.
Ignored if a shell is interactive and the monitor option (-m) is set.
Ignored if a shell is interactive and the monitor option (-m) is set.

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.

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

The sh utility is compliant with the IEEE Std 1003.1-2008 (“POSIX.1”) specification, except where noted below:

Enabling POSIX mode changes some behaviour to make sh adhere more strictly to the IEEE Std 1003.1-2008 (“POSIX.1”) specification.

March 31, 2022 OpenBSD-7.1