bash [options] [file]

Bash is Copyright (C) 1989-2004 by the Free Software Foundation, Inc.

Bash is an sh-compatible command language interpreter that executes
commands read from the standard input or from a file. Bash also
incorporates useful features from the Korn and C shells (ksh and csh).

Bash is intended to be a conformant implementation of the IEEE POSIX
Shell and Tools specification (IEEE Working Group 1003.2).

In addition to the single-character shell options documented in the
description of the set builtin command, bash interprets the following
options when it is invoked:

-c string If the -c option is present, then commands are read from
-i If the -i option is present, the shell is interactive.
-l Make bash act as if it had been invoked as a login shell
-r If the -r option is present, the shell becomes restricted
-s If the -s option is present, or if no arguments remain after
-D A list of all double-quoted strings preceded by $ is printed
[-+]O [shopt_option]
-- A -- signals the end of options and disables further option

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.

--help Display a usage message on standard output and exit success-
--init-file file
--rcfile file




--norc Do not read and execute the personal initialization file





If arguments remain after option processing, and neither the -c nor
the -s option has been supplied, the first argument is assumed to be
the name of a file containing shell commands. If bash is invoked in
this fashion, $0 is set to the name of the file, and the positional
parameters are set to the remaining arguments. Bash reads and exe-
cutes commands from this file, then exits. Bash's exit status is the
exit status of the last command executed in the script. If no com-
mands are executed, the exit status is 0. An attempt is first made to
open the file in the current directory, and, if no file is found, then
the shell searches the directories in PATH for the script.

A login shell is one whose first character of argument zero is a -, or
one started with the --login option.

An interactive shell is one started without non-option arguments and
without the -c option whose standard input and error are both con-
nected 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-inter-
active shell with the --login option, it first reads and executes com-
mands from the file /etc/profile, if that file exists. After reading
that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.pro-
file, 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

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 fol-
lowing command were executed:
but the value of the PATH variable is not used to search for the file

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 interac-
tive 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 docu-
blank A space or tab.
word A sequence of characters considered as a single unit by the
name A word consisting only of alphanumeric characters and under-
control operator

Reserved words are words that have a special meaning to the shell.
The following words are recognized as reserved when unquoted and
either the first word of a simple command (see SHELL GRAMMAR below) or
the third word of a case or for command:

! case do done elif else esac fi for function if in select then until
while { } time [[ ]]

Simple Commands
A simple command is a sequence of optional variable assignments fol-
lowed by blank-separated words and redirections, and terminated by a
control operator. The first word specifies the command to be exe-
cuted, 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:

The standard output of command is connected via a pipe to the standard
input of command2. This connection is performed before any redirec-
tions specified by the command (see REDIRECTION below).

The return status of a pipeline is the exit status of the last com-
mand, unless the pipefail option is enabled. If pipefail is enabled,
the pipeline's return status is the value of the last (rightmost) com-
mand to exit with a non-zero status, or zero if all commands exit suc-
cessfully. If the reserved word ! precedes a pipeline, the exit sta-
tus of that pipeline is the logical negation of the exit status as
described above. 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 .

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 exe-
cutes 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, respec-
tively. An AND list has the form

command2 is executed if, and only if, command1 returns an exit status
of zero.

An OR list has the form

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.

Compound Commands
A compound command is one of the following:

