sh(1P, 1p) | shell, the standard command language interpreter |
loksh-sh, sh(1) | command language interpreter |
heirloom-sh, sh, jsh(1) | the standard command interpreter |
mksh, sh(1) | MirBSD Korn shell |
SH(1) | General Commands Manual | SH(1) |
sh
— command
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:
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
getopts
or
read
makes the assignment.-b
-C
-e
&&
and
||
constructs, only exit if the last component
fails. Errexit is ignored for while
,
until
, if
, and
elif
lists and pipelines beginning
‘!’.-f
-h
-i
-m
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
-o
optionexit
command).-u
-v
-x
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.
.
filePATH
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 ...]:
command does nothing – it is a
placeholder for when a command is required. Its exit status is always
zero.alias
[name[=value]
...]bg
[id ...]jobs
command, below) to run in the background. The
default job is "%+".break
[n]for
,
while
, or until
loop, or
from loop level n.cd
[-L
| -P
]
[dir]$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:
command
[-p
| -V
|
-v
] command
[arg ...]The options to command
are as
follows:
-p
PATH
to search for the
command.-V
-v
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]for
, while
, or
until
loop, or from loop level
n.eval
[arg ...]exec
[command [arg ...]]exec
returns 0.exit
[n]export
[-p
]
name[=value]
...The options to the export
command are
as follows:
-p
false
fc
[-lnr
] [-e
editor] [-s
[old=new]]
[first [last]]The options to the fc
command are as
follows:
-e
editorFCEDIT
.-l
-ln
-r
-lr
) commands in reverse
order.-s
[old=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 ...]jobs
command, below) to run in the foreground. The
default job is "%+".getopts
optstring name [arg ...]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]-r
) all utilities from the hash list. Without
arguments, show the utilities currently hashed.jobs
[-l
| -p
]
[id ...]The options to the jobs
command are as
follows:
Job id can be selected in one of the following ways:
kill
[-l
[signal]]
[-s
signal]
[-
signal] pid
...SIGTERM
, to the process
with ID pid.
The options to the kill
command are as
follows:
-l
[signal]-s
signal-
signaljobs
, above). The process ID 0 signals all
processes in the current process group.The supported signal numbers are:
SIGHUP
:
Terminal line hangup.SIGINT
:
Interrupt a program.SIGQUIT
:
Quit a program.SIGABRT
:
Call abort(3).SIGKILL
:
Kill a program. Cannot be caught or ignored.SIGALRM
:
Real-time timer expired.SIGTERM
:
Software termination signal.pwd
[-L
| -P
]The options to the pwd
command are as
follows:
If both options are given, the last specified is used; if none
are given, the default is -L
.
read
[-r
] name ...The options to the read
command are as
follows:
-r
readonly
[-p
]
name[=value]The options to the readonly
command
are as follows:
-p
return
[n].
script with exit
status n, or that of the last command executed.set
[-abCefhmnuvx
] [-o
[option]] [arg ...]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]times
trap
[action signal ...]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
type
command ...ulimit
[-f
n]umask
[-S
] [mask]The options to the umask
command are
as follows:
-S
See chmod(1) for the format of mask.
unalias
[-a
] name ...The options to the unalias
command are
as follows:
-a
unset
[-fv
] name ...The options to the unset
command are
as follows:
wait
[pid ...]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:
=
\
*
@
c~
.
v
l
,
[count]⟨space⟩h
w
W
e
E
b
B
^
$
0
|
f
cF
ct
cT
c;
f
, F
,
t
, or T
command. Ignore
any count specified with the last command.,
f
, F
,
t
, or T
command, but in
the opposite direction. Ignore any count specified
with the last command.a
A
i
I
R
c
motionc
, 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
S
r
_
x
X
d
motiond
, 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.D
y
motiony
, 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.Y
p
P
u
U
k
,
[count]-
j
,
[count]+
G
n
N
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 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.
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:
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).
Command expansion has a command executed in a subshell and the results output in its place. The basic format is:
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:
Arithmetic expansion works similarly, with an arithmetic expression being evaluated and substituted. The format is:
Where expression is an integer or parameter name, optionally combined with any of the operators described below, listed and grouped according to precedence:
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.
alnum alpha blank cntrl digit graph lower print punct space upper xdigit
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 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.
-C
option).[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.
<<
, except leading tabs are stripped
from lines in block.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:
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:
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:
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:
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:
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:
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.
Some parameters have special meaning to the shell and are listed below.
set
command.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 following environment variables affect the execution of
sh
:
CDPATH
cd
command. If unset or empty, the current working directory is used.ENV
FCEDIT
fc
builtin. The default is
ed(1).HISTFILE
HISTSIZE
HOME
IFS
LINENO
MAIL
sh
reports the arrival of new mail (ascertained by checking a file's
modification time) every MAILCHECK
seconds.
MAIL
is overridden by
MAILPATH
.MAILCHECK
MAIL
or MAILPATH
. The
default is 600 (10 minutes). If set to 0, check before issuing each
prompt.MAILPATH
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
OPTARG
getopts
command.OPTIND
getopts
command.PATH
PATH
on OpenBSD is:
/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin:/usr/local/sbin
POSIXLY_CORRECT
PPID
PPID
as the current shell.PS1
PS2
PS4
-x
option). The default is
‘+ ’.PWD
The following signals affect the execution of
sh
:
SIGINT
SIGQUIT
SIGTERM
SIGTSTP
monitor
option (-m
) is set.SIGTTIN
monitor
option (-m
) is set.SIGTTOU
monitor
option (-m
) is set.The sh
utility exits with one of:
Otherwise sh
returns the exit status of
the last command it invoked.
The sh
utility is compliant with the
IEEE Std 1003.1-2008 (“POSIX.1”)
specification, except where noted below:
-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).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.newgrp
is unsupported.break
and continue
built-ins should exit/return from the outermost loop if the argument
n is greater than the level of loops.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 IEEE
Std 1003.1-2008 (“POSIX.1”) specification.
March 6, 2024 | x86_64 |