| www.delorie.com/gnu/docs/bash/bash.1.html | search |
![]() Buy the book! | |
Bash is intended to be a conformant implementation of the IEEE POSIX Shell and Tools specification (IEEE Working Group 1003.2).
INVOCATION
below).
RESTRICTED SHELL
below).
SHELL BUILTIN COMMANDS
below).
If shopt_option is present, -O sets the value of that option;
+O unsets it.
If shopt_option is not supplied, the names and values of the shell
options accepted by shopt are printed on the standard output.
If the invocation option is +O, the output is displayed in a format
that may be reused as input.
Bash also interprets a number of multi-character options. These options must appear on the command line before the single-character options to be recognized.
INVOCATION
below).
/etc/profile
or any of the personal initialization files
~/.bash_profile,
~/.bash_login,
or
~/.profile.
By default,
bash
reads these files when it is invoked as a login shell (see
INVOCATION
below).
RESTRICTED SHELL
below).
PATH
for the script.
An interactive shell is one started without non-option arguments
and without the
-c
option
whose standard input and output are
both connected to terminals (as determined by
isatty(3)),
or one started with the
-i
option.
PS1
is set and
$-
includes
i
if
bash
is interactive,
allowing a shell script or a startup file to test this state.
The following paragraphs describe how
bash
executes its startup files.
If any of the files exist but cannot be read,
bash
reports an error.
Tildes are expanded in file names as described below under
Tilde Expansion
in the
EXPANSION
section.
When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists.
When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.
When
bash
is started non-interactively, to run a shell script, for example, it
looks for the variable
BASH_ENV
in the environment, expands its value if it appears there, and uses the
expanded value as the name of a file to read and execute.
Bash
behaves as if the following command were executed:
but the value of the
PATH
variable is not used to search for the file name.
If
bash
is invoked with the name
sh,
it tries to mimic the startup behavior of historical versions of
sh
as closely as possible,
while conforming to the POSIX standard as well.
When invoked as an interactive login shell, or a non-interactive
shell with the --login option, it first attempts to
read and execute commands from
/etc/profile
and
~/.profile,
in that order.
The
--noprofile
option may be used to inhibit this behavior.
When invoked as an interactive shell with the name
sh,
bash
looks for the variable
ENV,
expands its value if it is defined, and uses the
expanded value as the name of a file to read and execute.
Since a shell invoked as
sh
does not attempt to read and execute commands from any other startup
files, the
--rcfile
option has no effect.
A non-interactive shell invoked with the name
sh
does not attempt to read any other startup files.
When invoked as
sh,
bash
enters
posix
mode after the startup files are read.
When
bash
is started in
posix
mode, as with the
--posix
command line option, it follows the POSIX standard for startup files.
In this mode, interactive shells expand the
ENV
variable and commands are read and executed from the file
whose name is the expanded value.
No other startup files are read.
Bash attempts to determine when it is being run by the remote shell daemon, usually rshd. If bash determines it is being run by rshd, it reads and executes commands from ~/.bashrc, if that file exists and is readable. It will not do this if invoked as sh. The --norc option may be used to inhibit this behavior, and the --rcfile option may be used to force another file to be read, but rshd does not generally invoke the shell with those options or allow them to be specified.
If the shell is started with the effective user (group) id not equal to the
real user (group) id, and the -p option is not supplied, no startup
files are read, shell functions are not inherited from the environment, the
SHELLOPTS
variable, if it appears in the environment, is ignored,
and the effective user id is set to the real user id.
If the -p option is supplied at invocation, the startup behavior is
the same, but the effective user id is not reset.
The following definitions are used throughout the rest of this document.
SHELL GRAMMAR
below) or the third word of a
case
or
for
command:
A simple command is a sequence of optional variable assignments followed by blank-separated words and redirections, and terminated by a control operator. The first word specifies the command to be executed, and is passed as argument zero. The remaining words are passed as arguments to the invoked command.
The return value of a simple command is its exit status, or 128+n if the command is terminated by signal n.
A pipeline is a sequence of one or more commands separated by the character |. The format for a pipeline is:
[time [-p]] [ ! ] command [ | command2 ... ]
The standard output of
command
is connected via a pipe to the standard input of
command2.
This connection is performed before any redirections specified by the
command (see
REDIRECTION
below).
If the reserved word ! precedes a pipeline, the exit status of that pipeline is the logical NOT of the exit status of the last command. Otherwise, the status of the pipeline is the exit status of the last command. The shell waits for all commands in the pipeline to terminate before returning a value.
If the
time
reserved word precedes a pipeline, the elapsed as well as user and
system time consumed by its execution are reported when the pipeline
terminates.
The -p option changes the output format to that specified by POSIX.
The
TIMEFORMAT
variable may be set to a format string that specifies how the timing
information should be displayed; see the description of
TIMEFORMAT
under
Shell Variables
below.
Each command in a pipeline is executed as a separate process (i.e., in a subshell).
A list is a sequence of one or more pipelines separated by one of the operators ;, &, &&, or ||, and optionally terminated by one of ;, &, or <newline>.
Of these list operators, && and || have equal precedence, followed by ; and &, which have equal precedence.
A sequence of one or more newlines may appear in a list instead of a semicolon to delimit commands.
If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. Commands separated by a ; are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed.
The control operators && and || denote AND lists and OR lists, respectively. An AND list has the form
command1 && command2
command2 is executed if, and only if, command1 returns an exit status of zero.
An OR list has the form
command1 || command2
command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.
A compound command is one of the following:
ARITHMETIC EVALUATION.
If the value of the expression is non-zero, the return status is 0;
otherwise the return status is 1. This is exactly equivalent to
let "expression".
CONDITIONAL EXPRESSIONS.
Word splitting and pathname expansion are not performed on the words
between the [[ and ]]; tilde expansion, parameter and
variable expansion, arithmetic expansion, command substitution, process
substitution, and quote removal are performed.
When the == and != operators are used, the string to the
right of the operator is considered a pattern and matched according
to the rules described below under Pattern Matching.
The return value is 0 if the string matches or does not match
the pattern, respectively, and 1 otherwise.
Any part of the pattern may be quoted to force it to be matched as a
string.
Expressions may be combined using the following operators, listed
in decreasing order of precedence:
The && and operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.
PARAMETERS
below).
The return status is the exit status of the last command that executes.
If the expansion of the items following in results in an empty
list, no commands are executed, and the return status is 0.
ARITHMETIC EVALUATION.
The arithmetic expression expr2 is then evaluated repeatedly
until it evaluates to zero.
Each time expr2 evaluates to a non-zero value, list is
executed and the arithmetic expression expr3 is evaluated.
If any expression is omitted, it behaves as if it evaluates to 1.
The return value is the exit status of the last command in list
that is executed, or false if any of the expressions is invalid.
PARAMETERS
below). The
PS3
prompt is then displayed and a line read from the standard input.
If the line consists of a number corresponding to one of
the displayed words, then the value of
name
is set to that word. If the line is empty, the words and prompt
are displayed again. If EOF is read, the command completes. Any
other value read causes
name
to be set to null. The line read is saved in the variable
REPLY.
The
list
is executed after each selection until a
break
command is executed.
The exit status of
select
is the exit status of the last command executed in
list,
or zero if no commands were executed.
FUNCTIONS
below.)
SHELL BUILTIN COMMANDS
below), a word beginning with
#
causes that word and all remaining characters on that line to
be ignored. An interactive shell without the
interactive_comments
option enabled does not allow comments. The
interactive_comments
option is on by default in interactive shells.
Each of the metacharacters listed above under
DEFINITIONS
has special meaning to the shell and must be quoted if it is to
represent itself.
When the command history expansion facilities are being used, the history expansion character, usually !, must be quoted to prevent history expansion.
There are three quoting mechanisms: the escape character, single quotes, and double quotes.
A non-quoted backslash (\) is the escape character. It preserves the literal value of the next character that follows, with the exception of <newline>. If a \<newline> pair appears, and the backslash is not itself quoted, the \<newline> is treated as a line continuation (that is, it is removed from the input stream and effectively ignored).
Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, and \. The characters $ and ` retain their special meaning within double quotes. The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or <newline>. A double quote may be quoted within double quotes by preceding it with a backslash.
The special parameters
*
and
@
have special meaning when in double
quotes (see
PARAMETERS
below).
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specifed by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows:
The expanded result is single-quoted, as if the dollar sign had not been present.
A double-quoted string preceded by a dollar sign ($) will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted.
SHELL BUILTIN COMMANDS).
A parameter is set if it has been assigned a value. The null string is
a valid value. Once a variable is set, it may be unset only by using
the
unset
builtin command (see
SHELL BUILTIN COMMANDS
below).
A variable may be assigned to by a statement of the form
name=[value]
If
value
is not given, the variable is assigned the null string. All
values
undergo tilde expansion, parameter and variable expansion,
command substitution, arithmetic expansion, and quote
removal (see
EXPANSION
below). If the variable has its
integer
attribute set, then
value
is subject to arithmetic expansion even if the $((...)) expansion is
not used (see
Arithmetic Expansion
below).
Word splitting is not performed, with the exception
of "$@" as explained below under
Special Parameters.
Pathname expansion is not performed.
Assignment statements may also appear as arguments to the
declare,
typeset,
export,
readonly,
and
local
builtin commands.
A
positional parameter
is a parameter denoted by one or more
digits, other than the single digit 0. Positional parameters are
assigned from the shell's arguments when it is invoked,
and may be reassigned using the
set
builtin command. Positional parameters may not be assigned to
with assignment statements. The positional parameters are
temporarily replaced when a shell function is executed (see
FUNCTIONS
below).
When a positional parameter consisting of more than a single
digit is expanded, it must be enclosed in braces (see
EXPANSION
below).
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
IFS
special variable. That is, "$*" is equivalent
to "$1c$2c...", where
c
is the first character of the value of the
IFS
variable. If
IFS
is unset, the parameters are separated by spaces.
If
IFS
is null, the parameters are joined without intervening separators.
The following variables are set by the shell:
DIRSTACK
is unset, it loses its special properties, even if it is
subsequently reset.
FUNCNAME
have no effect and return an error status.
If
FUNCNAME
is unset, it loses its special properties, even if it is
subsequently reset.
GROUPS
have no effect and return an error status.
If
GROUPS
is unset, it loses its special properties, even if it is
subsequently reset.
HISTCMD
is unset, it loses its special properties, even if it is
subsequently reset.
LINENO
is unset, it loses its special properties, even if it is
subsequently reset.
SHELL BUILTIN COMMANDS
below).
SHELL BUILTIN COMMANDS
below).
RANDOM.
If
RANDOM
is unset, it loses its special properties, even if it is
subsequently reset.
SECONDS,
the value returned upon subsequent
references is
the number of seconds since the assignment plus the value assigned.
If
SECONDS
is unset, it loses its special properties, even if it is
subsequently reset.
SHELL BUILTIN COMMANDS
below). The options appearing in
SHELLOPTS
are those reported as
on
by set -o.
If this variable is in the environment when
bash
starts up, each shell option in the list will be enabled before
reading any startup files.
This variable is read-only.
The following variables are used by the shell. In some cases, bash assigns a default value to a variable; these cases are noted below.
BASH_ENV
is subjected to parameter expansion, command substitution, and arithmetic
expansion before being interpreted as a file name.
PATH
is not used to search for the resultant file name.
READLINE
below).
A filename whose suffix matches one of the entries in
FIGNORE
is excluded from the list of matched filenames.
A sample value is
GLOBIGNORE,
it is removed from the list of matches.
HISTORY
below). The default value is ~/.bash_history. If unset, the
command history is not saved when an interactive shell exits.
HISTORY
below). The default value is 500.
/etc/hosts
that should be read when the shell needs to complete a
hostname.
The list of possible hostname completions may be changed while the
shell is running;
the next time hostname completion is attempted after the
value is changed,
bash
adds the contents of the new file to the existing list.
If
HOSTFILE
is set, but has no value, bash attempts to read
/etc/hosts
to obtain the list of possible hostname completions.
When
HOSTFILE
is unset, the hostname list is cleared.
EOF
character as the sole input. If set, the value is the number of
consecutive
EOF
characters which must be
typed as the first characters on an input line before
bash
exits. If the variable exists but does not have a numeric value, or
has no value, the default value is 10. If it does not exist,
EOF
signifies the end of input to the shell.
~/.inputrc
(see
READLINE
below).
MAILPATH
variable is not set,
bash
informs the user of the arrival of mail in the specified file.
MAILPATH='/var/mail/bfox?"You have mail":~/shell-mail?"$_ has mail!"'
Bash supplies a default value for this variable, but the location of the user mail files that it uses is system dependent (e.g., /var/mail/$USER).
SHELL BUILTIN COMMANDS
below).
OPTERR
is initialized to 1 each time the shell is invoked or a shell
script is executed.
COMMAND EXECUTION
below). The default path is system-dependent,
and is set by the administrator who installs
bash.
A common value is
PROMPTING
below) and used as the primary prompt string. The default value is
``\s-\v\$ ''.
SHELL GRAMMAR
above).
PS4
is replicated multiple times, as necessary, to indicate multiple
levels of indirection. The default is ``+ ''.
JOB CONTROL
below). If set to any other value, the supplied string must
be a prefix of a stopped job's name; this provides functionality
analogous to the
%
job identifier.
HISTORY EXPANSION
below). The first character is the history expansion character,
the character which signals the start of a history
expansion, normally `!'.
The second character is the quick substitution
character, which is used as shorthand for re-running the previous
command entered, substituting one string for another in the command.
The default is `^'.
The optional third character is the character
which indicates that the remainder of the line is a comment when found
as the first character of a word, normally `#'. The history
comment character causes history substitution to be skipped for the
remaining words on the line. It does not necessarily cause the shell
parser to treat the rest of the line as a comment.
An array is created automatically if any variable is assigned to using
the syntax name[subscript]=value. The
subscript
is treated as an arithmetic expression that must evaluate to a number
greater than or equal to zero. To explicitly declare an array, use
declare -a name
(see
SHELL BUILTIN COMMANDS
below).
declare -a name[subscript]
is also accepted; the subscript is ignored. Attributes may be
specified for an array variable using the
declare
and
readonly
builtins. Each attribute applies to all members of an array.
Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value is of the form [subscript]=string. Only string is required. If the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero. This syntax is also accepted by the declare builtin. Individual array elements may be assigned to using the name[subscript]=value syntax introduced above.
Any element of an array may be referenced using
${name[subscript]}. The braces are required to avoid
conflicts with pathname expansion. If
subscript is @ or *, the word expands to
all members of name. These subscripts differ only when the
word appears within double quotes. If the word is double-quoted,
${name[*]} expands to a single
word with the value of each array member separated by the first
character of the
IFS
special variable, and ${name[@]} expands each element of
name to a separate word. When there are no array members,
${name[@]} expands to nothing. This is analogous to the expansion
of the special parameters * and @ (see
Special Parameters
above). ${#name[subscript]} expands to the length of
${name[subscript]}. If subscript is * or
@, the expansion is the number of elements in the array.
Referencing an array variable without a subscript is equivalent to
referencing element zero.
The unset builtin is used to destroy arrays. unset name[subscript] destroys the array element at index subscript. unset name, where name is an array, or unset name[subscript], where subscript is * or @, removes the entire array.
The declare, local, and readonly builtins each accept a -a option to specify an array. The read builtin accepts a -a option to assign a list of words read from the standard input to an array. The set and declare builtins display array values in a way that allows them to be reused as assignments.
The order of expansions is: brace expansion, tilde expansion, parameter, variable and arithmetic expansion and command substitution (done in a left-to-right fashion), word splitting, and pathname expansion.
On systems that can support it, there is an additional expansion available: process substitution.
Only brace expansion, word splitting, and pathname expansion
can change the number of words of the expansion; other expansions
expand a single word to a single word.
The only exceptions to this are the expansions of
"$@" and "${name[@]}"
as explained above (see
PARAMETERS).
Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to pathname expansion, but the filenames generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by a series of comma-separated strings between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right.
Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved. For example, a{d,c,b}e expands into `ade ace abe'.
Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.
A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma. Any incorrectly formed brace expansion is left unchanged. A { or , may be quoted with a backslash to prevent its being considered part of a brace expression. To avoid conflicts with parameter expansion, the string ${ is not considered eligible for brace expansion.
This construct is typically used as shorthand when the common prefix of the strings to be generated is longer than in the above example:
mkdir /usr/local/src/bash/{old,new,dist,bugs}
Brace expansion introduces a slight incompatibility with
historical versions of
sh.
sh
does not treat opening or closing braces specially when they
appear as part of a word, and preserves them in the output.
Bash
removes braces from words as a consequence of brace
expansion. For example, a word entered to
sh
as file{1,2}
appears identically in the output. The same word is
output as
file1 file2
after expansion by
bash.
If strict compatibility with
sh
is desired, start
bash
with the
+B
option or disable brace expansion with the
+B
option to the
set
command (see
SHELL BUILTIN COMMANDS
below).
If a word begins with an unquoted tilde character (`~'), all of
the characters preceding the first unquoted slash (or all characters,
if there is no unquoted slash) are considered a tilde-prefix.
If none of the characters in the tilde-prefix are quoted, the
characters in the tilde-prefix following the tilde are treated as a
possible login name.
If this login name is the null string, the tilde is replaced with the
value of the shell parameter
HOME.
If
HOME
is unset, the home directory of the user executing the shell is
substituted instead.
Otherwise, the tilde-prefix is replaced with the home directory
associated with the specified login name.
If the tilde-prefix is a `~+', the value of the shell variable
PWD
replaces the tilde-prefix.
If the tilde-prefix is a `~-', the value of the shell variable
OLDPWD,
if it is set, is substituted.
If the characters following the tilde in the tilde-prefix consist
of a number N, optionally prefixed
by a `+' or a `-', the tilde-prefix is replaced with the corresponding
element from the directory stack, as it would be displayed by the
dirs
builtin invoked with the tilde-prefix as an argument.
If the characters following the tilde in the tilde-prefix consist of a
number without a leading `+' or `-', `+' is assumed.
If the login name is invalid, or the tilde expansion fails, the word is unchanged.
Each variable assignment is checked for unquoted tilde-prefixes immediately
following a
:
or
=.
In these cases, tilde expansion is also performed.
Consequently, one may use file names with tildes in assignments to
PATH,
MAILPATH,
and
CDPATH,
and the shell assigns the expanded value.
The `$' character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.
When braces are used, the matching ending brace is the first `}' not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or paramter expansion.
If the first character of parameter is an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exception to this is the expansion of ${!prefix*} described below.
In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. When not performing substring expansion, bash tests for a parameter that is unset or null; omitting the colon results in a test only for a parameter that is unset.
ARITHMETIC EVALUATION
below).
length must evaluate to a number greater than or equal to zero.
If offset evaluates to a number less than zero, the value
is used as an offset from the end of the value of parameter.
If parameter is @, the result is length positional
parameters beginning at offset.
If parameter is an array name indexed by @ or *,
the result is the length
members of the array beginning with ${parameter[offset]}.
Substring indexing is zero-based unless the positional parameters
are used, in which case the indexing starts at 1.
IFS
special variable.
Command substitution allows the output of a command to replace the command name. There are two forms:
$(command)
Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).
When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.
Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes.
If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.
Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:
$((expression))
The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, string expansion, command substitution, and quote removal. Arithmetic substitutions may be nested.
The evaluation is performed according to the rules listed below under
ARITHMETIC EVALUATION.
If
expression
is invalid,
bash
prints a message indicating failure and no substitution occurs.
Process substitution is supported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files. It takes the form of <(list) or >(list). The process list is run with its input or output connected to a FIFO or some file in /dev/fd. The name of this file is passed as an argument to the current command as the result of the expansion. If the >(list) form is used, writing to the file will provide input for list. If the <(list) form is used, the file passed as an argument should be read to obtain the output of list.
When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion.
The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting.
The shell treats each character of
IFS
as a delimiter, and splits the results of the other
expansions into words on these characters. If
IFS
is unset, or its
value is exactly
<space><tab><newline>,
the default, then
any sequence of
IFS
characters serves to delimit words. If
IFS
has a value other than the default, then sequences of
the whitespace characters
space
and
tab
are ignored at the beginning and end of the
word, as long as the whitespace character is in the
value of
IFS
(an
IFS
whitespace character).
Any character in
IFS
that is not
IFS
whitespace, along with any adjacent
IFS
whitespace characters, delimits a field.
A sequence of
IFS
whitespace characters is also treated as a delimiter.
If the value of
IFS
is null, no word splitting occurs.
Explicit null arguments ("" or '') are retained. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. If a parameter with no value is expanded within double quotes, a null argument results and is retained.
Note that if no expansion occurs, no splitting is performed.
After word splitting,
unless the
-f
option has been set,
bash
scans each word for the characters
*,
?,
and
[.
If one of these characters appears, then the word is
regarded as a
pattern,
and replaced with an alphabetically sorted list of
file names matching the pattern.
If no matching file names are found,
and the shell option
nullglob
is disabled, the word is left unchanged.
If the
nullglob
option is set, and no matches are found,
the word is removed.
If the shell option
nocaseglob
is enabled, the match is performed without regard to the case
of alphabetic characters.
When a pattern is used for pathname expansion,
the character
``.''
at the start of a name or immediately following a slash
must be matched explicitly, unless the shell option
dotglob
is set.
When matching a pathname, the slash character must always be
matched explicitly.
In other cases, the
``.''
character is not treated specially.
See the description of
shopt
below under
SHELL BUILTIN COMMANDS
for a description of the
nocaseglob,
nullglob,
and
dotglob
shell options.
The
GLOBIGNORE
shell variable may be used to restrict the set of file names matching a
pattern.
If
GLOBIGNORE
is set, each matching file name that also matches one of the patterns in
GLOBIGNORE
is removed from the list of matches.
The file names
``.''
and
``..''
are always ignored, even when
GLOBIGNORE
is set. However, setting
GLOBIGNORE
has the effect of enabling the
dotglob
shell option, so all other file names beginning with a
``.''
will match.
To get the old behavior of ignoring file names beginning with a
``.'',
make
``.*''
one of the patterns in
GLOBIGNORE.
The
dotglob
option is disabled when
GLOBIGNORE
is unset.
Pattern Matching
Any character that appears in a pattern, other than the special pattern characters described below, matches itself. The NUL character may not occur in a pattern. The special pattern characters must be quoted if they are to be matched literally.
The special pattern characters have the following meanings:
If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. In the following description, a pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the following sub-patterns:
After the preceding expansions, all unquoted occurrences of the characters \, ', and " that did not result from one of the above expansions are removed.
In the following descriptions, if the file descriptor number is omitted, and the first character of the redirection operator is <, the redirection refers to the standard input (file descriptor 0). If the first character of the redirection operator is >, the redirection refers to the standard output (file descriptor 1).
The word following the redirection operator in the following descriptions, unless otherwise noted, is subjected to brace expansion, tilde expansion, parameter expansion, command substitution, arithmetic expansion, quote removal, pathname expansion, and word splitting. If it expands to more than one word, bash reports an error.
Note that the order of redirections is significant. For example, the command
ls > dirlist 2>&1
directs both standard output and standard error to the file dirlist, while the command
ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard error was duplicated as standard output before the standard output was redirected to dirlist.
Bash handles several filenames specially when they are used in redirections, as described in the following table:
A failure to open or create a file causes the redirection to fail.
Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified.
The general format for redirecting input is:
[n]<word
Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size.
The general format for redirecting output is:
[n]>word
If the redirection operator is >, and the noclobber option to the set builtin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file. If the redirection operator is >|, or the redirection operator is > and the noclobber option to the set builtin command is not enabled, the redirection is attempted even if the file named by word exists.
Redirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created.
The general format for appending output is:
[n]>>word
Bash allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word with this construct.
There are two formats for redirecting standard output and standard error:
&>word
Of the two forms, the first is preferred. This is semantically equivalent to
>word 2>&1
This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command.
The format of here-documents is:
<<[-]word
here-document
delimiter
No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.
If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.
<<<word
The word is expanded and supplied to the command on its standard input.
The redirection operator
[n]<&word
is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to -, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used.
The operator
[n]>&word
is used similarly to duplicate output file descriptors. If n is not specified, the standard output (file descriptor 1) is used. If the digits in word do not specify a file descriptor open for output, a redirection error occurs. As a special case, if n is omitted, and word does not expand to one or more digits, the standard output and standard error are redirected as described previously.
The redirection operator
[n]<&digit-
moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified. digit is closed after being duplicated to n.
Similarly, the redirection operator
[n]>&digit-
moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified.
The redirection operator
[n]<>word
causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created.
SHELL BUILTIN COMMANDS
below).
The first word of each command, if unquoted,
is checked to see if it has an
alias. If so, that word is replaced by the text of the alias.
The alias name and the replacement text may contain any valid
shell input, including the
metacharacters
listed above, with the exception that the alias name may not
contain =. The first word of the replacement text is tested
for aliases, but a word that is identical to an alias being expanded
is not expanded a second time. This means that one may alias
ls
to
ls -F,
for instance, and
bash
does not try to recursively expand the replacement text.
If the last character of the alias value is a
blank,
then the next command
word following the alias is also checked for alias expansion.
Aliases are created and listed with the alias command, and removed with the unalias command.
There is no mechanism for using arguments in the replacement text.
If arguments are needed, a shell function should be used (see
FUNCTIONS
below).
Aliases are not expanded when the shell is not interactive, unless
the
expand_aliases
shell option is set using
shopt
(see the description of
shopt
under
SHELL BUILTIN COMMANDS
below).
The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias. This behavior is also an issue when functions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands.
For almost every purpose, aliases are superseded by shell functions.
SHELL GRAMMAR,
stores a series of commands for later execution.
When the name of a shell function is used as a simple command name,
the list of commands associated with that function name is executed.
Functions are executed in the context of the
current shell; no new process is created to interpret
them (contrast this with the execution of a shell script).
When a function is executed, the arguments to the
function become the positional parameters
during its execution.
The special parameter
#
is updated to reflect the change. Positional parameter 0
is unchanged.
The
FUNCNAME
variable is set to the name of the function while the function
is executing.
All other aspects of the shell execution
environment are identical between a function and its caller
with the exception that the
DEBUG
trap (see the description of the
trap
builtin under
SHELL BUILTIN COMMANDS
below) is not inherited unless the function has been given the
trace attribute (see the description of the
declare
builtin below).
Variables local to the function may be declared with the local builtin command. Ordinarily, variables and their values are shared between the function and its caller.
If the builtin command return is executed in a function, the function completes and execution resumes with the next command after the function call. When a function completes, the values of the positional parameters and the special parameter # are restored to the values they had prior to the function's execution.
Function names and definitions may be listed with the -f option to the declare or typeset builtin commands. The -F option to declare or typeset will list the function names only. Functions may be exported so that subshells automatically have them defined with the -f option to the export builtin.
Functions may be recursive. No limit is imposed on the number of recursive calls.
Shell variables are allowed as operands; parameter expansion is performed before the expression is evaluated. Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax. The value of a variable is evaluated as an arithmetic expression when it is referenced. A shell variable need not have its integer attribute turned on to be used in an expression.
Constants with a leading 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadecimal. Otherwise, numbers take the form [base#]n, where base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. The digits greater than 9 are represented by the lowercase letters, the uppercase letters, @, and _, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangably to represent numbers between 10 and 35.
Operators are evaluated in order of precedence. Sub-expressions in parentheses are evaluated first and may override the precedence rules above.
- OP
is one of
-eq,
-ne,
-lt,
-le,
-gt,
or
-ge.
These arithmetic binary operators return true if arg1
is equal to, not equal to, less than, less than or equal to,
greater than, or greater than or equal to arg2, respectively.
Arg1
and
arg2
may be positive or negative integers.
REDIRECTION.
If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment. If any of the assignments attempts to assign a value to a readonly variable, an error occurs, and the command exits with a non-zero status.
If no command name results, redirections are performed, but do not affect the current shell environment. A redirection error causes the command to exit with a non-zero status.
If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits. If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed. If there were no command substitutions, the command exits with a status of zero.
If the command name contains no slashes, the shell attempts to
locate it. If there exists a shell function by that name, that
function is invoked as described above in
FUNCTIONS.
If the name does not match a function, the shell searches for
it in the list of shell builtins. If a match is found, that
builtin is invoked.
If the name is neither a shell function nor a builtin,
and contains no slashes,
bash
searches each element of the
PATH
for a directory containing an executable file by that name.
Bash
uses a hash table to remember the full pathnames of executable
files (see
hash
under
SHELL BUILTIN COMMANDS
below).
A full search of the directories in
PATH
is performed only if the command is not found in the hash table.
If the search is unsuccessful, the shell prints an error
message and returns an exit status of 127.
If the search is successful, or if the command name contains one or more slashes, the shell executes the named program in a separate execution environment. Argument 0 is set to the name given, and the remaining arguments to the command are set to the arguments given, if any.
If this execution fails because the file is not in executable
format, and the file is not a directory, it is assumed to be
a shell script, a file
containing shell commands. A subshell is spawned to execute
it. This subshell reinitializes itself, so
that the effect is as if a new shell had been invoked
to handle the script, with the exception that the locations of
commands remembered by the parent (see
hash
below under
SHELL BUILTIN COMMANDS)
are retained by the child.
If the program is a file beginning with #!, the remainder of the first line specifies an interpreter for the program. The shell executes the specified interpreter on operating systems that do not handle this executable format themselves. The arguments to the interpreter consist of a single optional argument following the interpreter name on the first line of the program, followed by the name of the program, followed by the command arguments, if any.
When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. Unless otherwise noted, the values are inherited from the shell.
A command invoked in this separate environment cannot affect the shell's execution environment.
Command substitution and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment cannot affect the shell's execution environment.
If a command is followed by a & and job control is not active, the default standard input for the command is the empty file /dev/null. Otherwise, the invoked command inherits the file descriptors of the calling shell as modified by redirections.
The shell provides several ways to manipulate the environment. On invocation, the shell scans its own environment and creates a parameter for each name found, automatically marking it for export to child processes. Executed commands inherit the environment. The export and declare -x commands allow parameters and functions to be added to and deleted from the environment. If the value of a parameter in the environment is modified, the new value becomes part of the environment, replacing the old. The environment inherited by any executed command consists of the shell's initial environment, whose values may be modified in the shell, less any pairs removed by the unset command, plus any additions via the export and declare -x commands.
The environment for any
simple command
or function may be augmented temporarily by prefixing it with
parameter assignments, as described above in
PARAMETERS.
These assignment statements affect only the environment seen
by that command.
If the -k option is set (see the set builtin command below), then all parameter assignments are placed in the environment for a command, not just those that precede the command name.
When bash invokes an external command, the variable _ is set to the full file name of the command and passed to that command in its environment.
If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126.
If a command fails because of an error during expansion or redirection, the exit status is greater than zero.
Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage.
Bash itself returns the exit status of the last command executed, unless a syntax error occurs, in which case it exits with a non-zero value. See also the exit builtin command below.
SIGTERM
(so that kill 0 does not kill an interactive shell),
and
SIGINT
is caught and handled (so that the wait builtin is interruptible).
In all cases, bash ignores
SIGQUIT.
If job control is in effect,
bash
ignores
SIGTTIN,
SIGTTOU,
and
SIGTSTP.
Synchronous jobs started by bash have signal handlers
set to the values inherited by the shell from its parent.
When job control is not in effect, asynchronous commands
ignore
SIGINT
and
SIGQUIT
as well.
Commands run as a result of command substitution ignore the
keyboard-generated job control signals
SIGTTIN,
SIGTTOU,
and
SIGTSTP.
The shell exits by default upon receipt of a
SIGHUP.
Before exiting, an interactive shell resends the
SIGHUP
to all jobs, running or stopped.
Stopped jobs are sent
SIGCONT
to ensure that they receive the
SIGHUP.
To prevent the shell from
sending the signal to a particular job, it should be removed from the
jobs table with the
disown
builtin (see
SHELL BUILTIN COMMANDS
below) or marked
to not receive
SIGHUP
using
disown -h.
If the
huponexit
shell option has been set with
shopt,
bash
sends a
SIGHUP
to all jobs when an interactive login shell exits.
When bash receives a signal for which a trap has been set while waiting for a command to complete, the trap will not be executed until the command completes. When bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed.
The shell associates a job with each pipeline. It keeps a table of currently executing jobs, which may be listed with the jobs command. When bash starts a job asynchronously (in the background), it prints a line that looks like:
[1] 25647
indicating that this job is job number 1 and that the process ID of the last process in the pipeline associated with this job is 25647. All of the processes in a single pipeline are members of the same job. Bash uses the job abstraction as the basis for job control.
To facilitate the implementation of the user interface to job
control, the operating system maintains the notion of a current terminal
process group ID. Members of this process group (processes whose
process group ID is equal to the current terminal process group ID)
receive keyboard-generated signals such as
SIGINT.
These processes are said to be in the
foreground.
Background
processes are those whose process group ID differs from the terminal's;
such processes are immune to keyboard-generated signals.
Only foreground processes are allowed to read from or write to the
terminal. Background processes which attempt to read from (write to) the
terminal are sent a
SIGTTIN (SIGTTOU)
signal by the terminal driver,
which, unless caught, suspends the process.
If the operating system on which bash is running supports job control, bash contains facilities to use it. Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. Typing the delayed suspend character (typically ^Y, Control-Y) causes the process to be stopped when it attempts to read input from the terminal, and control to be returned to bash. The user may then manipulate the state of this job, using the bg command to continue it in the background, the fg command to continue it in the foreground, or the kill command to kill it. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.
There are a number of ways to refer to a job in the shell. The character % introduces a job name. Job number n may be referred to as %n. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. For example, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports an error. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. If the substring matches more than one job, bash reports an error. The symbols %% and %+ refer to the shell's notion of the current job, which is the last job stopped while it was in the foreground or started in the background. The previous job may be referenced using %-. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always flagged with a +, and the previous job with a -.
Simply naming a job can be used to bring it into the foreground: %1 is a synonym for ``fg %1'', bringing job 1 from the background into the foreground. Similarly, ``%1 &'' resumes job 1 in the background, equivalent to ``bg %1''.
The shell learns immediately whenever a job changes state.
Normally,
bash
waits until it is about to print a prompt before reporting
changes in a job's status so as to not interrupt
any other output. If the
-b
option to the
set
builtin command
is enabled,
bash
reports such changes immediately.
Any trap on
SIGCHLD
is executed for each child that exits.
If an attempt to exit bash is made while jobs are stopped, the shell prints a warning message. The jobs command may then be used to inspect their status. If a second attempt to exit is made without an intervening command, the shell does not print another warning, and the stopped jobs are terminated.
PS1
when it is ready to read a command, and the secondary prompt
PS2
when it needs more input to complete a command.
Bash
allows these prompt strings to be customized by inserting a number of
backslash-escaped special characters that are decoded as follows:
The command number and the history number are usually different:
the history number of a command is its position in the history
list, which may include commands restored from the history file
(see
HISTORY
below), while the command number is the position in the sequence
of commands executed during the current shell session.
After the string is decoded, it is expanded via
parameter expansion, command substitution, arithmetic
expansion, and quote removal, subject to the value of the
promptvars
shell option (see the description of the
shopt
command under
SHELL BUILTIN COMMANDS
below).
SHELL BUILTIN COMMANDS
below).
In this section, the emacs-style notation is used to denote keystrokes. Control keys are denoted by C-key, e.g., C-n means Control-N. Similarly, meta keys are denoted by M-key, so M-x means Meta-X. (On keyboards without a meta key, M-x means ESC x, i.e., press the Escape key then the x key. This makes ESC the meta prefix. The combination M-C-x means ESC-Control-x, or press the Escape key then hold the Control key while pressing the x key.)
Readline commands may be given numeric arguments, which normally act as a repeat count. Sometimes, however, it is the sign of the argument that is significant. Passing a negative argument to a command that acts in the forward direction (e.g., kill-line) causes that command to act in a backward direction. Commands whose behavior with arguments deviates from this are noted below.
When a command is described as killing text, the text deleted is saved for possible future retrieval (yanking). The killed text is saved in a kill ring. Consecutive kills cause the text to be accumulated into one unit, which can be yanked all at once. Commands which do not kill text separate the chunks of text on the kill ring.
Readline is customized by putting commands in an initialization
file (the inputrc file).
The name of this file is taken from the value of the
INPUTRC
variable. If that variable is unset, the default is
~/.inputrc.
When a program which uses the readline library starts up, the
initialization file is read, and the key bindings and variables
are set.
There are only a few basic constructs allowed in the
readline initialization file.
Blank lines are ignored.
Lines beginning with a # are comments.
Lines beginning with a $ indicate conditional constructs.
Other lines denote key bindings and variable settings.
The default key-bindings may be changed with an inputrc file. Other programs that use this library may add their own commands and bindings.
For example, placing
M-Control-u: universal-argument
The following symbolic character names are recognized: RUBOUT, DEL, ESC, LFD, NEWLINE, RET, RETURN, SPC, SPACE, and TAB.
In addition to command names, readline allows keys to be bound to a string that is inserted when the key is pressed (a macro).
The syntax for controlling key bindings in the inputrc file is simple. All that is required is the name of the command or the text of a macro and a key sequence to which it should be bound. The name may be specified in one of two ways: as a symbolic key name, possibly with Meta- or Control- prefixes, or as a key sequence.
When using the form keyname:function-name or macro, keyname is the name of a key spelled out in English. For example:
In the above example, C-u is bound to the function universal-argument, M-DEL is bound to the function backward-kill-word, and C-o is bound to run the macro expressed on the right hand side (that is, to insert the text into the line).
In the second form, "keyseq":function-name or macro, keyseq differs from keyname above in that strings denoting an entire key sequence may be specified by placing the sequence within double quotes. Some GNU Emacs style key escapes can be used, as in the following example, but the symbolic character names are not recognized.
In this example, C-u is again bound to the function universal-argument. C-x C-r is bound to the function re-read-init-file, and ESC [ 1 1 ~ is bound to insert the text
The full set of GNU Emacs style escape sequences is
In addition to the GNU Emacs style escape sequences, a second set of backslash escapes is available:
When entering the text of a macro, single or double quotes must be used to indicate a macro definition. Unquoted text is assumed to be a function name. In the macro body, the backslash escapes described above are expanded. Backslash will quote any other character in the macro text, including " and '.
Bash
allows the current readline key bindings to be displayed or modified
with the
bind
builtin command. The editing mode may be switched during interactive
use by using the
-o
option to the
set
builtin command (see
SHELL BUILTIN COMMANDS
below).
Readline has variables that can be used to further customize its behavior. A variable may be set in the inputrc file with a statement of the form
set variable-name value
Except where noted, readline variables can take the values On or Off. The variables and their default values are:
Readline implements a facility similar in spirit to the conditional compilation features of the C preprocessor which allows key bindings and variable settings to be performed as the result of tests. There are four parser directives used.
$if Bash
# Quote the current or previous word
"\C-xq": "\eb\"\ef\""
$endif
$include /etc/inputrc
Readline provides commands for searching through the command history
(see
HISTORY
below) for lines containing a specified string.
There are two search modes:
incremental
and
non-incremental.
Incremental searches begin before the user has finished typing the search string. As each character of the search string is typed, readline displays the next entry from the history matching the string typed so far. An incremental search requires only as many characters as needed to find the desired history entry. The characters present in the value of the isearch-terminators variable are used to terminate an incremental search. If that variable has not been assigned a value the Escape and Control-J characters will terminate an incremental search. Control-G will abort an incremental search and restore the original line. When the search is terminated, the history entry containing the search string becomes the current line.
To find other matching entries in the history list, type Control-S or Control-R as appropriate. This will search backward or forward in the history for the next entry matching the search string typed so far. Any other key sequence bound to a readline command will terminate the search and execute that command. For instance, a newline will terminate the search and accept the line, thereby executing the command from the history list.
Readline remembers the last incremental search string. If two Control-Rs are typed without any intervening characters defining a new search string, any remembered search string is used.
Non-incremental searches read the entire search string before starting to search for matching history lines. The search string may be typed by the user or be part of the contents of the current line.
The following is a list of the names of the commands and the default key sequences to which they are bound. Command names without an accompanying key sequence are unbound by default. In the following descriptions, point refers to the current cursor position, and mark refers to a cursor position saved by the set-mark command. The text between the point and mark is referred to as the region.
HISTCONTROL
variable. If the line is a modified history
line, then restore the history line to its original state.
HISTORY EXPANSION
below for a description of history expansion.
HISTORY EXPANSION
below for a description of history expansion.
HISTORY EXPANSION
below for a description of history expansion.
ALIASES
above for a description of alias expansion.
$FCEDIT,
$EDITOR,
and emacs as the editor, in that order.
EOF.
ESC
f
is equivalent to
Meta-f.
When word completion is attempted for an argument to a command for
which a completion specification (a compspec) has been defined
using the complete builtin (see
SHELL BUILTIN COMMANDS
below), the programmable completion facilities are invoked.
First, the command name is identified. If a compspec has been defined for that command, the compspec is used to generate the list of possible completions for the word. If the command word is a full pathname, a compspec for the full pathname is searched for first. If no compspec is found for the full pathname, an attempt is made to find a compspec for the portion following the final slash.
Once a compspec has been found, it is used to generate the list of matching words. If a compspec is not found, the default bash completion as described above under Completing is performed.
First, the actions specified by the compspec are used.
Only matches which are prefixed by the word being completed are
returned.
When the
-f
or
-d
option is used for filename or directory name completion, the shell
variable
FIGNORE
is used to filter the matches.
Any completions specified by a filename expansion pattern to the
-G option are generated next.
The words generated by the pattern need not match the word
being completed.
The
GLOBIGNORE
shell variable is not used to filter the matches, but the
FIGNORE
variable is used.
Next, the string specified as the argument to the -W option
is considered.
The string is first split using the characters in the
IFS
special variable as delimiters.
Shell quoting is honored.
Each word is then expanded using
brace expansion, tilde expansion, parameter and variable expansion,
command substitution, arithmetic expansion, and pathname expansion,
as described above under
EXPANSION.
The results are split using the rules described above under
Word Splitting.
The results of the expansion are prefix-matched against the word being
completed, and the matching words become the possible completions.
After these matches have been generated, any shell function or command
specified with the -F and -C options is invoked.
When the command or function is invoked, the
COMP_LINE
and
COMP_POINT
variables are assigned values as described above under
Shell Variables.
If a shell function is being invoked, the
COMP_WORDS
and
COMP_CWORD
variables are also set.
When the function or command is invoked, the first argument is the
name of the command whose arguments are being completed, the
second argument is the word being completed, and the third argument
is the word preceding the word being completed on the current command line.
No filtering of the generated completions against the word being completed
is performed; the function or command has complete freedom in generating
the matches.
Any function specified with -F is invoked first.
The function may use any of the shell facilities, including the
compgen builtin described below, to generate the matches.
It must put the possible completions in the
COMPREPLY
array variable.
Next, any command specified with the -C option is invoked in an environment equivalent to command substitution. It should print a list of completions, one per line, to the standard output. Backslash may be used to escape a newline, if necessary.
After all of the possible completions are generated, any filter specified with the -X option is applied to the list. The filter is a pattern as used for pathname expansion; a & in the pattern is replaced with the text of the word being completed. A literal & may be escaped with a backslash; the backslash is removed before attempting a match. Any completion that matches the pattern will be removed from the list. A leading ! negates the pattern; in this case any completion not matching the pattern will be removed.
Finally, any prefix and suffix specified with the -P and -S options are added to each member of the completion list, and the result is returned to the readline completion code as the list of possible completions.
If the previously-applied actions do not generate any matches, and the -o dirnames option was supplied to complete when the compspec was defined, directory name completion is attempted.
By default, if a compspec is found, whatever it generates is returned to the completion code as the full set of possible completions. The default bash completions are not attempted, and the readline default of filename completion is disabled. If the -o default option was supplied to complete when the compspec was defined, readline's default completion will be performed if the compspec generates no matches.
When a compspec indicates that directory name completion is desired, the programmable completion functions force readline to append a slash to completed names which are symbolic links to directories, subject to the value of the mark-directories readline variable, regardless of the setting of the mark-symlinked-directories readline variable.
HISTSIZE
commands (default 500) is saved. The shell
stores each command in the history list prior to parameter and
variable expansion (see
EXPANSION
above) but after history expansion is performed, subject to the
values of the shell variables
HISTIGNORE
and
HISTCONTROL.
On startup, the history is initialized from the file named by
the variable
HISTFILE
(default ~/.bash_history).
The file named by the value of
HISTFILE
is truncated, if necessary, to contain no more than
the number of lines specified by the value of
HISTFILESIZE.
When an interactive shell exits, the last
$HISTSIZE
lines are copied from the history list to
$HISTFILE.
If the
histappend
shell option is enabled
(see the description of
shopt
under
SHELL BUILTIN COMMANDS
below), the lines are appended to the history file,
otherwise the history file is overwritten.
If
HISTFILE
is unset, or if the history file is unwritable, the history is
not saved. After saving the history, the history file is truncated
to contain no more than
HISTFILESIZE
lines. If
HISTFILESIZE
is not set, no truncation is performed.
The builtin command
fc
(see
SHELL BUILTIN COMMANDS
below) may be used to list or edit and re-execute a portion of
the history list.
The
history
builtin may be used to display or modify the history list and
manipulate the history file.
When using command-line editing, search commands
are available in each editing mode that provide access to the
history list.
The shell allows control over which commands are saved on the history
list. The
HISTCONTROL
and
HISTIGNORE
variables may be set to cause the shell to save only a subset of the
commands entered.
The
cmdhist
shell option, if enabled, causes the shell to attempt to save each
line of a multi-line command in the same history entry, adding
semicolons where necessary to preserve syntactic correctness.
The
lithist
shell option causes the shell to save the command with embedded newlines
instead of semicolons. See the description of the
shopt
builtin below under
SHELL BUILTIN COMMANDS
for information on setting and unsetting shell options.
The shell supports a history expansion feature that
is similar to the history expansion in
csh.
This section describes what syntax features are available. This
feature is enabled by default for interactive shells, and can be
disabled using the
+H
option to the
set
builtin command (see
SHELL BUILTIN COMMANDS
below). Non-interactive shells do not perform history expansion
by default.
History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the current input line, or fix errors in previous commands quickly.
History expansion is performed immediately after a complete line is read, before the shell breaks it into words. It takes place in two parts. The first is to determine which line from the history list to use during substitution. The second is to select portions of that line for inclusion into the current one. The line selected from the history is the event, and the portions of that line that are acted upon are words. Various modifiers are available to manipulate the selected words. The line is broken into words in the same fashion as when reading input, so that several metacharacter-separated words surrounded by quotes are considered one word. History expansions are introduced by the appearance of the history expansion character, which is ! by default. Only backslash (\) and single quotes can quote the history expansion character.
Several shell options settable with the shopt builtin may be used to tailor the behavior of history expansion. If the histverify shell option is enabled (see the description of the shopt builtin), and readline is being used, history substitutions are not immediately passed to the shell parser. Instead, the expanded line is reloaded into the readline editing buffer for further modification. If readline is being used, and the histreedit shell option is enabled, a failed history substitution will be reloaded into the readline editing buffer for correction. The -p option to the history builtin command may be used to see what a history expansion will do before using it. The -s option to the history builtin may be used to add commands to the end of the history list without actually executing them, so that they are available for subsequent recall.
The shell allows control of the various characters used by the history expansion mechanism (see the description of histchars above under Shell Variables).
An event designator is a reference to a command line entry in the history list.
Word designators are used to select desired words from the event. A : separates the event specification from the word designator. It may be omitted if the word designator begins with a ^, $, *, -, or %. Words are numbered from the beginning of the line, with the first word being denoted by 0 (zero). Words are inserted into the current line separated by single spaces.
If a word designator is supplied without an event specification, the previous command is used as the event.
After the optional word designator, there may appear a sequence of one or more of the following modifiers, each preceded by a `:'.
Unless otherwise noted, each builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options.
PATH
are used to find the directory containing
filename.
The file searched for in
PATH
need not be executable.
When bash is not in posix mode, the current directory is
searched if no file is found in
PATH.
If the
sourcepath
option to the
shopt
builtin command is turned off, the
PATH
is not searched.
If any arguments are supplied, they become the positional
parameters when filename is executed. Otherwise the positional
parameters are unchanged.
The return status is the status of the last command exited within
the script (0 if no commands are executed), and false if
filename
is not found or cannot be read.
The return value is 0 unless an unrecognized option is given or an error occurred.
HOME
is the
default
dir.
The variable
CDPATH
defines the search path for the directory containing
dir.
Alternative directory names in
CDPATH
are separated by a colon (:). A null directory name in
CDPATH
is the same as the current directory, i.e., ``.''. If
dir
begins with a slash (/),
then
CDPATH
is not used. The
-P
option says to use the physical directory structure instead of
following symbolic links (see also the
-P
option to the
set
builtin command); the
-L
option forces symbolic links to be followed. An argument of
-
is equivalent to
$OLDPWD.
The return value is true if the directory was successfully changed;
false otherwise.
PATH
are executed. If the
-p
option is given, the search for
command
is performed using a default value for
PATH
that is guaranteed to find all of the standard utilities.
If either the
-V
or
-v
option is supplied, a description of
command
is printed. The
-v
option causes a single word indicating the command or file name
used to invoke
command
to be displayed; the
-V
option produces a more verbose description.
If the
-V
or
-v
option is supplied, the exit status is 0 if
command
was found, and 1 if not. If neither option is supplied and
an error occurred or
command
cannot be found, the exit status is 127. Otherwise, the exit status of the
command
builtin is the exit status of
command.
The matches will be generated in the same way as if the programmable completion code had generated them directly from a completion specification with the same flags. If word is specified, only those completions matching word will be displayed.
The return value is true unless an invalid option is supplied, or no matches were generated.
The process of applying these completion specifications when word completion is attempted is described above under Programmable Completion.
Other options, if specified, have the following meanings. The arguments to the -G, -W, and -X options (and, if necessary, the -P and -S options) should be quoted to protect them from expansion before the complete builtin is invoked.
HOSTFILE
shell variable.
IFS
special variable as delimiters, and each resultant word is expanded.
The possible completions are the members of the resultant list which
match the word being completed.
COMPREPLY
array variable.
The return value is true unless an invalid option is supplied, an option other than -p or -r is supplied without a name argument, an attempt is made to remove a completion specification for a name for which no specification exists, or an error occurs adding a completion specification.
ARITHMETIC EVALUATION )
is performed when the variable is assigned a value.
Using `+' instead of `-' turns off the attribute instead, with the exception that +a may not be used to destroy an array variable. When used in a function, makes each name local, as with the local command. The return value is 0 unless an invalid option is encountered, an attempt is made to define a function using an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax (see Arrays above), one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-existent function with -f.
The return value is 0 unless an invalid option is supplied or n indexes beyond the end of the directory stack.
SIGHUP
is not sent to the job if the shell receives a
SIGHUP.
If no
jobspec
is present, and neither the
-a
nor the
-r
option is supplied, the current job is used.
If no
jobspec
is supplied, the
-a
option means to remove or mark all jobs; the
-r
option without a
jobspec
argument restricts operation to running jobs.
The return value is 0 unless a
jobspec
does not specify a valid job.
PATH
instead of the shell builtin version, run
The
-f
option means to load the new builtin command
name
from shared object
filename,
on systems that support dynamic loading. The
-d
option will delete a builtin previously loaded with
-f.
If no name arguments are given, or if the
-p
option is supplied, a list of shell builtins is printed.
With no other option arguments, the list consists of all enabled
shell builtins.
If -n is supplied, only disabled builtins are printed.
If -a is supplied, the list printed includes all builtins, with an
indication of whether or not each is enabled.
If -s is supplied, the output is restricted to the POSIX
special builtins.
The return value is 0 unless a
name
is not a shell builtin or there is an error loading a new builtin
from a shared object.
EXIT
is executed before the shell terminates.
The
-n
option suppresses
the command numbers when listing. The
-r
option reverses the order of
the commands. If the
-l
option is given,
the commands are listed on
standard output. Otherwise, the editor given by
ename
is invoked
on a file containing those commands. If
ename
is not given, the
value of the
FCEDIT
variable is used, and
the value of
EDITOR
if
FCEDIT
is not set. If neither variable is set,
vi
is used. When editing is complete, the edited commands are
echoed and executed.
In the second form, command is re-executed after each instance of pat is replaced by rep. A useful alias to use with this is so that typing runs the last command beginning with and typing re-executes the last command.
If the first form is used, the return value is 0 unless an invalid option is encountered or first or last specify history lines out of range. If the -e option is supplied, the return value is the value of the last command executed or failure if an error occurs with the temporary file of commands. If the second form is used, the return status is that of the command re-executed, unless cmd does not specify a valid history line, in which case fc returns failure.
OPTIND.
OPTIND
is initialized to 1 each time the shell or a shell script
is invoked. When an option requires an argument,
getopts
places that argument into the variable
OPTARG.
The shell does not reset
OPTIND
automatically; it must be manually reset between multiple
calls to
getopts
within the same shell invocation if a new set of parameters
is to be used.
When the end of options is encountered, getopts exits with a return value greater than zero. OPTIND is set to the index of the first non-option argument, and name is set to ?.
getopts normally parses the positional parameters, but if more arguments are given in args, getopts parses those instead.
getopts
can report errors in two ways. If the first character of
optstring
is a colon,
silent
error reporting is used. In normal operation diagnostic messages
are printed when invalid options or missing option arguments are
encountered.
If the variable
OPTERR
is set to 0, no error messages will be displayed, even if the first
character of
optstring
is not a colon.
If an invalid option is seen,
getopts
places ? into
name
and, if not silent,
prints an error message and unsets
OPTARG.
If
getopts
is silent,
the option character found is placed in
OPTARG
and no diagnostic message is printed.
If a required argument is not found, and
getopts
is not silent,
a question mark (?) is placed in
name,
OPTARG
is unset, and a diagnostic message is printed.
If
getopts
is silent, then a colon (:) is placed in
name
and
OPTARG
is set to the option character found.
getopts returns true if an option, specified or unspecified, is found. It returns false if the end of options is encountered or an error occurs.
HISTFILE
is used. Options, if supplied, have the following meanings:
The return value is 0 unless an invalid option is encountered, an error occurs while reading or writing the history file, an invalid offset is supplied as an argument to -d, or the history expansion supplied as an argument to -p fails.
If jobspec is given, output is restricted to information about that job. The return status is 0 unless an invalid option is encountered or an invalid jobspec is supplied.
If the -x option is supplied, jobs replaces any jobspec found in command or args with the corresponding process group ID, and executes command passing it args, returning its exit status.
SIGKILL
or a signal number;
signum
is a signal number. If
sigspec
is a signal name, the name may be
given with or without the
SIG
prefix.
If
sigspec
is not present, then
SIGTERM
is assumed.
An argument of
-l
lists the signal names.
If any arguments are supplied when
-l
is given, the names of the signals corresponding to the arguments are
listed, and the return status is 0.
The exit_status argument to
-l
is a number specifying either a signal number or the exit status of
a process terminated by a signal.
kill
returns true if at least one signal was successfully sent, or false
if an error occurs or an invalid option is encountered.
ARITHMETIC EVALUATION).
If the last
arg
evaluates to 0,
let
returns 1; 0 is returned otherwise.
If the popd command is successful, a dirs is performed as well, and the return status is 0. popd returns false if an invalid option is encountered, the directory stack is empty, a non-existent directory stack entry is specified, or the directory change fails.
The format is reused as necessary to consume all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied. The return value is zero on success, non-zero on failure.
If the pushd command is successful, a dirs is performed as well. If the first form is used, pushd returns 0 unless the cd to dir fails. With the second form, pushd returns 0 unless the directory stack is empty, a non-existent directory stack element is specified, or the directory change to the specified new current directory fails.
IFS
are used to split the line into words.
The backslash character (\) may be used to remove any special
meaning for the next character read and for line continuation.
Options, if supplied, have the following meanings:
READLINE
above) is used to obtain the line.
If no
names
are supplied, the line read is assigned to the variable
REPLY.
The return code is zero, unless end-of-file is encountered, read
times out, or an invalid file descriptor is supplied as the argument to
-u.
SHELL GRAMMAR
above) exits with a non-zero status. The shell does not exit if the
command that fails is part of an
until
or
while
loop,
part of an
if
statement, part of a
&&
or
||
list, or if the command's return value is
being inverted via
!.
A trap on ERR, if set, is executed before the shell exits.
JOB CONTROL
above). Background processes run in a separate process
group and a line containing their exit status is printed
upon their completion.
HISTORY.
This option is on by default in interactive shells.
If -o is supplied with no option-name, the values of the current options are printed. If +o is supplied with no option-name, a series of set commands to recreate the current option settings is displayed on the standard output.
$ENV
and
$BASH_ENV
files are not processed, shell functions are not inherited from the
environment, and the
SHELLOPTS
variable, if it appears in the environment, is ignored.
If the shell is started with the effective user (group) id not equal to the
real user (group) id, and the -p option is not supplied, these actions
are taken and the effective user id is set to the real user id.
If the -p option is supplied at startup, the effective user id is
not reset.
Turning this option off causes the effective user
and group ids to be set to the real user and group ids.
PS4,
followed by the command and its expanded arguments.
The options are off by default unless otherwise noted. Using + rather than - causes these options to be turned off. The options can also be specified as arguments to an invocation of the shell. The current set of options may be found in $-. The return status is always true unless an invalid option is encountered.
If either -s or -u is used with no optname arguments, the display is limited to those options which are set or unset, respectively. Unless otherwise noted, the shopt options are disabled (unset) by default.
The return status when listing options is zero if all optnames are enabled, non-zero otherwise. When setting or unsetting options, the return status is zero unless an optname is not a valid shell option.
The list of shopt options is:
LINES
and
COLUMNS.
ALIASES.
This option is enabled by default for interactive shells.
READLINE
above).
This is enabled by default.
SIGHUP
to all jobs when an interactive login shell exits.
COMMENTS
above). This option is enabled by default.
INVOCATION
above).
The value may not be changed.
PROMPTING
above. This option is enabled by default.
RESTRICTED SHELL
below).
The value may not be changed.
This is not reset when the startup files are executed, allowing
the startup files to discover whether or not a shell is restricted.
PATH
to find the directory containing the file supplied as an argument.
This option is enabled by default.
SIGCONT
signal. The
-f
option says not to complain if this is
a login shell; just suspend anyway. The return status is 0 unless
the shell is a login shell and
-f
is not supplied, or if job control is not enabled.
CONDITIONAL EXPRESSIONS.
Expressions may be combined using the following operators, listed
in decreasing order of precedence.
test and [ evaluate conditional expressions using a set of rules based on the number of arguments.
CONDITIONAL EXPRESSIONS,
the expression is true if the unary test is true.
If the first argument is not a valid unary conditional operator, the expression
is false.
CONDITIONAL EXPRESSIONS,
the result of the expression is the result of the binary test using
the first and third arguments as operands.
If the first argument is !, the value is the negation of
the two-argument test using the second and third arguments.
If the first argument is exactly ( and the third argument is
exactly ), the result is the one-argument test of the second
argument.
Otherwise, the expression is false.
The -a and -o operators are considered binary operators
in this case.
EXIT
(0) the command
arg
is executed on exit from the shell.
If a
sigspec
is
DEBUG,
the command
arg
is executed after every simple command (see
SHELL GRAMMAR
above).
If a
sigspec
is
ERR,
the command
arg
is executed whenever a simple command has a non-zero exit status.
The
ERR
trap is not executed if the failed command is part of an
until
or
while
loop,
part of an
if
statement, part of a
&&
or
||
list, or if the command's return value is
being inverted via
!.
The
-l
option causes the shell to print a list of signal names and
their corresponding numbers.
Signals ignored upon entry to the shell cannot be trapped or reset.
Trapped signals are reset to their original values in a child
process when it is created.
The return status is false if any
sigspec
is invalid; otherwise
trap
returns true.
PATH
search for each name, even if
would not return
file.
If a command is hashed,
-p
and
-P
print the hashed value, not necessarily the file that appears
first in
PATH.
If the
-a
option is used,
type
prints all of the places that contain
an executable named
name.
This includes aliases and functions,
if and only if the
-p
option is not also used.
The table of hashed commands is not consulted
when using
-a.
The
-f
option suppresses shell function lookup, as with the command builtin.
type
returns true if any of the arguments are found, false if
none are found.
If limit is given, it is the new value of the specified resource (the -a option is display only). If no option is given, then -f is assumed. Values are in 1024-byte increments, except for -t, which is in seconds, -p, which is in units of 512-byte blocks, and -n and -u, which are unscaled values. The return status is 0 unless an invalid option or argument is supplied, or an error occurs while setting a new limit.
RANDOM,
SECONDS,
LINENO,
HISTCMD,
FUNCNAME,
GROUPS,
or
DIRSTACK
are unset, they lose their special properties, even if they are
subsequently reset. The exit status is true unless a
name
does not exist or is readonly.
If bash is started with the name rbash, or the -r option is supplied at invocation, the shell becomes restricted. A restricted shell is used to set up an environment more controlled than the standard shell. It behaves identically to bash with the exception that the following are disallowed or not performed:
These restrictions are enforced after any startup files are read.
When a command that is found to be a shell script is executed (see
COMMAND EXECUTION
above),
rbash
turns off any restrictions in the shell spawned to execute the
script.
/bin/bash
/etc/profile
~/.bash_profile
~/.bashrc
~/.bash_logout
~/.inputrc
Chet Ramey, Case Western Reserve University
chet@ins.CWRU.Edu
Once you have determined that a bug actually exists, use the bashbug command to submit a bug report. If you have a fix, you are encouraged to mail that as well! Suggestions and `philosophical' bug reports may be mailed to bug-bash@gnu.org or posted to the Usenet newsgroup gnu.bash.bug.
ALL bug reports should include:
Comments and bug reports concerning this manual page should be directed to chet@ins.CWRU.Edu.
It's too big and too slow.
There are some subtle differences between
bash
and traditional versions of
sh,
mostly because of the
POSIX
specification.
Aliases are confusing in some uses.
Shell builtin commands and functions are not stoppable/restartable.
Compound commands and command sequences of the form `a ; b ; c' are not handled gracefully when process suspension is attempted. When a process is stopped, the shell immediately executes the next command in the sequence. It suffices to place the sequence of commands between parentheses to force it into a subshell, which may be stopped as a unit.
Commands inside of $(...) command substitution are not parsed until substitution is attempted. This will delay error reporting until some time after the command is entered.
Array variables may not (yet) be exported.
| webmaster donations bookstore | delorie software privacy |
| Copyright © 2003 by The Free Software Foundation | Updated Jun 2003 |