(list) list is executed in a subshell environment (see COMMAND EXECU-

{ list; }


[[ expression ]]

for name [ in word ] ; do list ; done

for (( expr1 ; expr2 ; expr3 )) ; do list ; done

select name [ in word ] ; do list ; done

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

if list; then list; [ elif list; then list; ] ... [ else list; ] fi

while list; do list; done
until list; do list; done

Shell Function Definitions
A shell function is an object that is called like a simple command and
executes a compound command with a new set of positional parameters.
Shell functions are declared as follows:

[ function ] name () compound-command [redirection]

In a non-interactive shell, or an interactive shell in which the
interactive_comments option to the shopt builtin is enabled (see 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 inter-
active shells.

Quoting is used to remove the special meaning of certain characters or
words to the shell. Quoting can be used to disable special treatment
for special characters, to prevent reserved words from being recog-
nized as such, and to prevent parameter expansion.

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 his-
tory expansion character, usually !, must be quoted to prevent history

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 . If a \ pair appears, and the backslash is not
itself quoted, the \ 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 . A dou-
ble quote may be quoted within double quotes by preceding it with a
backslash. When command history is being used, the double quote may
not be used to quote the history expansion character.

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 cur-
rent locale is C or POSIX, the dollar sign is ignored. If the string
is translated and replaced, the replacement is double-quoted.

A parameter is an entity that stores values. It can be a name, a num-
ber, or one of the special characters listed below under Special
Parameters. A variable is a parameter denoted by a name. A variable
has a value and zero or more attributes. Attributes are assigned
using the declare builtin command (see declare below in SHELL BUILTIN

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

If value is not given, the variable is assigned the null string. All
values undergo tilde expansion, parameter and variable expansion, com-
mand substitution, arithmetic expansion, and quote removal (see EXPAN-
SION below). If the variable has its integer attribute set, then
value is evaluated as an arithmetic expression even if the $((...))
expansion is not used (see Arithmetic Expansion below). Word split-
ting 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 alias,
declare, typeset, export, readonly, and local builtin commands.

Positional Parameters
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

When a positional parameter consisting of more than a single digit is
expanded, it must be enclosed in braces (see EXPANSION below).

Special Parameters
The shell treats several parameters specially. These parameters may
only be referenced; assignment to them is not allowed.
* Expands to the positional parameters, starting from one. When
@ Expands to the positional parameters, starting from one. When
# Expands to the number of positional parameters in decimal.
? Expands to the status of the most recently executed foreground
- Expands to the current option flags as specified upon invoca-
$ Expands to the process ID of the shell. In a () subshell, it
! Expands to the process ID of the most recently executed back-
0 Expands to the name of the shell or shell script. This is set
_ At shell startup, set to the absolute file name of the shell or

Shell Variables
The following variables are set by the shell:

BASH Expands to the full file name used to invoke this instance of








EUID Expands to the effective user ID of the current user, initial-


GROUPS An array variable containing the list of groups of which the




LINENO Each time this parameter is referenced, the shell substitutes a


OLDPWD The previous working directory as set by the cd command.

OPTARG The value of the last option argument processed by the getopts

OPTIND The index of the next argument to be processed by the getopts

OSTYPE Automatically set to a string that describes the operating sys-


PPID The process ID of the shell's parent. This variable is read-

PWD The current working directory as set by the cd command.

RANDOM Each time this parameter is referenced, a random integer

REPLY Set to the line of input read by the read builtin command when



SHLVL Incremented by one each time an instance of bash is started.

UID Expands to the user ID of the current user, initialized at

The following variables are used by the shell. In some cases, bash
assigns a default value to a variable; these cases are noted below.

CDPATH The search path for the cd command. This is a colon-separated
EMACS If bash finds this variable in the environment when the shell
FCEDIT The default editor for the fc builtin command.
HOME The home directory of the current user; the default argument
IFS The Internal Field Separator that is used for word splitting
LANG Used to determine the locale category for any category not
LC_ALL This variable overrides the value of LANG and any other LC_
LINES Used by the select builtin command to determine the column
MAIL If this parameter is set to a file name and the MAILPATH vari-
OPTERR If set to the value 1, bash displays error messages generated
PATH The search path for commands. It is a colon-separated list of
PS1 The value of this parameter is expanded (see PROMPTING below)
PS2 The value of this parameter is expanded as with PS1 and used as
PS3 The value of this parameter is used as the prompt for the
PS4 The value of this parameter is expanded as with PS1 and the
SHELL The full pathname to the shell is kept in this environment

TMOUT If set to a value greater than zero, TMOUT is treated as the



Bash provides one-dimensional array variables. Any variable may be
used as an array; the declare builtin will explicitly declare an
array. There is no maximum limit on the size of an array, nor any
requirement that members be indexed or assigned contiguously. Arrays
are indexed using integers and are zero-based.

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 [sub-
script]=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 char-
acter 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 equiva-
lent 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.

Expansion is performed on the command line after it has been split
into words. There are seven kinds of expansion performed: brace
expansion, tilde expansion, parameter and variable expansion, command
substitution, arithmetic expansion, word splitting, and pathname

The order of expansions is: brace expansion, tilde expansion, parame-
ter, 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 PARAME-

Brace Expansion
Brace expansion is a mechanism by which arbitrary strings may be gen-
erated. 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 either a series of
comma-separated strings or a sequence expression 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'.

A sequence expression takes the form {x..y}, where x and y are either
integers or single characters. When integers are supplied, the
expression expands to each number between x and y, inclusive. When
characters are supplied, the expression expands to each character lex-
icographically between x and y, inclusive. Note that both x and y
must be of the same type.

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 interpreta-
tion 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 or a valid sequence
expression. 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 param-
eter expansion, the string ${ is not considered eligible for brace

This construct is typically used as shorthand when the common prefix
of the strings to be generated is longer than in the above example:


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

Tilde Expansion
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 direc-
tory of the user executing the shell is substituted instead. Other-
wise, 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 imme-
diately 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.

Parameter Expansion
The '$' character introduces parameter expansion, command substitu-
tion, 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 fol-
lowing 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


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 vari-
able; 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 exceptions to this are the
expansions of ${!prefix*} and ${!name[@]} described below. The excla-
mation point must immediately follow the left brace in order to intro-
duce indirection.

In each of the cases below, word is subject to tilde expansion, param-
eter 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 parame-
ter that is unset.








Command Substitution
Command substitution allows the output of a command to replace the
command name. There are two forms:


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 back-
quoted 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
Arithmetic expansion allows the evaluation of an arithmetic expression
and the substitution of the result. The format for arithmetic expan-
sion is:

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 expan-
sion, command substitution, and quote removal. Arithmetic expansions
may be nested.

The evaluation is performed according to the rules listed below under
ARITHMETIC EVALUATION. If expression is invalid, bash prints a mes-
sage indicating failure and no substitution occurs.

Process Substitution
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 out-
put 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

Word Splitting
The shell scans the results of parameter expansion, command substitu-
tion, 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 , 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 split-
ting 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.

Pathname Expansion
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 dis-
abled, the word is left unchanged. If the nullglob option is set, and
no matches are found, the word is removed. If the failglob shell
option is set, and no matches are found, an error message is printed
and the command is not executed. If the shell option nocaseglob is
enabled, the match is performed without regard to the case of alpha-
betic 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, fail-
glob, 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 when GLOBIGNORE is set and not null. However, setting
GLOBIGNORE to a non-null value 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 pat-
tern characters described below, matches itself. The NUL character
may not occur in a pattern. A backslash escapes the following charac-
ter; the escaping backslash is discarded when matching. The special
pattern characters must be quoted if they are to be matched literally.

The special pattern characters have the following meanings:

* Matches any string, including the null string.
? Matches any single character.
[...] Matches any one of the enclosed characters. A pair of charac-

If the extglob shell option is enabled using the shopt builtin, sev-
eral extended pattern matching operators are recognized. In the fol-
lowing 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:

Quote Removal
After the preceding expansions, all unquoted occurrences of the char-
acters \, ', and " that did not result from one of the above expan-
sions are removed.

Before a command is executed, its input and output may be redirected
using a special notation interpreted by the shell. Redirection may
also be used to open and close files for the current shell execution
environment. The following redirection operators may precede or
appear anywhere within a simple command or may follow a command.
Redirections are processed in the order they appear, from left to

In the following descriptions, if the file descriptor number is omit-
ted, 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 descrip-
tions, 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

directs both standard output and standard error to the file dirlist,
while the command

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 redi-
rections, as described in the following table:

A failure to open or create a file causes the redirection to fail.

Redirecting Input
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:

Redirecting Output
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:

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.

Appending Redirected Output
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:

Redirecting Standard Output and Standard Error
Bash allows both the standard output (file descriptor 1) and the stan-
dard 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


Of the two forms, the first is preferred. This is semantically equiv-
alent to

Here Documents
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:

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 \ 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

Here Strings
A variant of here documents, the format is:

The word is expanded and supplied to the command on its standard

Duplicating File Descriptors
The redirection operator

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 evalu-
ates to -, file descriptor n is closed. If n is not specified, the
standard input (file descriptor 0) is used.

The operator

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.

Moving File Descriptors
The redirection operator

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

moves the file descriptor digit to file descriptor n, or the standard
output (file descriptor 1) if n is not specified.

Opening File Descriptors for Reading and Writing
The redirection operator

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.

Aliases allow a string to be substituted for a word when it is used as
the first word of a simple command. The shell maintains a list of
aliases that may be set and unset with the alias and unalias builtin
commands (see SHELL BUILTIN COMMANDS below). The first word of each
simple 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 characters /,
$, ', and = and any of the shell metacharacters or quoting characters
listed above may not appear in an alias name. The replacement text
may contain any valid shell input, including shell metacharacters.
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 com-
mand 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

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 exe-
cuted. 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.

A shell function, defined as described above under 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 exe-
cuted 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. Special parameter 0 is
unchanged. The first element of 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) or the -o
functrace shell option has been enabled with the set builtin (in which
case all functions inherit the DEBUG trap).

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 func-
tion call. Any command associated with the RETURN trap is executed
before execution resumes. 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 (and optionally the source
file and line number, if the extdebug shell option is enabled). Func-
tions may be exported so that subshells automatically have them
defined with the -f option to the export builtin. Note that shell
functions and variables with the same name may result in multiple
identically-named entries in the environment passed to the shell's
children. Care should be taken in cases where this may cause a prob-

Functions may be recursive. No limit is imposed on the number of
recursive calls.

The shell allows arithmetic expressions to be evaluated, under certain
circumstances (see the let and declare builtin commands and Arithmetic
Expansion). Evaluation is done in fixed-width integers with no check
for overflow, though division by 0 is trapped and flagged as an error.
The operators and their precedence, associativity, and values are the
same as in the C language. The following list of operators is grouped
into levels of equal-precedence operators. The levels are listed in
order of decreasing precedence.

id++ id--
++id --id
- + unary minus and plus
! ~ logical and bitwise negation
** exponentiation
* / % multiplication, division, remainder
+ - addition, subtraction
<< >> left and right bitwise shifts
<= >= < >
== != equality and inequality
& bitwise AND
^ bitwise exclusive OR
| bitwise OR
&& logical AND
|| logical OR
= *= /= %= += -= <<= >>= &= ^= |=
expr1 , expr2

Shell variables are allowed as operands; parameter expansion is per-
formed before the expression is evaluated. Within an expression,
shell variables may also be referenced by name without using the
parameter expansion syntax. A shell variable that is null or unset
evaluates to 0 when referenced by name without using the parameter
expansion syntax. The value of a variable is evaluated as an arith-
metic expression when it is referenced, or when a variable which has
been given the integer attribute using declare -i is assigned a value.
A null value evaluates to 0. A shell variable need not have its inte-
ger attribute turned on to be used in an expression.

Constants with a leading 0 are interpreted as octal numbers. A lead-
ing 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 repre-
sented by the lowercase letters, the uppercase letters, @, and _, in
that order. If base is less than or equal to 36, lowercase and upper-
case 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

Conditional expressions are used by the [[ compound command and the
test and [ builtin commands to test file attributes and perform string
and arithmetic comparisons. Expressions are formed from the following
unary or binary primaries. If any file argument to one of the pri-
maries is of the form /dev/fd/n, then file descriptor n is checked.
If the file argument to one of the primaries is one of /dev/stdin,
/dev/stdout, or /dev/stderr, file descriptor 0, 1, or 2, respectively,
is checked.

-a file
-b file
-c file
-d file
-e file
-f file
-g file
-h file
-k file
-p file
-r file
-s file
-t fd True if file descriptor fd is open and refers to a terminal.
-u file
-w file
-x file
-O file
-G file
-L file
-S file
-N file
file1 -nt file2
file1 -ot file2
file1 -ef file2
-o optname
-z string
-n string

string1 == string2

string1 != string2

string1 < string2

string1 > string2

arg1 OP arg2

When a simple command is executed, the shell performs the following
expansions, assignments, and redirections, from left to right.

1. The words that the parser has marked as variable assignments

2. The words that are not variable assignments or redirections are

3. Redirections are performed as described above under REDIREC-

4. The text after the = in each variable assignment undergoes

If no command name results, the variable assignments affect the cur-
rent 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 expan-
sions 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.

After a command has been split into words, if it results in a simple
command and an optional list of arguments, the following actions are

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 con-
taining 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 exe-
cution environment. Argument 0 is set to the name given, and the
remaining arguments to the command are set to the arguments given, if

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 con-
sist 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.

The shell has an execution environment, which consists of the follow-

? open files inherited by the shell at invocation, as modified by

? the current working directory as set by cd, pushd, or popd, or

? the file creation mode mask as set by umask or inherited from

? current traps set by trap

? shell parameters that are set by variable assignment or with

? shell functions defined during execution or inherited from the

? options enabled at invocation (either by default or with com-

? options enabled by shopt

? shell aliases defined with alias

? various process IDs, including those of background jobs, the

When a simple command other than a builtin or shell function is to be
executed, it is invoked in a separate execution environment that con-
sists of the following. Unless otherwise noted, the values are inher-
ited from the shell.

? the shell's open files, plus any modifications and additions

? the current working directory

? the file creation mode mask

? shell variables and functions marked for export, along with

? traps caught by the shell are reset to the values inherited

A command invoked in this separate environment cannot affect the
shell's execution environment.

Command substitution, commands grouped with parentheses, and asyn-
chronous 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 environ-

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.

When a program is invoked it is given an array of strings called the
environment. This is a list of name-value pairs, of the form

The shell provides several ways to manipulate the environment. On
invocation, the shell scans its own environment and creates a parame-
ter 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 environ-
ment, 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 envi-

For the shell's purposes, a command which exits with a zero exit sta-
tus has succeeded. An exit status of zero indicates success. A non-
zero exit status indicates failure. When a command terminates on a
fatal signal N, bash uses the value of 128+N as the exit status.

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

When bash is interactive, in the absence of any traps, it ignores
SIGTERM (so that kill 0 does not kill an interactive shell), and SIG-
INT is caught and handled (so that the wait builtin is interruptible).
In all cases, bash ignores SIGQUIT. If job control is in effect, bash

Non-builtin commands run by bash have signal handlers set to the val-
ues inherited by the shell from its parent. When job control is not
in effect, asynchronous commands ignore SIGINT and SIGQUIT in addition
to these inherited handlers. Commands run as a result of command sub-
stitution ignore the keyboard-generated job control signals SIGTTIN,

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 partic-
ular 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.

If 0for which a trap has been set, the trap will not be executed until
the command completes. When bash is waiting for an asynchronous com-
mand 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 exe-

Job control refers to the ability to selectively stop (suspend) the
execution of processes and continue (resume) their execution at a
later point. A user typically employs this facility via an interac-
tive interface supplied jointly by the system's terminal driver and

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:

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 pro-
cess 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 (SIGT-
TOU) signal by the terminal driver, which, unless caught, suspends the

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 pro-
cess 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 char-
acter % 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 exam-
ple, %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 sub-
string 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.

When executing interactively, bash displays the primary prompt 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 substitu-
tion, arithmetic expansion, and quote removal, subject to the value of
the promptvars shell option (see the description of the shopt command

This is the library that handles reading input when using an interac-
tive shell, unless the --noediting option is given at shell invoca-
tion. By default, the line editing commands are similar to those of
emacs. A vi-style line editing interface is also available. To turn
off line editing after the shell is running, use the +o emacs or +o vi
options to the set builtin (see SHELL BUILTIN COMMANDS below).

Readline Notation
In this section, the emacs-style notation is used to denote
keystrokes. Control keys are denoted by C-key, e.g., C-n means Con-
trol-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 Initialization
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 read-
line 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 bind-

For example, placing

into the inputrc would make M-C-u execute the readline command univer-

The following symbolic character names are recognized: RUBOUT, DEL,

In addition to command names, readline allows keys to be bound to a
string that is inserted when the key is pressed (a macro).

Readline Key Bindings
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 speci-
fied 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 ''> output'' 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-argu-
ment. C-x C-r is bound to the function re-read-init-file, and ESC [ 1
1 ~ is bound to insert the text ''Function Key 1''.

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 modi-
fied with the bind builtin command. The editing mode may be switched
during interactive use by using the -o option to the set builtin com-
mand (see SHELL BUILTIN COMMANDS below).

Readline Variables
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

Except where noted, readline variables can take the values On or Off.
The variables and their default values are:

bell-style (audible)
comment-begin (''#'')
completion-ignore-case (Off)
completion-query-items (100)
convert-meta (On)
disable-completion (Off)
editing-mode (emacs)
enable-keypad (Off)
expand-tilde (Off)
horizontal-scroll-mode (Off)
input-meta (Off)
isearch-terminators (''C-[C-J'')
keymap (emacs)
mark-directories (On)
mark-modified-lines (Off)
mark-symlinked-directories (Off)
match-hidden-files (On)
output-meta (Off)
page-completions (On)
print-completions-horizontally (Off)
show-all-if-ambiguous (Off)
show-all-if-unmodified (Off)
visible-stats (Off)

Readline Conditional Constructs
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 The $if construct allows bindings to be made based on the edit-

$endif This command, as seen in the previous example, terminates an

$else Commands in this branch of the $if directive are executed if


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, read-
line 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 con-
taining 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 termi-
nate the search and accept the line, thereby executing the command
from the history list.

Readline remembers the last incremental search string. If two Con-
trol-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.

Readline Command Names
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.

Commands for Moving
beginning-of-line (C-a)
end-of-line (C-e)
forward-char (C-f)
backward-char (C-b)
forward-word (M-f)
backward-word (M-b)
clear-screen (C-l)

Commands for Manipulating the History
accept-line (Newline, Return)
previous-history (C-p)
next-history (C-n)
beginning-of-history (M-<)
end-of-history (M->)
reverse-search-history (C-r)
forward-search-history (C-s)
non-incremental-reverse-search-history (M-p)
non-incremental-forward-search-history (M-n)
yank-nth-arg (M-C-y)
yank-last-arg (M-., M-_)
shell-expand-line (M-C-e)
history-expand-line (M-^)
insert-last-argument (M-., M-_)
operate-and-get-next (C-o)
edit-and-execute-command (C-xC-e)

Commands for Changing Text
delete-char (C-d)
backward-delete-char (Rubout)
quoted-insert (C-q, C-v)
tab-insert (C-v TAB)
self-insert (a, b, A, 1, !, ...)
transpose-chars (C-t)
transpose-words (M-t)
upcase-word (M-u)
downcase-word (M-l)
capitalize-word (M-c)

Killing and Yanking
kill-line (C-k)
backward-kill-line (C-x Rubout)
unix-line-discard (C-u)
kill-word (M-d)
backward-kill-word (M-Rubout)
unix-word-rubout (C-w)
delete-horizontal-space (M-\)
yank (C-y)
yank-pop (M-y)

Numeric Arguments
digit-argument (M-0, M-1, ..., M--)

complete (TAB)
possible-completions (M-?)
insert-completions (M-*)
complete-filename (M-/)
possible-filename-completions (C-x /)
complete-username (M-~)
possible-username-completions (C-x ~)
complete-variable (M-$)
possible-variable-completions (C-x $)
complete-hostname (M-@)
possible-hostname-completions (C-x @)
complete-command (M-!)
possible-command-completions (C-x !)
dynamic-complete-history (M-TAB)
complete-into-braces (M-{)

Keyboard Macros
start-kbd-macro (C-x ()
end-kbd-macro (C-x ))
call-last-kbd-macro (C-x e)

re-read-init-file (C-x C-r)
abort (C-g)
do-uppercase-version (M-a, M-b, M-x, ...)
prefix-meta (ESC)
undo (C-_, C-x C-u)
revert-line (M-r)
tilde-expand (M-&)
set-mark (C-@, M-)
exchange-point-and-mark (C-x C-x)
character-search (C-])
character-search-backward (M-C-])
insert-comment (M-#)
glob-complete-word (M-g)
glob-expand-word (C-x *)
glob-list-expansions (C-x g)
display-shell-version (C-x C-v)

Programmable Completion
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 pro-
grammable 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 possi-
ble completions for the word. If the command word is a full pathname,
a compspec for the full pathname is searched for first. If no comp-
spec 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 comple-
tion 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 consid-
ered. The string is first split using the characters in the IFS spe-
cial 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 envi-
ronment 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 speci-
fied with the -X option is applied to the list. The filter is a pat-
tern 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 com-

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.

If the -o plusdirs option was supplied to complete when the compspec
was defined, directory name completion is attempted and any matches
are added to the results of the other actions.

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 bashdefault option was
supplied to complete when the compspec was defined, the bash default
completions are attempted if the compspec generates no matches. If
the -o default option was supplied to complete when the compspec was
defined, readline's default completion will be performed if the comp-
spec (and, if attempted, the default bash completions) generate no

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.

When the -o history option to the set builtin is enabled, the shell
provides access to the command history, the list of commands previ-
ously typed. The value of the HISTSIZE variable is used as the number
of commands to save in a history list. The text of the last 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 semi-
colons where necessary to preserve syntactic correctness. The lithist
shell option causes the shell to save the command with embedded new-
lines 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 sur-
rounded 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 characters inhibit history expansion if found immediately fol-
lowing the history expansion character, even if it is unquoted: space,
tab, newline, carriage return, and =. If the extglob shell option is
enabled, ( will also inhibit expansion.

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 read-
line 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).

Event Designators
An event designator is a reference to a command line entry in the his-
tory list.

! Start a history substitution, except when followed by a blank,
!n Refer to command line n.
!-n Refer to the current command line minus n.
!! Refer to the previous command. This is a synonym for '!-1'.
!# The entire command line typed so far.

Word Designators
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 sepa-
rated by single spaces.

0 (zero)
n The nth word.
^ The first argument. That is, word 1.
$ The last argument.
% The word matched by the most recent '?string?' search.
x-y A range of words; '-y' abbreviates '0-y'.
* All of the words but the zeroth. This is a synonym for '1-$'.
x* Abbreviates x-$.
x- Abbreviates x-$ like x*, but omits the last word.

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 ':'.

h Remove a trailing file name component, leaving only the head.
t Remove all leading file name components, leaving the tail.
r Remove a trailing suffix of the form .xxx, leaving the base-
e Remove all but the trailing suffix.
p Print the new command but do not execute it.
q Quote the substituted words, escaping further substitutions.
x Quote the substituted words as with q, but break into words at
& Repeat the previous substitution.
g Cause changes to be applied over the entire event line. This
G Apply the following 's' modifier once to each word in the event

Unless otherwise noted, each builtin command documented in this sec-
tion as accepting options preceded by - accepts -- to signify the end
of the options.
: [arguments]

. filename [arguments]
source filename [arguments]

alias [-p] [name[=value] ...]

bg [jobspec]

bind [-m keymap] [-lpsvPSV]
bind [-m keymap] [-q function] [-u function] [-r keyseq]
bind [-m keymap] -f filename
bind [-m keymap] -x keyseq:shell-command
bind [-m keymap] keyseq:function-name
bind readline-command

break [n]

builtin shell-builtin [arguments]

cd [-L|-P] [dir]

caller [expr]

command [-pVv] command [arg ...]

compgen [option] [word]

complete [-abcdefgjksuv] [-o comp-option] [-A action] [-G globpat] [-W
wordlist] [-P prefix] [-S suffix]
complete -pr [name ...]

continue [n]

declare [-afFirtx] [-p] [name[=value] ...]
typeset [-afFirtx] [-p] [name[=value] ...]

dirs [-clpv] [+n] [-n]

disown [-ar] [-h] [jobspec ...]

echo [-neE] [arg ...]

enable [-adnps] [-f filename] [name ...]

eval [arg ...]

exec [-cl] [-a name] [command [arguments]]

exit [n]

export [-fn] [name[=word]] ...
export -p

fc [-e ename] [-nlr] [first] [last]
fc -s [pat=rep] [cmd]

fg [jobspec]

getopts optstring name [args]

hash [-lr] [-p filename] [-dt] [name]

help [-s] [pattern]

history [n]
history -c
history -d offset
history -anrw [filename]
history -p arg [arg ...]
history -s arg [arg ...]

jobs [-lnprs] [ jobspec ... ]
jobs -x command [ args ... ]

kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ...
kill -l [sigspec | exit_status]

let arg [arg ...]

local [option] [name[=value] ...]

logout Exit a login shell.

popd [-n] [+n] [-n]

printf format [arguments]

pushd [-n] [dir]
pushd [-n] [+n] [-n]

pwd [-LP]

read [-ers] [-u fd] [-t timeout] [-a aname] [-p prompt] [-n nchars]
[-d delim] [name ...]

readonly [-apf] [name[=word] ...]

return [n]

set [--abefhkmnptuvxBCHP] [-o option] [arg ...]

shift [n]

shopt [-pqsu] [-o] [optname ...]

suspend [-f]
test expr
[ expr ]

times Print the accumulated user and system times for the shell and

trap [-lp] [[arg] sigspec ...]

type [-aftpP] name [name ...]

ulimit [-SHacdflmnpstuv [limit]]

umask [-p] [-S] [mode]

unalias [-a] [name ...]

unset [-fv] [name ...]

wait [n]

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:

? changing directories with cd

? setting or unsetting the values of SHELL, PATH, ENV, or

? specifying command names containing /

? specifying a file name containing a / as an argument to the .

? Specifying a filename containing a slash as an argument to the

? importing function definitions from the shell environment at

? parsing the value of SHELLOPTS from the shell environment at

? redirecting output using the >, >|, <>, >&, &>, and >> redirec-

? using the exec builtin command to replace the shell with

? adding or deleting builtin commands with the -f and -d options

? Using the enable builtin command to enable disabled shell

? specifying the -p option to the command builtin command

? turning off restricted mode with set +r or set +o restricted.

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.

Bash Reference Manual, Brian Fox and Chet Ramey
The Gnu Readline Library, Brian Fox and Chet Ramey
The Gnu History Library, Brian Fox and Chet Ramey
Portable Operating System Interface (POSIX) Part 2: Shell and Utili-
ties, IEEE
sh, ksh, csh
emacs, vi


Brian Fox, Free Software Foundation

Chet Ramey, Case Western Reserve University

If you find a bug in bash, you should report it. But first, you
should make sure that it really is a bug, and that it appears in the
latest version of bash. The latest version is always available from

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 or posted to the Usenet newsgroup

ALL bug reports should include:

The version number of bash
The hardware and operating system
The compiler used to compile
A description of the bug behaviour
A short script or 'recipe' which exercises the bug

bashbug inserts the first three items automatically into the template
it provides for filing a bug report.

Comments and bug reports concerning this manual page should be
directed to chet@po.CWRU.Edu.

It's too big and too slow.

There are some subtle differences between bash and traditional ver-
sions 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

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. For example, unmatched parenthe-
ses, even inside shell comments, will result in error messages while
the construct is being read.

Array variables may not (yet) be exported.