SH(1) | General Commands Manual | SH(1) |
sh
—
sh |
[-abCEeFfhIiLmnpquVvXx ]
[+abCEeFfhIiLmnpquVvXx ]
[-o option_name]
[+o option_name]
[command_file [argument ...]] |
sh |
-c [-s ]
[-abCEeFfhIiLmnpquVvXx ]
[+abCEeFfhIiLmnpquVvXx ]
[-o option_name]
[+o option_name]
command_string
[command_name [argument ...]] |
sh |
-s
[-abCEeFfhIiLmnpquVvXx ]
[+abCEeFfhIiLmnpquVvXx ]
[-o option_name]
[+o option_name]
[argument ...] |
sh
is the standard command interpreter for the system.
It is a re-implementation and extension of the Bourne shell. This version has
many features which make it appear similar in some respects to the Korn shell,
but it is not a Korn shell clone (see
ksh(1)). This man page is not
intended to be a tutorial or a complete specification of the shell.
-i
flag is set), and the -c
option is not present, the shell is considered an interactive shell. An
interactive shell generally prompts before each command and handles
programming and command errors differently (as described below). When first
starting, the shell inspects argument 0, and if it begins with a dash
‘-’, the shell is also considered a login shell. This is
normally done automatically by the system when the user first logs in. A login
shell first reads commands (as if by using the “.” command) from
the files /etc/profile and
.profile in the user's home directory ($HOME), if they
exist. If the environment variable ENV
is set on entry
to a shell, or is set in the .profile of a login
shell, and either the shell is interactive, or the
posix
option is not set, the shell then performs
parameter and arithmetic expansion on the value of
ENV
, (these are described later) and if no errors
occurred, then reads commands from the file name that results. Note that no
error messages result from these expansions, to verify that
ENV
is correct, as desired, use:
eval printf '%s\\n'
“${ENV}”
ENV
appears to contain a command
substitution, which is not performed here, or if there were no expansions to
expand, the value of ENV
is used as the file name.
Therefore, a user should place commands that are to be executed
only at login time in the .profile file, and
commands that are executed for every shell inside the
ENV
file. To set the ENV
variable to some file, place the following line in your
.profile of your home directory
ENV=$HOME/.shinit; export
ENV
substituting for “.shinit” any filename you wish.
Since the ENV
file can be read for every invocation
of the shell, including shell scripts and non-interactive shells, the
following paradigm is useful for restricting commands in the
ENV
file to interactive invocations. Place commands
within the “case
” and
“esac
” below (these commands are
described later):
case $- in *i*) # commands for interactive use only ... esac
If command line arguments besides the options have been specified,
and neither -c
nor -s
was
given, then the shell treats the first argument as the name of a file from
which to read commands (a shell script). This also becomes
$0
and the remaining arguments are set as the
positional parameters of the shell ($1
,
$2
, etc). Otherwise, if -c
was given, then the first argument, which must exist, is taken to be a
string of sh
commands to execute. Then if any
additional arguments follow the command string, those arguments become
$0
, $1
, ... Otherwise, if
additional arguments were given (which implies that
-s
was set) those arguments become
$1
, $2
, ... If
$0
has not been set by the preceding processing, it
will be set to argv[0] as passed to the shell, which
will usually be the name of the shell itself. If -s
was given, or if neither -c
nor any additional
(non-option) arguments were present, the shell reads commands from its
standard input.
set
built-in, have a corresponding name that can
be used as an argument to the -o
option. The
set
-o
name is provided next
to the single letter option in the description below. Some options have only a
long name, they are described after the flag options, they are used with
-o
or +o
only, either on the
command line, or with the set
built-in command. Other
options described are for the command line only. Specifying a dash
“-
” turns the option on, while using a
plus “+
” disables the option. The
following options can be set from the command line and, unless otherwise
stated, with the set
built-in (described later).
-a
allexport-b
notify-C
noclobber-c
0
will be set from the
command_name operand if given, and the positional
parameters (1
, 2
, etc.)
set from the remaining argument operands, if any.
-c
is only available at invocation, it cannot be
set
, and there is no form using
“+
”.-E
emacs-V
if it had been set). (See the
Command Line Editing
section below.)-e
errexitif
, elif
,
while
, or until
, or if the
command is the left hand operand of an “&&” or
“||” operator, or if it is a pipeline (or simple command)
preceded by the “!” operator. With pipelines, only the
status of the entire pipeline (indicated by the last command it contains)
is tested when -e
is set to determine if the shell
should exit.-F
forksh
can be compiled to always
use fork(2) in which case
altering the -F
flag has no effect.-f
noglob-h
trackall-I
ignoreeof-i
interactive-L
local_linenoLINENO
when used within the function, to refer to
the line number defined such that first line of the function is line 1.
When reset, LINENO
in a function refers to the
line number within the file within which the definition of the function
occurs. This option defaults to “on” in this shell. For more
details see the section LINENO
below.-m
monitor-n
noexec-n
becomes set in an interactive shell, it will automatically be cleared just
before the next time the command line prompt (PS1
)
is written.-p
nopriv-p
is cleared,
those privileges can never be regained, however much the
-p
option is manipulated.-q
quietprofile-v
or -x
options
have been set, temporarily disable them before reading initialization
files, these being /etc/profile,
.profile, and the file specified by the
ENV
environment variable.-s
stdin-c
nor file arguments are present). If after
processing a command_string with the -c
option,
the shell has not exited, and the -s
option is
set, it will continue reading more commands from standard input. This
option has no effect when set or reset after the shell has already started
reading from the command_file, or from standard input. Note that the
-s
flag being set does not cause the shell to be
interactive.-u
nounset-u
.-V
vi-E
if it had been
set). (See the Command Line
Editing section below.)-v
verbose-X
xlockxtrace
(-x
) option to be sent to standard error as it
exists when the -X
option is enabled (regardless
of its previous state.) For example:
set -X 2>/tmp/trace-file
Each change (set or clear) to -X
is
also performed upon -x
, but not the
converse.
-x
xtrace$PS4
) before it is executed. Unless
-X
is set, “standard error” means
that which existed immediately before any redirections to be applied to
the command are performed. Useful for debugging.cd
command. In a non-interactive shell this
option has no effect.fc
in the
Built-ins section.) (Not
implemented.)POSIXLY_CORRECT
is present. That can be overridden
(set or reset) by the -o
option on the command
line. Currently this option controls whether (!posix) or not (posix) the
file given by the ENV
variable is read at startup
by a non-interactive shell. It also controls whether file descriptors
greater than 2 opened using the exec
built-in
command are passed on to utilities executed (“yes” in posix
mode), whether a colon (:) terminates the user name in tilde (~)
expansions other than in assignment statements (“no” in
posix mode), the format of the output of the kill
-l
command, where posix mode causes the names of
the signals be separated by either a single space or newline, and where
otherwise sufficient spaces are inserted to generate nice looking columns,
and whether the shell treats an empty brace-list compound statement as a
syntax error (expected by POSIX) or permits it. Such statements
“{ }” can be useful when defining dummy functions.
Lastly, in posix mode, only one “!” is permitted before a
pipeline.PS1
, PS2
, and
PS4
each time, before they are output. This option
should not be set until after the prompts have been set (or verified) to
avoid accidentally importing unwanted command substitutions from the
environment.-E
or
-V
, must be enabled for this to work.& && ( ) ; ;; ;&
| || <newline>
< > >| << >>
<& >& <<- <>
$
), backquote
(`
), and backslash (\
). The
backslash inside double quotes is historically weird, and serves to quote only
the following characters (and these not in all contexts):
$ ` " \
<newline>,
$'...'
)Enclosing characters in a matched pair of single quotes, with the
first immediately preceded by an unquoted dollar sign
($
) provides a quoting mechanism similar to single
quotes, except that within the sequence of characters, any backslash
(\
), is an escape character, which causes the
following character to be treated specially. Only a subset of the characters
that can occur in the string are defined after a backslash, others are
reserved for future definition, and currently generate a syntax error if
used. The escape sequences are modeled after the similar sequences in
strings in the C programming language, with some extensions.
The following characters are treated literally when following the escape character (backslash):
\ ' "
\\
” allows the escape
character (backslash) to appear in the string literally.
“\'
” allows a single quote character
into the string, such an escaped single quote does not terminate the quoted
string. “\"
” is for compatibility
with C strings, the double quote has no special meaning in a shell C-style
string, and does not need to be escaped, but may be.
A newline following the escape character is treated as a line continuation, like the same sequence in a double quoted string, or when not quoted – the two characters, the backslash escape and the newline, are removed from the input string.
The following characters, when escaped, are converted in a manner similar to the way they would be in a string in the C language:
a b e f n r t v
In addition to those there are 5 forms that need additional data,
which is obtained from the subsequent characters. An escape
(\
) followed by one, two or three, octal digits
(‘0’..‘7’) is processed to form an 8 bit
character value. If only one or two digits are present, the following
character must be something other than an octal digit. It is safest to
always use all 3 digits, with leading zeros if needed. If all three digits
are present, the first must be one of
‘0’..‘3’.
An escape followed by ‘x’ (lower case only) can be
followed by one or two hexadecimal digits
(‘0’..‘9’, ‘A’..‘F’,
or ‘a’..‘f’.) As with octal, if only one hex
digit is present, the following character must be something other than a hex
digit, so always giving 2 hex digits is best. However, unlike octal, it is
unspecified in the standard how many hex digits can be consumed. This
sh
takes at most two, but other shells will continue
consuming characters as long as they remain valid hex digits. Consequently,
users should ensure that the character following the hex escape sequence is
something other than a hex digit. One way to achieve this is to end the
$'...'
string immediately after the final hex digit,
and then, immediately start another, so
$'\x33'$'4...'
$'\x334'
There are two escape sequences beginning with
‘\u
’ or
‘\U
’. The former is followed by from 1
to 4 hex digits, the latter by from 1 to 8 hex digits. Leading zeros can be
used to pad the sequences to the maximum permitted length, to avoid any
possible ambiguity problem with the following character, and because there
are some shells that insist on exactly 4 (or 8) hex digits. These sequences
are evaluated to form the value of a Unicode code point, which is then
encoded into UTF-8 form, and entered into the string. (The code point should
be converted to the appropriate code point value for the corresponding
character in the character set given by the current locale, or perhaps the
locale in use when the shell was started, but is not... currently.) Not all
values that are possible to write are valid, values that specify (known)
invalid Unicode code points will be rejected, or simply produce
‘?’.
Lastly, as another addition to what is available in C, the escape character (backslash), followed by ‘c’ (lower case only) followed by one additional character, which must be an alphabetic character (a letter), or one of the following:
@ [ \ ] ^ _ ?
\c?
’ the value obtained is the
least significant 5 bits of the ASCII value of the character following the
‘\c
’ escape sequence. That is what is
commonly known as the “control” character obtained from the
given character. The escape sequence
‘\c?
’ yields the ASCII DEL character
(0x7F). Note that to obtain the ASCII FS character (0x1C) this way, (that is
control-\) the trailing ‘\
’ must be
escaped itself, and so for this one case, the full escape sequence is
“\c\\
”. The sequence
“\c\
X” where
‘X’ is some character other than
‘\
’ is reserved for future use, its
meaning is unspecified. In this sh
an error is
generated.
If any of the preceding escape sequences generate the value
‘\0’ (a NUL character) that character, and all that follow in
the same $'...'
string, are omitted from the
resulting word.
After the $'...'
string has had any
included escape sequences converted, it is treated as if it had been a
single quoted string.
! |
{ |
} |
case |
do |
done |
elif |
else |
esac |
fi |
for |
if |
in |
then |
until |
while |
Their meanings are discussed later.
alias
built-in command. Whenever a reserved word (see
above) may occur, and after checking for reserved words, the shell checks the
word to see if it matches an alias. If it does, it replaces it in the input
stream with its value. For example, if there is an alias called
“lf” with the value “ls -F”, then the input:
lf foobar
⟨return⟩
would become
ls -F foobar
⟨return⟩
Aliases provide a convenient way for naive users to create shorthands for commands without having to learn how to create functions with arguments. They can also be used to create lexically obscure code. This use is strongly discouraged.
=
value”
are stripped off, the value is expanded, as described below, and the
results are assigned to the environment of the simple command. Redirection
operators and their arguments (as described below) are stripped off and
saved for processing in step 3 below.=
value”
variable assignments recognized in item 1 affect the current shell.[n]redir-op
file
where redir-op is one of the redirection operators mentioned previously. A list of the possible redirections, and their meanings, follows.
The [n] is an optional number, as in
‘3
’ (not
‘[3]
’), that refers to a file
descriptor. If present it must occur unquoted, immediately before the
redirection operator, with no intervening white space, and becomes a part of
that operator. If file descriptor n was open prior to
the redirection, its previous use is closed.
All redirections have a single word file argument following the operator (white space is allowed between the redirection operator and file), though it is sometimes expressed as n2. That argument is expanded (see Word Expansions below) using tilde expansion, parameter expansion, arithmetic expansion, command substitution and quote removal to produce the path name (or file descriptor) to be used. No field splitting or pathname expansion takes place. In the list below, where the file is given as n2 the result of the expansions must be a number which refers to a suitable open file descriptor.
>
file>|
file-C
option.>>
file<
file<&
n2<& −
>&
n2>& −
<>
fileThe following redirection is often called a “here-document”.
[n ]<<
delimiter... here-doc-text ...
delimiter
The “here-doc-text” starts immediately after the next unquoted newline character following the here-document redirection operator. If there is more than one here-document redirection on the same line, then the text for the first (from left to right) is read first, and subsequent here-doc-text for later here-document redirections follows immediately after, until all such redirections have been processed.
All the text on successive lines up to the delimiter, which must
appear on a line by itself, with nothing other than an immediately following
newline, is saved away and made available to the command on standard input,
or file descriptor n if it is specified. If the delimiter as specified on
the initial line is quoted, then the here-doc-text is treated literally;
otherwise, the text is treated much like a double quoted string, except that
‘"
’ characters have no special
meaning, and are not escaped by ‘\
’,
and is subjected to parameter expansion, command substitution, and
arithmetic expansion as described in the
Word Expansions section below. If
the operator is <<-
instead of
<<
, then leading tabs in all lines in the
here-doc-text, including before the end delimiter, are stripped. If the
delimiter is not quoted, lines in here-doc-text that end with an unquoted
\
are joined to the following line, the
\
and following newline are simply removed while
reading the here-document, which thus guarantees that neither of those lines
can be the end delimiter.
It is a syntax error for the end of the input file (or string) to be reached before the delimiter is encountered.
When a shell function is executed, all of the shell positional
parameters (note: excluding 0
, which is a special,
not positional, parameter, and remains unchanged) are set to the arguments
of the shell function. The variables which are explicitly placed in the
environment of the command (by placing assignments to them before the
function name) are made local to the function and are set to the values
given, and exported for the benefit of programs executed with the function.
Then the command given in the function definition is executed. The
positional parameters, and local variables, are restored to their original
values when the command completes. This all occurs within the current shell,
and the function can alter variables, or other settings, of the shell, but
not the positional parameters nor their related special parameters.
Shell built-ins are executed internally to the shell, without spawning a new process.
Otherwise, if the command name doesn't match a function or
built-in, the command is searched for as a normal program in the file system
(as described in the next section). When a normal program is executed, the
shell runs the program, passing the arguments and the environment to the
program. If the program is not a normal executable file, and if it does not
begin with the “magic number” whose ASCII representation is
“#!
”, so
execve(2) returns
ENOEXEC
then) the shell will interpret the program
in a sub-shell. The child shell will reinitialize itself in this case, so
that the effect will be as if a new shell had been invoked to handle the
ad-hoc shell script, except that the location of hashed commands located in
the parent shell will be remembered by the child.
Note that previous versions of this document and the source code itself misleadingly and sporadically refer to a shell script without a magic number as a “shell procedure”.
PATH
in turn for the command. The value of the PATH
variable should be a series of entries separated by colons. Each entry
consists of a directory name. The current directory may be indicated
implicitly by an empty directory name, or explicitly by a single period.
If a directory searched contains an executable file with the same name as
the command given, the search terminates, and that program is
executed.If a command consists entirely of variable assignments then the exit status of the command is that of the last command substitution if any, otherwise 0.
If redirections are present, and any fail to be correctly performed, any command present is not executed, and an exit status of 2 is returned.
Unless otherwise stated, the exit status of a list is that of the last simple command executed by the list.
|
’, and optionally preceded by
the “!
” reserved word. Note that
‘|
’ is an operator, and so is recognized
anywhere it appears unquoted, it does not require surrounding white space or
other syntax elements. On the other hand
“!
” being a reserved word, must be
separated from adjacent words by white space (or other operators, perhaps
redirects) and is only recognized as the reserved word when it appears in a
command word position (such as at the beginning of a pipeline.)
The standard output of all but the last command in the sequence is connected to the standard input of the next command. The standard output of the last command is inherited from the shell, as usual, as is the standard input of the first command.
The format for a pipeline is:
[!] command1 [|
command2
...]
The standard output of command1 is connected to the standard input of command2. The standard input, standard output, or both of each command is considered to be assigned by the pipeline before any redirection specified by redirection operators that are part of the command are performed.
If the pipeline is not in the background (discussed later), the shell waits for all commands to complete.
The commands in a pipeline can either be simple commands, or one of the compound commands described below. The simplest case of a pipeline is a single simple command.
If the pipefail
option was set when a
pipeline was started, the pipeline status is the status of the last
(lexically last, i.e.: rightmost) command in the pipeline to exit with
non-zero exit status, or zero, if, and only if, all commands in the pipeline
exited with a status of zero. If the pipefail
option
was not set, which is the default state, the pipeline status is the exit
status of the last (rightmost) command in the pipeline, and the exit status
of any other commands in the pipeline is ignored.
If the reserved word “!
”
precedes the pipeline, the exit status becomes the logical NOT of the
pipeline status as determined above. That is, if the pipeline status is
zero, the exit status is 1; if the pipeline status is other than zero, the
exit status is zero. If there is no
“!
” reserved word, the pipeline status
becomes the exit status.
Because pipeline assignment of standard input or standard output or both takes place before redirection, it can be modified by redirection. For example:
$ command1 2>&1 |
command2
sends both the standard output and standard error of command1 to the standard input of command2.
Note that unlike some other shells, each process in the pipeline is a child of the invoking shell (unless it is a shell built-in, in which case it executes in the current shell — but any effect it has on the environment is wiped).
A pipeline is a simple case of an AND-OR-list (described below.) A
;
or ⟨newline⟩ terminator causes the
preceding pipeline, or more generally, the preceding AND-OR-list to be
executed sequentially; that is, the shell executes the commands, and waits
for them to finish before proceeding to following commands. An
&
terminator causes asynchronous (background)
execution of the preceding AND-OR-list (see the next paragraph below). The
exit status of an asynchronous AND-OR-list is zero. The actual status of the
commands, after they have completed, can be obtained using the
wait
built-in command described later.
&
&
), the shell executes the command
asynchronously — that is, the shell does not wait for the command to
finish before executing the next command.
The format for running a command in background is:
command1 &
[command2 &
...]
If the shell is not interactive, the standard input of an
asynchronous command is set to /dev/null. The
process identifier of the most recent command started in the background can
be obtained from the value of the special parameter
“!
” (see
Special Parameters) provided it
is accessed before the next asynchronous command is started.
The commands in a list are executed in the order they are written.
If command is followed by an ampersand, the shell starts the command and
immediately proceeds to the next command; otherwise it waits for the command
to terminate before proceeding to the next one. A newline is equivalent to a
‘;
’ when no other operator is present,
and the command being input could syntactically correctly be terminated at
the point where the newline is encountered, otherwise it is just
whitespace.
&&
” and
“||
” are AND-OR list operators. After
executing the commands that precede the
“&&
” the subsequent command is
executed if and only if the exit status of the preceding command(s) is zero.
“||
” is similar, but executes the
subsequent command if and only if the exit status of the preceding command is
nonzero. If a command is not executed, the exit status remains unchanged and
the following AND-OR list operator (if any) uses that status.
“&&
” and
“||
” both have the same priority. Note
that these operators are left-associative, so
true || echo bar && echo
baz
if
,
while
, until
,
for
, case
if
command is
if
listthen
list [elif
listthen
list ] ... [else
list ]fi
The first list is executed, and if the exit status of that list is
zero, the list following the then
is executed.
Otherwise the list after an elif
(if any) is
executed and the process repeats. When no more elif
reserved words, and accompanying lists, appear, the list after the
else
reserved word, if any, is executed.
The syntax of the while
command is
while
listdo
listdone
The two lists are executed repeatedly while the exit status of the
first list is zero. The until
command is similar,
but has the word until
in place of
while
, which causes it to repeat until the exit
status of the first list is zero.
The syntax of the for
command is
for
variable [in
word ... ]do
listdone
The words are expanded, or "$@"
if in
(and the following words) is not present, and
then the list is executed repeatedly with the variable set to each word in
turn. If in
appears after the variable, but no words
are present, the list is not executed, and the exit status is zero.
do
and done
may be replaced
with ‘{
’ and
‘}
’, but doing so is non-standard and
not recommended.
The syntax of the break
and
continue
commands is
break
[num ]continue
[num ]
break
terminates the
num innermost for
,
while
, or until
loops.
continue
breaks execution of the
num-1 innermost for
,
while
, or until
loops, and
then continues with the next iteration of the enclosing loop. These are
implemented as special built-in commands. The parameter
num, if given, must be an unsigned positive integer
(greater than zero). If not given, 1 is used.
The syntax of the case
command is
case
wordin
[(
] pattern)
[list ];&
[(
] pattern)
[list ];;
...esac
The pattern can actually be one or more patterns (see Shell Patterns described later), separated by “|” characters.
word is expanded and matched against each
pattern in turn, from first to last, with each pattern
being expanded just before the match is attempted. When a match is found,
pattern comparisons cease, and the associated list, if
given, is evaluated. If the list is terminated with
“;&
” execution then falls through
to the following list, if any, without evaluating its pattern, or attempting
a match. When a list terminated with
“;;
” has been executed, or when
esac
is reached, execution of the
case
statement is complete. The exit status is that
of the last command executed from the last list evaluated, if any, or zero
otherwise.
(
list)
{
list; }
Note that while parentheses are operators, and do not require any extra syntax, braces are reserved words, so the opening brace must be followed by white space (or some other operator), and the closing brace must occur in a position where a new command word might otherwise appear.
The first of these executes the commands in a sub-shell. Built-in
commands grouped into a (
list)
will not affect the current shell. The second form does not fork another
shell so is slightly more efficient, and allows for commands which do affect
the current shell. Grouping commands together this way allows you to
redirect their output as though they were one program:
{ echo -n "hello " ; echo "world" ; } > greeting
Note that “}
” must follow a
control operator (here, “;
”) so that
it is recognized as a reserved word and not as another command argument.
name()
command [redirect
...]
A function definition is an executable statement; when executed it installs a function named name and returns an exit status of zero. The command is normally a list enclosed between “{” and “}”. The standard syntax also allows the command to be any of the other compound commands, including a sub-shell, all of which are supported. As an extension, this shell also allows a simple command (or even another function definition) to be used, though users should be aware this is non-standard syntax. This means that
l() ls "$@"
ls
command.
If the optional redirect, (see Redirections), which may be of any of the normal forms, is given, it is applied each time the function is called. This means that a simple “Hello World” function might be written (in the extended syntax) as:
hello() cat <<EOF Hello World! EOF
To be correctly standards conforming this should be re-written as:
hello() { cat; } <<EOF Hello World! EOF
Note the distinction between those forms, and
hello() { cat <<EOF Hello World! EOF }
which reads and processes the here-document each time the shell executes the function, and which applies that input only to the cat command, not to any other commands that might appear in the function.
Variables may be declared to be local to a function by using the
local
command. This should usually appear as the
first statement of a function, though local
is an
executable command which can be used anywhere in a function. See
Built-ins below for its definition.
The function completes after having executed
command with exit status set to the status returned by
command. If command is a
compound-command it can use the return
command (see
Built-ins below) to finish before
completing all of command.
name=
value
Variables set by the user must have a name consisting solely of alphabetics, numerics, and underscores — the first of which must not be numeric. A parameter can also be denoted by a number or a special character as explained below.
set
built-in can
also be used to set or reset them, and shift
can be
used to manipulate the list.
To refer to the 10th (and later) positional parameters, the form
${
n}
must be used. Without the braces, a digit following “$” can
only refer to one of the first 9 positional parameters, or the special
parameter 0
. The word
“$10
” is treated identically to
“${1}0
”.
*
IFS
variable, or by a ⟨space⟩ if
IFS
is unset.@
$@
is double-quoted. What this basically means,
for example, is if $1
is “abc” and
$2
is “def ghi”, then
"$@"
expands to the two arguments:
"abc" "def ghi
"
#
?
-
(hyphen, or minus)$
$
as its parent.!
!
” will be
unset. Once set, the value of “!
”
will be retained until another background command is started.0
(zero)Tilde expansions, parameter expansions, command substitutions,
arithmetic expansions, and quote removals that occur within a single word
expand to a single field. It is only field splitting or pathname expansion
that can create multiple fields from a single word. The single exception to
this rule is the expansion of the special parameter
@
within double quotes, as was described above.
The order of word expansion is:
IFS
variable is null.-f
is in
effect).The $ character is used to introduce parameter expansion, command substitution, or arithmetic evaluation.
HOME
variable (the current user's home directory).
In variable assignments, an unquoted tilde immediately after the assignment operator (=), and each unquoted tilde immediately after an unquoted colon in the value to be assigned is also subject to tilde expansion as just stated.
${expression}
where expression consists of all characters
until the matching ‘}
’. Any
‘}
’ escaped by a backslash or within a
quoted string, and characters in embedded arithmetic expansions, command
substitutions, and variable expansions, are not examined in determining the
matching ‘}
’.
The simplest form for parameter expansion is:
${parameter}
The value, if any, of parameter is substituted.
The parameter name or symbol can be enclosed in braces, which are optional in this simple case, except for positional parameters with more than one digit or when parameter is followed by a character that could be interpreted as part of the name. If a parameter expansion occurs inside double quotes:
@
.In addition, a parameter expansion where braces are used, can be
modified by using one of the following formats. If the
‘:
’ is omitted in the following
modifiers, then the test in the expansion applies only to unset parameters,
not null ones.
${
parameter:-
word}
${
parameter:=
word}
${
parameter:?
[word]}
${
parameter:+
word}
${
#
parameter}
The following four varieties of parameter expansion provide for
substring processing. In each case, pattern matching notation (see
Shell Patterns), rather than
regular expression notation, is used to evaluate the patterns. If parameter
is *
or @
, the result of the
expansion is unspecified. Enclosing the full parameter expansion string in
double quotes does not cause the following four varieties of pattern
characters to be quoted, whereas quoting characters within the braces has
this effect.
${
parameter%
word}
%
’ character, it must be
quoted.${
parameter%%
word}
%%
” pattern operator only produces
different results from the “%
”
operator when the pattern contains at least one unquoted
‘*
’.${
parameter#
word}
#
’ character, it must be
quoted.${
parameter##
word}
#
”
pattern operator as “%%
” has with
“%
”.$(
list)
or the older (“backquoted”) version, which is best avoided:
`
list`
See the section Complex
Commands above for the definition of list
.
The shell expands the command substitution by executing the
list in a sub-shell environment and replacing the
command substitution with the standard output of the
list after removing any sequence of one or more
⟨newline⟩s from the end of the substitution. (Embedded
⟨newline⟩s before the end of the output are not removed;
however, during field splitting, they may be used to separate fields (as
spaces usually are) depending on the value of IFS
and any quoting that is in effect.)
Note that if a command substitution includes commands to be run in
the background, the sub-shell running those commands will only wait for them
to complete if an appropriate wait
command is
included in the command list. However, the shell in which the result of the
command substitution will be used will wait for both the sub-shell to exit
and for the file descriptor that was initially standard output for the
command substitution sub-shell to be closed. In some circumstances this
might not happen until all processes started by the command substitution
have finished.
$((
expression))
The expression in an arithmetic expansion is treated as if it were in double quotes, except that a double quote character inside the expression is just a normal character (it quotes nothing.) The shell expands all tokens in the expression for parameter expansion, command substitution, and quote removal (the only quoting character is the backslash ‘\’, and only when followed by another ‘\’, a dollar sign ‘$’, a backquote ‘`’ or a newline.)
Next, the shell evaluates the expanded result as an arithmetic expression and substitutes the calculated value of that expression.
Arithmetic expressions use a syntax similar to that of the C
language, and are evaluated using the
‘intmax_t
’ data type (this is an
extension to POSIX, which requires only
‘long
’ arithmetic.) Shell variables
may be referenced by name inside an arithmetic expression, without needing a
“$” sign. Variables that are not set, or which have an empty
(null string) value, used this way evaluate as zero (that is,
“x” in arithmetic, as an R-Value, is evaluated as
“${x:-0}”) unless the sh
-u
flag is set, in which case a reference to an
unset variable is an error. Note that unset variables used in the ${var}
form expand to a null string, which might result in syntax errors.
Referencing the value of a variable which is not numeric is an error.
All of the C expression operators applicable to integers are supported, and operate as they would in a C expression. Use white space, or parentheses, to disambiguate confusing syntax, otherwise, as in C, the longest sequence of consecutive characters which make a valid token (operator, variable name, or number) is taken to be that token, even if the token designated cannot be used and a different interpretation could produce a successful parse. This means, as an example, that “a+++++b” is parsed as the gibberish sequence “a ++ ++ + b”, rather than as the valid alternative “a ++ + ++ b”. Similarly, separate the ‘,’ operator from numbers with white space to avoid the possibility of confusion with the decimal indicator in some locales (though fractional, or floating-point, numbers are not supported in this implementation.)
It should not be necessary to state that the C operators which operate on, or produce, pointer types, are not supported. Those include unary “*” and “&” and the struct and array referencing binary operators: “.”, “->” and “[”.
$@
” even if it did,
for field splitting and multiple fields can result.
The shell treats each character of the IFS
as a delimiter and uses the delimiters to split the results of parameter
expansion and command substitution into fields.
Non-whitespace characters in IFS
are
treated strictly as parameter separators. So adjacent non-whitespace
IFS
characters will produce empty parameters. On the
other hand, any sequence of whitespace characters that occur in
IFS
(known as IFS
whitespace) can occur, leading and trailing IFS
whitespace, and any IFS
whitespace surrounding a non
whitespace IFS
delimiter, is removed. Any sequence
of IFS
whitespace characters without a
non-whitespace IFS
delimiter acts as a single field
separator.
If IFS
is unset it is assumed to contain
space, tab, and newline, all of which are IFS
whitespace characters. If IFS
is set to a null
string, there are no delimiters, and no field splitting occurs.
-f
flag is set, file name generation is
performed after word splitting is complete. Each word is viewed as a series of
patterns, separated by slashes. The process of expansion replaces the word
with the names of all existing files whose names can be formed by replacing
each pattern with a string that matches the specified pattern. There are two
restrictions on this: first, a pattern cannot match a string containing a
slash, and second, a pattern cannot match a string starting with a period
unless the first character of the pattern is a period. The next section
describes the patterns used for both Pathname Expansion and the
case
command.
An asterisk (“*”) matches any string of characters. A question mark (“?”) matches any single character. A left bracket (“[”) introduces a character class. The end of the character class is indicated by a right bracket (“]”); if this “]” is missing then the “[” matches a “[” rather than introducing a character class. A character class matches any of the characters between the square brackets. A named class of characters (see wctype(3)) may be specified by surrounding the name with (“[:”) and (“:]”). For example, (“[[:alpha:]]”) is a shell pattern that matches a single letter. A range of characters may be specified using a minus sign (“−”). The character class may be complemented by making an exclamation mark (“!”) the first character of the character class.
To include a “]” in a character class, make it the first character listed (after the “!”, if any). To include a “−”, make it the first (after !) or last character listed. If both “]” and “−” are to be included, the “]” must be first (after !) and the “−” last, in the character class.
:
[arg ...].
filePATH
variable if its name does not contain a
directory separator (‘/’). The
return
command (see below) can be used for a
premature return from the sourced file.
The POSIX standard has been unclear on how loop control keywords (break and continue) behave across a dot command boundary. This implementation allows them to control loops surrounding the dot command, but obviously such behavior should not be relied on. It is now permitted by the standard, but not required.
alias
[name[=
string
...]]=
string
is specified, the shell defines the alias name with
value string. If just name is
specified, the value of the alias name is printed.
With no arguments, the alias
built-in prints the
names and values of all defined aliases (see
unalias
).bg
[job ...]command
[-pVv
] command
[arg ...]-p
PATH
that
guarantees to find all the standard utilities.-V
type
built-in.-v
cd
[-Pe
] [directory
[replace]]$HOME
).
If replace is specified, then the new directory name
is generated by replacing the first occurrence of the string
directory in the current directory name with
replace. Otherwise if
directory is
‘-
’, then the current working
directory is changed to the previous current working directory as set in
OLDPWD
. Otherwise if an entry for
CDPATH
appears in the environment of the
cd
command or the shell variable
CDPATH
is set and the directory name does not
begin with a slash, and its first (or only) component isn't dot or dot
dot, then the directories listed in CDPATH
will be
searched for the specified directory. The format of
CDPATH
is the same as that of
PATH
.
The -P
option (which is the
unalterable default in this sh
) instructs the
shell to change to the directory specified (or determined) and if
successful update PWD
with the new physical
directory path. That is the path name, not traversing any symbolic
links, of the altered working directory of the shell.
The -e
option alters the
interpretation of the exit status. cd
will exit
with status 0 if successful. If the directory was successfully changed,
but PWD
was unable to be updated,
cd
will exit with status 1 if the
-e
option was given, and status 0 otherwise.
Upon any other error, including usage errors, and failing to
successfully change directory, cd
will exit with
status 2.
When the directory changes, and PWD
is
updated, the variable OLDPWD
is set to the
working directory (Ns PWD
) as it was before the
change.
Some shells also support a -L
option,
which instructs the shell to update PWD
with the
logical path and to change the current directory accordingly. This is
not supported.
In an interactive shell, or if the
posix
option is set, the
cd
command will print out the name of the
directory that it actually switched to (that is, the pathname passed to
the successful chdir(2)
system call) if this is different from the name
that the user gave, or if the cdprint
option is
set. The destination may be different because a non-empty element of the
CDPATH
mechanism was used, or because the
replace argument was used, or because the
directory parameter was specified as
“-”.
eval
string ...exec
[command [arg ...]]exec
command are marked as permanent, so that they
are not undone when the exec
command finishes.
When the posix
option is not set, file descriptors
created via such redirections are marked close-on-exec (see
open(2)
O_CLOEXEC
or
fcntl(2)
F_SETFD /
FD_CLOEXEC
),
unless the descriptors refer to the standard input, output, or error (file
descriptors 0, 1, 2). Traditionally Bourne-like shells (except
ksh(1)), made those file
descriptors available to exec'ed processes. To be assured the
close-on-exec setting is off, redirect the descriptor to (or from) itself,
either when invoking a command for which the descriptor is wanted open, or
by using exec
(perhaps the same
exec
as opened it, after the open) to leave the
descriptor open in the shell and pass it to all commands invoked
subsequently. Alternatively, see the fdflags
command below, which can set, or clear, this, and other, file descriptor
flags.exit
[exitstatus]export
[-nx
] name[=value] ...export
[-x
] [-p
[name ...]]export
-q
[-x
] name
...-n
the specified names are un-exported. Variables
can also be un-exported using the unset
built in
command. With -x
(exclude) the specified names are
marked not to be exported, and any that had been exported, will be
un-exported. Later attempts to export the variable will be refused. Note
this does not prevent explicitly exporting a variable to a single command,
script or function by preceding that command invocation by a variable
assignment to that variable, provided the variable is not also read-only.
That is
export -x FOO # FOO will now not be exported by default export FOO # this command will fail (non-fatally) FOO=some_value my_command
still passes the value
(FOO=some_value
) to
my_command
through the environment.
The shell allows the value of a variable to be set at the same time it is exported (or unexported, etc) by writing
export [-nx]
name=value
With no arguments the export command lists the names of all
set exported variables, or if -x
was given, all
set variables marked not for export. With the -p
option specified, the output will be formatted suitably for
non-interactive use, and unset variables are included. When
-p
is given, variable names, but not values, may
also be given, in which case output is limited to the variables
named.
With -q
and a list of variable names,
the export
command will exit with status 0 if
all the named variables have been marked for export, or 1 if any are not
so marked. If -x
is also given, the test is
instead for variables marked not to be exported.
Other than with -q
, the
export
built-in exits with status 0, unless an
attempt is made to export a variable which has been marked as
unavailable for export, in which cases it exits with status 1. In all
cases if an invalid option, or option combination, is given, or an
invalid variable name is present, export
will
write a message to the standard error output, and exit with a non-zero
status. A non-interactive shell will terminate.
Note that there is no restriction upon exporting, or un-exporting, read-only variables. The no-export flag can be reset by unsetting the variable and creating it again – provided the variable is not also read-only.
fc
[-e
editor]
[first [last]]fc
-l
[-nr
]
[first [last]]fc
-s
[old=new]
[first]fc
built-in lists, or edits and re-executes,
commands previously entered to an interactive shell.
-e
editorPATH
variable. The
value in the FCEDIT
variable is used as a
default when -e
is not specified. If
FCEDIT
is null or unset, the value of the
EDITOR
variable is used. If
EDITOR
is null or unset,
ed(1) is used as the
editor.-l
(ell)-r
, with each command preceded
by the command number.-n
-l
.-r
-l
) or edited (with neither
-l
nor -s
).-s
HISTSIZE
variable. The value of
first or last or both are
one of the following:
+
]number-l
option.-
number=
new
operand is not also specified with -s
, the
string form of the first operand cannot contain an embedded equal
sign.The following environment variables affect the execution of
fc
:
fg
[job]fdflags
[-v
] [fd ...]fdflags
[-v
] -s
flags fd [...]-v
argument
enables verbose printing, printing flags that are also off, and the flags
of the file descriptor being set after setting. The
-s
flag interprets the flags
argument as a comma separated list of file descriptor flags, each preceded
with a “+” or a “−” indicating to set
or clear the respective flag. Valid flags are:
append
, async
,
sync
, nonblock
,
fsync
, dsync
,
rsync
, direct
,
nosigpipe
, and cloexec
.
Unique abbreviations of these names, of at least 2 characters, may be used
on input. See fcntl(2) and
open(2) for more
information.getopts
optstring vargetopts
command, not to be confused with
the Bell Labs–derived
getopt(1).
The first argument should be a series of letters, each of which may be optionally followed by a colon to indicate that the option requires an argument. The variable specified is set to the parsed option.
The getopts
command deprecates the
older getopt(1) utility
due to its handling of arguments containing whitespace.
The getopts
built-in may be used to
obtain options and their arguments from a list of parameters. When
invoked, getopts
places the value of the next
option from the option string in the list in the shell variable
specified by var and its index in the shell
variable OPTIND
. When the shell is invoked,
OPTIND
is initialized to 1. For each option that
requires an argument, the getopts
built-in will
place it in the shell variable OPTARG
. If an
option is not allowed for in the optstring, then
OPTARG
will be unset.
optstring is a string of recognized
option letters (see
getopt(3)). If a letter is
followed by a colon, the option is expected to have an argument which
may or may not be separated from it by whitespace. If an option
character is not found where expected, getopts
will set the variable var to a
‘?
’;
getopts
will then unset
OPTARG
and write output to standard error. By
specifying a colon as the first character of
optstring all errors will be ignored.
A nonzero value is returned when the last option is reached.
If there are no remaining arguments, getopts
will set var to the special option,
“--
”, otherwise, it will set
var to
‘?
’.
The following code fragment shows how one might process the
arguments for a command that can take the options
-a
and -b
, and the
option -c
, which requires an argument.
while getopts abc: f do case $f in a | b) flag=$f;; c) carg=$OPTARG;; \?) echo $USAGE; exit 1;; esac done shift $((OPTIND - 1))
This code will accept any of the following as equivalent:
cmd -acarg file file cmd -a -c arg file file cmd -carg -a file file cmd -a -carg -- file file
hash
[-rv
] [command ...]hash
command prints out the contents of this table. Entries which have not been
looked at since the last cd
command are marked
with an asterisk; it is possible for these entries to be invalid.
With arguments, the hash
command
removes the specified commands from the hash table (unless they are
functions) and then locates them. With the -v
option, hash prints the locations of the commands as it finds them. The
-r
option causes the hash command to delete all
the entries in the hash table except for functions.
inputrc
filejobid
[-g
|-j
|-p
]
[job]%
’ forms, or the process id of the
job leader (“$!
” if the job was
created in the background.)
If one of the flags is given, then instead of the list of
process identifiers, the jobid
command
prints:
-g
-j
%
n”
notation, where n is a number) is printed.-p
These flags are mutually exclusive.
jobid
exits with status 2 if there is
an argument error, status 1, if with -g
the job
had no separate process group, or with -p
there
is no process group leader (should not happen), and otherwise exits with
status 0.
jobs
[-l
|-p
] [job
...]With the -l
flag the output is in a
longer form, with the process identifiers of each process (run from the
top level, as in a pipeline), and the status of each process, rather
than the job status.
With the -p
flag, the output contains
only the process identifier of the lead process.
In an interactive shell, each job shown as completed in the
output from the jobs command is implicitly waited for, and is removed
from the jobs table, never to be seen again. In an interactive shell,
when a background job terminates, the jobs
command (with that job as an argument) is implicitly run just before
outputting the next PS1 command prompt, after the job terminated. This
indicates that the job finished, shows its status, and cleans up the job
table entry for that job. Non-interactive shells need to execute
wait
commands to clean up terminated background
jobs.
local
[-INx
] [variable |
-] ...local
declaration, restored when the function
terminates.
With the -N
flag, variables made
local, are unset initially inside the function. Unless the
-x
flag is also given, such variables are also
unexported. The -I
flag, which is the default in
this shell, causes the initial value and exported attribute of local
variables to be inherited from the variable with the same name in the
surrounding scope, if there is one. If there is not, the variable is
initially unset, and not exported. The -N
and
-I
flags are mutually exclusive, if both are
given, the last specified applies. The read-only and unexportable
attributes are always inherited, if a variable with the same name
already exists.
The -x
flag (lower case) causes the
local variable to be exported, while the function runs, unless it has
the unexportable attribute. This can also be accomplished by using the
export
command, giving the same
variable names, after the
local
command.
Making an existing read-only variable local is possible, but
pointless. If an attempt is made to assign an initial value to such a
variable, the local
command fails, as does any
later attempted assignment. If the readonly
command is applied to a variable that has been declared local, the
variable cannot be (further) modified within the function, or any other
functions it calls, however when the function returns, the previous
status (and value) of the variable is returned.
Values may be given to local variables on the
local
command line in a similar fashion as used
for export
and readonly
.
These values are assigned immediately after the initialization described
above. Note that any variable references on the command line will have
been expanded before local
is executed, so
expressions like
local -N X=${X}
are well defined, first $X is expanded, and then the command run is
local -N
X=old-value-of-X
After arranging to preserve the old value and attributes, of
X
(“old-value-of X”)
local
unsets X
,
unexports it, and then assigns the “old-value-of-X” to
X
.
The shell uses dynamic scoping, so that if you make the
variable x
local to function
f
, which then calls function
g
, references to the variable
x
made inside g
will
refer to the variable x
declared inside
f
, not to the global variable named
x
.
Another way to view this, is as if the shell just has one
flat, global, namespace, in which all variables exist. The
local
command conceptually copies the
variable(s) named to unnamed temporary variables, and when the function
ends, copies them back again. All references to the variables reference
the same global variables, but while the function is active, after the
local
command has run, the values and attributes
of the variables might be altered, and later, when the function
completes, be restored.
Note that the positional parameters 1
,
2
, ... (see
Positional Parameters),
and the special parameters #
,
*
and @
(see
Special Parameters), are
always made local in all functions, and are reset inside the function to
represent the options and arguments passed to the function. Note that
$0
however retains the value it had outside the
function, as do all the other special parameters.
The only special parameter that can optionally be made local
is “-
”. Making
“-
” local causes any shell options
that are changed via the set command inside the function to be restored
to their original values when the function returns. If
-X
option is altered after
“-
” has been made local, then when
the function returns, the previous destination for
xtrace
output (as of the time of the
local
command) will also be restored. If any of
the shell's magic variables (those which return a value which may vary
without the variable being explicitly altered, e.g.:
SECONDS
or HOSTNAME
) are
made local in a function, they will lose their special properties when
set within the function, including by the local
command itself (if not to be set in the function, there is little point
in making a variable local) but those properties will be restored when
the function returns.
It is an error to use local
outside
the scope of a function definition. When used inside a function, it
exits with status 0, unless an undefined option is used, or an attempt
is made to assign a value to a read-only variable.
Note that either -I
or
-N
should always be used, or variables made
local should always be given a value, or explicitly unset, as the
default behavior (inheriting the earlier value, or starting unset after
local
) differs amongst shell implementations.
Using “local -
” is an extension
not implemented by most shells.
See the section LINENO below
for details of the effects of making the variable
LINENO
local.
pwd
[-LP
]-L
is specified
the cached value (initially set from PWD
) is
checked to see if it refers to the current directory; if it does the value
is printed. Otherwise the current directory name is found using
getcwd(3). The environment
variable PWD
is set to the printed value.
The default is pwd
-L
, but note that the built-in
cd
command doesn't support the
-L
option and will cache (almost) the absolute
path. If cd
is changed (as unlikely as that is),
pwd
may be changed to default to
pwd
-P
.
If the current directory is renamed and replaced by a symlink
to the same directory, or the initial PWD
value
followed a symbolic link, then the cached value may not be the absolute
path.
The built-in command may differ from the program of the same
name because the program will use PWD
and the
built-in uses a separately cached value.
read
[-p
prompt]
[-r
] variable
[...]-p
option is specified and the standard input is a
terminal. Then a line is read from the standard input. The trailing
newline is deleted from the line and the line is split as described in the
field splitting section of the Word
Expansions section above, and the pieces are assigned to the variables
in order. If there are more pieces than variables, the remaining pieces
(along with the characters in IFS
that separated
them) are assigned to the last variable. If there are more variables than
pieces, the remaining variables are assigned the null string. The
read
built-in will indicate success unless EOF is
encountered on input, in which case failure is returned.
By default, unless the -r
option is
specified, the backslash “\” acts as an escape character,
causing the following character to be treated literally. If a backslash
is followed by a newline, the backslash and the newline will be
deleted.
readonly
name[=value] ...readonly
[-p
[name ...]]readonly
-q
name ...readonly name=value
With no arguments the readonly
command
lists the names of all set read only variables. With the
-p
option specified, the output will be
formatted suitably for non-interactive use, and unset variables are
included. When the -p
option is given, a list of
variable names (without values) may also be specified, in which case
output is limited to the named variables.
With the -q
option, the
readonly
command tests the read-only status of
the variables listed and exits with status 0 if all named variables are
read-only, or with status 1 if any are not read-only.
Other than as specified for -q
the
readonly
command normally exits with status 0.
In all cases, if an unknown option, or an invalid option combination, or
an invalid variable name, is given; or a variable which was already
read-only is attempted to be set; the exit status will not be zero, a
diagnostic message will be written to the standard error output, and a
non-interactive shell will terminate.
return
[n]The POSIX standard says that the results of
return
outside a function or a dot command are
unspecified. This implementation treats such a return as a no-op with a
return value of 0 (success, true). Use the exit
command instead, if you want to return from a script or exit your
shell.
set
[{ -options
| +options
|
-- }
] arg ...set
command performs four different functions.
With no arguments, it lists the values of all shell variables.
With a single option of either
“-o
” or
“+o
” set
outputs the current values of the options. In the
-o
form, all options are listed, with their
current values. In the +o
form, the shell
outputs a string that can later be used as a command to reset all
options to their current values.
If options are given, it sets the specified option flags, or
clears them as described in the
Argument List
Processing section. In addition to the options listed there, when
the “option name” given to set
-o
is default
all of the
options are reset to the values they had immediately after
sh
initialization, before any startup scripts,
or other input, had been processed. While this may be of use to users or
scripts, its primary purpose is for use in the output of
“set
+o
”,
to avoid that command needing to list every available option. There is
no +o default
.
The fourth use of the set
command is
to set the values of the shell's positional parameters to the specified
arguments. To change the positional parameters without changing any
options, use “--” as the first argument to
set
. If no following arguments are present, the
set
command will clear all the positional
parameters (equivalent to executing “shift
$#
”.) Otherwise the following arguments become
$1
, $2
, ..., and
$#
is set to the number of arguments
present.
setvar
variable valuevariable=value
rather than using setvar
.
setvar
is intended to be used in functions that
assign values to variables whose names are passed as parameters.)shift
[n]shift
sets the value of $1
to the previous value of $2
, the value of
$2
to the previous value of
$3
, and so on, decreasing the value of
$#
by one. The shift count must be less than or
equal to the number of positional parameters (
“$#
”) before the shift.specialvar
variable ...sh
, could be treated as a
special variable, then cause that variable to be
made special, undoing any effects of an earlier
unset
or assignment to the variable. If all
variables given are recognized special variables in
this sh
the specialvar
command will exit with status 0, otherwise 1. Invalid usage will result in
an exit status of 2.
Note that all variables capable of being special are created that way, this command is not required to cause that to happen. However should such a variable be imported from the environment, that will cause (for those special variables so designated) the special effects for that variable to be lost. Consequently, as the contents of the environment cannot be controlled, any script which desires to make use of the properties of most of the special variables should use this command, naming the variables required, to ensure that their special properties are available.
times
The first output line gives the CPU and system times consumed by the shell itself. The second line gives the accumulated times for children of this shell (and their descendants) which have exited, and then been successfully waited for by the relevant parent. See times(3) for more information.
times
has no parameters, and exits
with an exit status of 0 unless an attempt is made to give it an
option.
trap
action signal ...trap
-
trap
[-l
]trap
[-p
] signal ...trap
N signal ...Cause the shell to parse and execute action when any of the
specified signals are received. The signals are specified by signal
number or as the name of the signal. If signal is
0
or its equivalent,
EXIT
, the action is executed when the shell
exits. The action may be a null (empty) string,
which causes the specified signals to be ignored. With
action set to
‘-
’ the specified signals are set
to their default actions. If the first signal is
specified in its numeric form, then action can be
omitted to achieve the same effect. This archaic, but still standard,
form should not be relied upon, use the explicit
‘-
’ action. If no signals are
specified with an action of ‘-
’,
all signals are reset.
When the shell forks off a sub-shell, it resets trapped (but
not ignored) signals to the default action. On non-interactive shells,
the trap
command has no effect on signals that
were ignored on entry to the shell. On interactive shells, the
trap
command will catch or reset signals ignored
on entry.
Issuing trap
with option
-l
will print a list of valid signal names.
trap
without any arguments causes it to write a
list of signals and their associated non-default actions to the standard
output in a format that is suitable as an input to the shell that
achieves the same trapping results. With the -p
flag, trap prints the same information for the signals specified, or if
none are given, for all signals, including those where the action is the
default. These variants of the trap command may be executed in a
sub-shell (such as in a command substitution), provided they appear as
the sole, or first, command in that sub-shell, in which case the state
of traps from the parent of that sub-shell is reported.
Examples:
trap
List trapped signals and their corresponding actions.
trap -l
Print a list of valid signals.
trap '' INT QUIT tstp
30
Ignore signals INT QUIT TSTP USR1.
trap date INT
Run the “date” command (print the date) upon receiving signal INT.
trap HUP INT
Run the “HUP” command, or function, upon receiving signal INT.
trap 1 2
Reset the actions for signals 1 (HUP) and 2 (INT) to their defaults.
traps=$(trap -p) # more commands ... trap 'action' SIG # more commands ... eval "$traps"
Save the trap status, execute commands, changing some traps,
and then reset all traps to their values at the start of the sequence.
The -p
option is required in the first command
here, or any signals that were previously untrapped (in their default
states) and which were altered during the intermediate code, would not
be reset by the final eval
.
type
[name ...]ulimit
[-H
|-S
]
[-a
| -btfdscmlrpnv
[value]]If neither -H
nor
-S
is specified, the soft limit is displayed or
both limits are set. If both are specified, the last one wins.
The limit to be interrogated or set, then, is chosen by specifying any one of these flags:
-a
-b
-c
-d
-f
-l
-m
-n
-p
-r
-s
-t
-v
If none of these is specified, it is the limit on file size that is shown or set. If value is specified, the limit is set to that number; otherwise the current limit is displayed.
Limits of an arbitrary process can be displayed or set using the sysctl(8) utility.
umask
[-S
] [mask]-S
a symbolic form is used instead of an octal
number.unalias
[-a
] [name]-a
is specified, all aliases are removed.unset
[-efvx
] name ...-v
is specified, the specified variables are
unset and unexported. Readonly variables cannot be unset. If
-f
is specified, the specified functions are
undefined. If -e
is given, the specified variables
are unexported, but otherwise unchanged, alternatively, if
-x
is given, the exported status of the variable
will be retained, even after it is unset.
If no flags are provided -v
is
assumed. If -f
is given with one of the other
flags, then the named variables will be unset, or unexported, and
functions of the same names will be undefined. The
-e
and -x
flags both
imply -v
. If -e
is
given, the -x
flag is ignored.
The exit status is 0, unless an attempt was made to unset a readonly variable, in which case the exit status is 1. It is not an error to unset (or undefine) a variable (or function) that is not currently set (or defined.)
wait
[-n
] [-p
var] [job ...]If no job arguments are given, wait for all jobs to complete and then return an exit status of zero (including when there were no jobs, and so nothing exited.)
With the -n
option, wait instead for
any one of the given jobs, or if none are given,
any job, to complete, and return the exit status of that job. If none of
the given job arguments is a current child of the
shell, or if no job arguments are given and the
shell has no unwaited for children, then the exit status will be
127.
The -p
var
option allows the process (or job) identifier of the job for which the
exit status is returned to be obtained. The variable named (which must
not be readonly) will be unset initially, then if a job has exited and
its status is being returned, set to the identifier from the arg list
(if given) of that job, or the lead process identifier of the job to
exit when used with -n
and no job arguments.
Note that -p
with neither
-n
nor job arguments is
useless, as in that case no job status is returned, the variable named
is simply unset.
If the wait is interrupted by a signal, its exit status will be greater than 128, and var, if given, will remain unset.
Once waited upon, by specific process number or job-id, or by
a wait
with no arguments, knowledge of the child
is removed from the system, and it cannot be waited upon again.
Note than when a list of jobs are given, more that one
argument might refer to the same job. In that case, if the final
argument represents a job that is also given earlier in the list, it is
not defined whether the status returned will be the exit status of the
job, or 127 indicating that the child no longer existed when the wait
command reached the later argument in the list. In this
sh
the exit status will be that from the job.
sh
waits for each job exactly once, regardless
of how many times (or how many different ways) it is listed in the
arguments to wait
. That is
wait 100 100 100
wait 100
sh
is
created as a “job” and added to the jobs table. When enabled by
the -m
option (aka -o
monitor
) when the job is created,
sh
places each job (if run from the top level shell)
into a process group of its own, which allows control of the process(es), and
its/their descendants, as a unit. When the -m
option
is off, or when started from a sub-shell environment, jobs share the same
process group as the parent shell. The -m
option is
enabled by default in interactive shells with a terminal as standard input and
standard error.
Jobs with separate process groups may be stopped, and then later
resumed in the foreground (with access to the terminal) or in the background
(where attempting to read from the terminal will result in the job
stopping.) A list of current jobs can be obtained using the
jobs
built-in command. Jobs are identified using
either the process identifier of the lead process of the job (the value
available in the special parameter “!
”
if the job is started in the background), or using percent notation. Each
job is given a “job number” which is a small integer, starting
from 1, and can be referenced as
“%
n” where
n is that number. Note that this applies to jobs both
with and without their own process groups. Job numbers are shown in the
output from the jobs
command enclosed in brackets
(‘[
’ and
‘]
’). Whenever the job table becomes
empty, the numbers begin at one again. In addition, there is the concept of
a current, and a previous job, identified by
“%+
” (or
“%%
” or even just
“%
”), and a previous job, identified
by “%-
”. Whenever a background job is
started, or a job is resumed in the background, it becomes the current job.
The job that was the current job (prepare for a big surprise here, drum
roll..., wait for it...) becomes the previous job. When the current job
terminates, the previous job is promoted to be the current job. In addition
the form
“%
string” finds
the job for which the command starts with string and
the form
“%?
string” finds
the job which contains the string in its command
somewhere. Both forms require the result to be unambiguous. For this purpose
the “command” is that shown in the output from the
jobs
command, not the original command line.
The bg
, fg
,
jobid
, jobs
,
kill
, and wait
commands all
accept job identifiers as arguments, in addition to process identifiers
(larger integers). See the Built-ins
section above, and kill(1), for
more details of those commands. In addition, a job identifier (using one of
the “% forms”) issued as a command, without arguments, is
interpreted as if it had been given as the argument to the
fg
command.
To cause a foreground process to stop, enter the terminal's
stop
character (usually control-Z). To cause a
background process to stop, send it a STOP
signal,
using the kill command. A useful function to define is
stop() { kill -s STOP "${@:-%%}"; }
The fg
command resumes a stopped job,
placing it in the foreground, and bg
resumes a
stopped job in the background. The jobid
command
provides information about process identifiers, job identifiers, and the
process group identifier, for a job.
Whenever a sub-shell is created, the jobs table becomes invalid (the sub-shell has no children.) However, to enable uses like
PID=$(jobid -p %1)
the table is only actually cleared in a sub-shell when needed to
create the first job there (built-in commands run in the foreground do not
create jobs.) Note that in this environment, there is no useful current job
(“%%
” actually refers to the sub-shell
itself, but is not accessible) but the job which is the current job in the
parent can be accessed as “%-
”.
sh
is being used interactively from a terminal, the
current command and the command history (see fc
in the
Built-ins section) can be edited using
emacs-mode or vi-mode command-line editing. The command
‘set -o emacs
’ (or
-E
option) enables emacs-mode editing. The command
‘set -o vi
’ (or
-V
option) enables vi-mode editing and places the
current shell process into vi insert mode. (See the
Argument List Processing
section above.)
The vi-mode uses commands similar to a subset of those described
in the vi(1) man page. With
vi-mode enabled, sh
can be switched between insert
mode and command mode. It's similar to vi
: pressing
the ⟨ESC⟩ key will throw you into vi command mode. Pressing
the ⟨return⟩ key while in command mode will pass the line to
the shell.
The emacs-mode uses commands similar to a subset available in the
emacs
editor. With emacs-mode enabled, special keys
can be used to modify the text in the buffer using the control key.
sh
uses the
editline(3) library. See
editline(7) for a list of
the possible command bindings, and the default settings in emacs and vi
modes. Also see editrc(5) for
the commands that can be given to configure
editline(7) in the file
named by the EDITRC
parameter, or a file used with
the inputrc
built-in command, or using
editline(7)'s configuration
command line.
When command line editing is enabled, the
editline(7) functions
control printing of the PS1
and
PS2
prompts when required. As, in this mode, the
command line editor needs to keep track of what characters are in what
position on the command line, care needs to be taken when setting the
prompts. Normal printing characters are handled automatically, however mode
setting sequences, which do not actually display on the terminal, need to be
identified to editline(7).
This is done, when needed, by choosing a character that is not needed
anywhere in the prompt, including in the mode setting sequences, any single
character is acceptable, and assigning it to the shell parameter
PSlit
. Then that character should be used, in pairs,
in the prompt string. Between each pair of PSlit
characters are mode setting sequences, which affect the printing attributes
of the following (normal) characters of the prompt, but do not themselves
appear visibly, nor change the terminal's cursor position.
Each such sequence, that is PSlit
character, mode setting character sequence, and another
PSlit
character, must currently be followed by at
least one following normal prompt character, or it will be ignored. That is,
a PSlit
character cannot be the final character of
PS1
or PS2
, nor may two
PSlit
delimited sequences appear adjacent to each
other. Each sequence can contain as many mode altering sequences as are
required however. Only the first character from
PSlit
will be used. When set
PSlit
should usually be set to a string containing
just one character, then it can simply be embedded in
PS1
(or PS2
) as in
PS1="${PSlit}
mset${PSlit}XYZ${PSlit}
mclr${PSlit}ABC"
The prompt visible will be “XYZABC” with the “XYZ” part shown according as defined by the mode setting characters mset, and then cleared again by mclr. See tput(1) for one method to generate appropriate mode sequences. Note that both parts, XYZ and ABC, must each contain at least one character.
If PSlit
is unset, which is its initial
state, or set to a null string, no literal character will be defined, and
all characters of the prompt strings will be assumed to be visible
characters (which includes spaces etc.) To allow smooth use of prompts,
without needing redefinition, when
editline(7) is disabled, the
character chosen should be one which will be ignored by the terminal if
received, as when
editline(7) is not in use,
the prompt strings are simply written to the terminal. For example,
setting:
PSlit="$(printf '\1')" PS1="${PSlit}$(tput bold blink)${PSlit}\$${PSlit}$(tput sgr0)${PSlit} "
will arrange for the primary prompt to be a bold blinking dollar sign, if supported by the current terminal, followed by an (ordinary) space, and, as the SOH (control-A) character (‘\1’) will not normally affect a terminal, this same prompt will usually work with editline(7) enabled or disabled.
CDPATH
cd
built-in.EDITRC
EDITRC
is
set (even with no actual value change,) and if command line editing
changes from disabled to enabled, or the editor style used is changed.
(See the -E
and -V
options
of the set
built-in command, described in
Built-ins above, which are documented
further above in Argument
List Processing.) If unset “$HOME/.editrc” is used.ENV
ENV
is processed
and used.EUSER
getpwuid(geteuid())->pw_name
EUSER
is
expanded, so changes to the shell's execution identity cause updates
without further action. If unset, it returns nothing. If set it loses its
special properties, and is simply a variable. See the
specialvar
built-in command for remedial
action.HISTSIZE
HOME
cd
built-in.HOSTNAME
HOSTNAME
is expanded, so
changes to the system's name are reflected without further action. If
unset, it returns nothing. If set it loses its special properties, and is
simply a variable. See the specialvar
built-in
command for remedial action.IFS
LANG
LINENO
MAIL
MAILPATH
. The check occurs just
before PS1
is written, immediately after reporting
jobs which have changed status, in interactive shells only. New mail is
considered to have arrived if the monitored file has increased in size
since the last check.MAILPATH
MAIL
setting. There is a maximum of 10 mailboxes
that can be monitored at once.PATH
POSIXLY_CORRECT
posix
will be set. (See the description of
the set
command in the
Built-ins section.) After
initialization it is unused by the shell, but is usually passed through
the environment to descendant processes, including other instances of the
shell, which may interpret it in a similar way.PPID
PS1
$
”, unless you are the superuser, in which case it defaults
to “#
”. This string is subject to
parameter, arithmetic, and if enabled by setting the
promptcmds
option, command substitution before
being output. During execution of commands used by command substitution,
execution tracing, the xtrace
(set
-x
) option is
temporarily disabled. If promptcmds
is not set and
the prompt string uses command substitution, the prompt used will be an
appropriate error string. For other expansion errors, the prompt will
become an empty string, without an error message. To verify parsing of
PS1
, the method suggested for
ENV
can be used.PS2
>
”. After expansion (as for
PS1
) it is written whenever more input is required
to complete the current command.PS4
PS1
,
as a prefix for each line when execution trace
(set
-x
) is enabled.
PS4
defaults to “+
”.PSc
PS1
. If a
privileged shell has its privileges removed by clearing the
-p
option, an attempt will be made to be reset
PSc
to “#” or “$”, as
appropriate for its new privilege level.PSlit
PS1
or PS2
to indicate to
editline(7) that the
characters between each pair of occurrences of the
PSlit
character will not appear in the visible
prompt, and will not cause the terminal's cursor to change position, but
rather set terminal attributes for the following prompt character(s) at
least one of which must be present. See
Command Line Editing above
for more information.RANDOM
RANDOM
can be assigned an
integer value to seed the PRNG. If the value assigned is a constant, then
the sequence of values produces on subsequent references of
RANDOM
will repeat after the next time the same
constant is assigned. Note, this is not guaranteed to remain constant from
one version of the shell to another – the PRNG algorithm, or
seeding method is subject to change. If RANDOM
is
assigned an empty value (null string) then the next time
RANDOM
is accessed, it will be seeded from a more
genuinely random source. The sequence of pseudo-random numbers generated
will not be able to be generated again (except by luck, whether good or
bad, depends!) This is also how the initial seed is generated, if none has
been assigned before RANDOM
is first accessed
after shell initialization. Should the error message “RANDOM
initialisation failed” appear on standard error, it indicates that
the source of good random numbers was not available, and
RANDOM
has instead been seeded with a more
predictable value. The following sequence of random numbers will not be as
unpredictable as they otherwise would be.SECONDS
specialvar
built-in command for remedial
action.START_TIME
$((START_TIME
+
SECONDS
))
START_TIME
has not
been modified, and SECONDS
has not been set or
unset.TERM
ToD
ToD_FORMAT
(or
“%T” if ToD_FORMAT
is unset) as the
format argument to
strftime(3) to encode the
current time of day, in the time zone defined by
TZ
if set, or current local time if not, and
returns the result. If unset ToD
returns nothing.
If set, it loses its special properties, and becomes a normal variable.
See the specialvar
built-in command for remedial
action.ToD_FORMAT
ToD
. Initially
unset.TZ
ToD
and if exported, other utilities
that deal with times. If unset, the system's local wall clock time zone is
used.NETBSD_SHELL
sh
defined by this manual
page, and gives its version information. It can also give information in
additional space separated words, after the version string. If the shell
was built as part of a reproducible build, the relevant date that was used
for that build will be included. Finally, any non-standard compilation
options, which may affect features available, that were used when building
the shell will be listed. NETBSD_SHELL
behaves
like any other variable that has the read-only and un-exportable
attributes set.LINENO
LINENO
is in many respects a normal shell variable,
containing an integer value. and can be expanded using any of the forms
mentioned above which can be used for any other variable.
LINENO
can be exported, made readonly, or
unset, as with any other variable, with similar effects. Note that while
being readonly prevents later attempts to set, or unset,
LINENO
, it does not prevent its value changing.
References to LINENO
(when not unset) always obtain
the current line number. However, LINENO
should
normally not ever be set or unset. In this shell setting
LINENO
reverses the effect of an earlier
unset
, but does not otherwise affect the value
obtained. If unset, LINENO
should not normally be
set again, doing so is not portable. If LINENO
is
set or unset, different shells act differently. The value of
LINENO
is never imported from the environment when
the shell is started, though if present there, as with any other variable,
LINENO
will be exported by this shell.
LINENO
is set automatically by the shell
to be the number of the source line on which it occurs. When exported,
LINENO
is exported with its value set to the line
number it would have had had it been referenced on the command line of the
command to which it is exported. Line numbers are counted from 1, which is
the first line the shell reads from any particular file. For this shell,
standard input, including in an interactive shell, the user's terminal, is
just another file and lines are counted there as well. However note that not
all shells count interactive lines this way, it is not wise to rely upon
LINENO
having a useful value, except in a script, or
a function.
The role of LINENO
in functions is less
clear. In some shells, LINENO
continues to refer to
the line number in the script which defines the function, in others lines
count from one within the function, always (and resume counting normally
once the function definition is complete) and others count in functions from
one if the function is defined interactively, but otherwise just reference
the line number in the script in which the function is defined. This shell
gives the user the option to choose. If the -L
flag
(the local_lineno
option, see
Argument List Processing)
is set, when the function is defined, then the function defaults to counting
lines with one being the first line of the function. When the
-L
flag is not set, the shell counts lines in a
function definition in the same continuous sequence as the lines that
surround the function definition. Further, if LINENO
is made local (see Built-ins above)
inside the function, the function can decide which behavior it prefers. If
LINENO
is made local and inherited, and not given a
value, as in
local -I
LINENO
LINENO
will give
the line number as if lines are counted in sequence with the lines that
surround the function definition (and any other function definitions in which
this is nested.) If LINENO
is made local, and in that
same command, given a value, as
local
[-I
|-N
]
LINENO
=value
LINENO
will give the line number as if lines are
counted from one from the beginning of the function. The value nominally
assigned in this case is irrelevant, and ignored. For completeness, if lineno
is made local and unset, as in
local -N
LINENO
LINENO
is simply unset inside the function, and
gives no value at all.
Now for some technical details. The line on which
LINENO
occurs in a parameter expansion, is the line
that contains the ‘$’ that begins the expansion of
LINENO
. In the case of nested expansions, that
‘$’ is the one that actually has
LINENO
as its parameter. In an arithmetic expansion,
where no ‘$’ is used to evaluate
LINENO
but LINENO
is simply
referenced as a variable, then the value is the line number of the line that
contains the ‘L’ of LINENO
. For
functions line one of the function definition (when relevant) is the line
that contains the first character of the function name in the definition.
When exported, the line number of the command is the line number where the
first character of the word which becomes the command name occurs.
When the shell opens a new file, for any reason, it counts lines
from one in that file, and then resumes its original counting once it
resumes reading the previous input stream. When handling a string passed to
eval
the line number starts at the line on which the
string starts, and then if the string contains internal newline characters,
those characters increase the line number. This means that references to
LINENO
in such a case can produce values larger than
would be produced by a reference on the line after the
eval
.
sh
command appeared in
Version 1 AT&T UNIX. It was replaced in
Version 7 AT&T UNIX with a version that
introduced the basis of the current syntax. That was, however, unmaintainable
so we wrote this one. This NetBSD
sh
is a much modified descendant of the ash shell
written by Ken Almquist.
The characters generated by filename completion should probably be quoted to ensure that the filename is still valid after the input line has been processed.
Job control of compound statements (loops, etc) is a complete mess.
Many, many, more. (But less than there were...)
October 31, 2021 | NetBSD 9.4 |