bash [options] [command_string | file]

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

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

Bash is intended to be a conformant implementation of the Shell and
Utilities portion of the IEEE POSIX specification (IEEE Standard
1003.1). Bash can be configured to be POSIX-conformant by default.

OPTIONS
All of the single-character shell options documented in the description
of the set builtin command, including -o, can be used as options when
the shell is invoked. In addition, bash interprets the following op-
tions when it is invoked:

-c If the -c option is present, then commands are read from the
-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 (see
-r If the -r option is present, the shell becomes restricted
-s If the -s option is present, or if no arguments remain after
-v Print shell input lines as they are read.
-x Print commands and their arguments as they are executed.
-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 op-
tions must appear on the command line before the single-character op-
tions to be recognized.

--debugger
--dump-po-strings
--dump-strings
--help Display a usage message on standard output and exit success-
--init-file file
--rcfile file

--login

--noediting

--noprofile

--norc Do not read and execute the system wide initialization file

--posix

--restricted

--verbose

--version

ARGUMENTS
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 parame-
ters are set to the remaining arguments. Bash reads and executes com-
mands from this file, then exits. Bash's exit status is the exit sta-
tus of the last command executed in the script. If no commands are ex-
ecuted, 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.

INVOCATION
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 (un-
less -s is specified) and without the -c option, whose standard input
and error 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 filenames as described below under Tilde Expan-
sion 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 ~/.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 an interactive login shell exits, or a non-interactive login shell
executes the exit builtin command, 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 /etc/bash.bashrc and ~/.bashrc, if
these files exist. 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 /etc/bash.bashrc and ~/.bashrc.

When bash is started non-interactively, to run a shell script, for ex-
ample, 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 com-
mand 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 be-
havior of historical versions of sh as closely as possible, while con-
forming 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 in-
hibit 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 exe-
cute commands from any other startup files, the --rcfile option has no
effect. A non-interactive shell invoked with the name sh does not at-
tempt 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 with its standard input
connected to a network connection, as when executed by the historical
remote shell daemon, usually rshd, or the secure shell daemon sshd. If
bash determines it is being run non-interactively in this fashion, it
reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if
these files exist and are 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 nei-
ther rshd nor sshd generally invoke the shell with those options or al-
low 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, BASHOPTS, CDPATH, and GLOBIGNORE variables, if they ap-
pear in the environment, are 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.

DEFINITIONS
The following definitions are used throughout the rest of this docu-
ment.
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-
metacharacter
control operator

RESERVED WORDS
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 command (see SHELL GRAMMAR below), the third word of a
case or select command (only in is valid), or the third word of a for
command (only in and do are valid):

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

SHELL GRAMMAR
This section describes the syntax of the various forms of shell com-
mands.

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 executed,
and is passed as argument zero. The remaining words are passed as ar-
guments 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.

Pipelines
A pipeline is a sequence of one or more commands separated by one of
the control operators | or |&. The format for a pipeline is:


The standard output of command1 is connected via a pipe to the standard
input of command2. This connection is performed before any redirec-
tions specified by the command1(see REDIRECTION below). If |& is used,
command1's standard error, in addition to its standard output, is con-
nected to command2's standard input through the pipe; it is shorthand
for 2>&1 |. This implicit redirection of the standard error to the
standard output is performed after any redirections specified by com-
mand1.

The return status of a pipeline is the exit status of the last command,
unless the pipefail option is enabled. If pipefail is enabled, the
pipeline's return status is the value of the last (rightmost) command
to exit with a non-zero status, or zero if all commands exit success-
fully. If the reserved word ! precedes a pipeline, the exit status 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. When the shell is in posix mode, it does not rec-
ognize time as a reserved word if the next token begins with a `-'.
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.

When the shell is in posix mode, time may be followed by a newline. In
this case, the shell displays the total user and system time consumed
by the shell and its children. The TIMEFORMAT variable may be used to
specify the format of the time information.

Each command in a multi-command pipeline, where pipes are created, is
executed in a subshell, which is a separate process. See COMMAND EXE-
CUTION ENVIRONMENT for a description of subshells and a subshell envi-
ronment. If the lastpipe option is enabled using the shopt builtin
(see the description of shopt below), the last element of a pipeline
may be run by the shell process when job control is not active.

Lists
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. These are
referred to as asynchronous commands. 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 exe-
cuted.

AND and OR lists are sequences of one or more pipelines separated by
the && and || control operators, respectively. AND and OR lists are
executed with left associativity. An AND list has the form


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

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. In most cases a list in a
command's description may be separated from the rest of the command by
one or more newlines, and may be followed by a newline in place of a
semicolon.

(list) list is executed in a subshell (see COMMAND EXECUTION ENVIRON-

{ list; }

((expression))

[[ expression ]]


See the description of the test builtin command (section SHELL BUILTIN
COMMANDS below) for the handling of parameters (i.e. missing parame-
ters).

When the == and != operators are used, the string to the right of the
operator is considered a pattern and matched according to the rules de-
scribed below under Pattern Matching, as if the extglob shell option
were enabled. The = operator is equivalent to ==. If the nocasematch
shell option is enabled, the match is performed without regard to the
case of alphabetic characters. The return value is 0 if the string
matches (==) or does not match (!=) the pattern, and 1 otherwise. Any
part of the pattern may be quoted to force the quoted portion to be
matched as a string.

An additional binary operator, =~, is available, with the same prece-
dence as == and !=. When it is used, the string to the right of the
operator is considered a POSIX extended regular expression and matched
accordingly (using the POSIX regcomp and regexec interfaces usually de-
scribed in regex(3)). The return value is 0 if the string matches the
pattern, and 1 otherwise. If the regular expression is syntactically
incorrect, the conditional expression's return value is 2. If the no-
casematch shell option is enabled, the match is performed without re-
gard to the case of alphabetic characters. If any part of the pattern
is quoted, the quoted portion is matched literally. This means every
character in the quoted portion matches itself, instead of having any
special pattern matching meaning. If the pattern is stored in a shell
variable, quoting the variable expansion forces the entire pattern to
be matched literally. Treat bracket expressions in regular expressions
carefully, since normal quoting and pattern characters lose their mean-
ings between brackets.

The pattern will match if it matches any part of the string. Anchor
the pattern using the ^ and $ regular expression operators to force it
to match the entire string. The array variable BASH_REMATCH records
which parts of the string matched the pattern. The element of BASH_RE-
MATCH with index 0 contains the portion of the string matching the en-
tire regular expression. Substrings matched by parenthesized subex-
pressions within the regular expression are saved in the remaining
BASH_REMATCH indices. The element of BASH_REMATCH with index n is the
portion of the string matching the nth parenthesized subexpression.
Bash sets BASH_REMATCH in the global scope; declaring it as a local
variable will lead to unexpected results.

Expressions may be combined using the following operators, listed in
decreasing order of precedence:



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-1; do list-2; done
until list-1; do list-2; done

Coprocesses
A coprocess is a shell command preceded by the coproc reserved word. A
coprocess is executed asynchronously in a subshell, as if the command
had been terminated with the & control operator, with a two-way pipe
established between the executing shell and the coprocess.

The syntax for a coprocess is:


This creates a coprocess named NAME. command may be either a simple
command or a compound command (see above). NAME is a shell variable
name. If NAME is not supplied, the default name is COPROC.

The recommended form to use for a coprocess is


This form is recommended because simple commands result in the co-
process always being named COPROC, and it is simpler to use and more
complete than the other compound commands.

If command is a compound command, NAME is optional. The word following
coproc determines whether that word is interpreted as a variable name:
it is interpreted as NAME if it is not a reserved word that introduces
a compound command. If command is a simple command, NAME is not al-
lowed; this is to avoid confusion between NAME and the first word of
the simple command.

When the coprocess is executed, the shell creates an array variable
(see Arrays below) named NAME in the context of the executing shell.
The standard output of command is connected via a pipe to a file de-
scriptor in the executing shell, and that file descriptor is assigned
to NAME[0]. The standard input of command is connected via a pipe to a
file descriptor in the executing shell, and that file descriptor is as-
signed to NAME[1]. This pipe is established before any redirections
specified by the command (see REDIRECTION below). The file descriptors
can be utilized as arguments to shell commands and redirections using
standard word expansions. Other than those created to execute command
and process substitutions, the file descriptors are not available in
subshells.

The process ID of the shell spawned to execute the coprocess is avail-
able as the value of the variable NAME_PID. The wait builtin command
may be used to wait for the coprocess to terminate.

Since the coprocess is created as an asynchronous command, the coproc
command always returns success. The return status of a coprocess is
the exit status of command.

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:

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

COMMENTS
In a non-interactive shell, or an interactive shell in which the inter-
active_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 interac-
tive shells.

QUOTING
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 recognized
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 (see HIS-
TORY EXPANSION below), 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
. If a \ pair appears, and the backslash is not it-
self 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,
when history expansion is enabled, !. When the shell is in posix mode,
the ! has no special meaning within double quotes, even when history
expansion is enabled. The characters $ and ` retain their special
meaning within double quotes. The backslash retains its special mean-
ing only when followed by one of the following characters: $, `, ", \,
or . A double quote may be quoted within double quotes by
preceding it with a backslash. If enabled, history expansion will be
performed unless an ! appearing in double quotes is escaped using a
backslash. The backslash preceding the ! is not removed.

The special parameters * and @ have special meaning when in double
quotes (see PARAMETERS below).

Character sequences of the form $'string' are treated as a special
variant of single quotes. The sequence expands to string, with back-
slash-escaped characters in string replaced as specified by the ANSI C
standard. Backslash escape sequences, if present, are decoded as fol-
lows:

The expanded result is single-quoted, as if the dollar sign had not
been present.

A double-quoted string preceded by a dollar sign ($"string") will cause
the string to be translated according to the current locale. The get-
text infrastructure performs the lookup and translation, using the
LC_MESSAGES, TEXTDOMAINDIR, and TEXTDOMAIN shell variables. If the
current locale is C or POSIX, if there are no translations available,
or if the string is not translated, the dollar sign is ignored. This
is a form of double quoting, so the string remains double-quoted by de-
fault, whether or not it is translated and replaced. If the noex-
pand_translation option is enabled using the shopt builtin, translated
strings are single-quoted instead of double-quoted. See the descrip-
tion of shopt below under SHELLBUILTINCOMMANDS.

PARAMETERS
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 Para-
meters. 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 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


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 splitting and path-
name expansion are not performed. Assignment statements may also ap-
pear as arguments to the alias, declare, typeset, export, readonly, and
local builtin commands (declaration commands). When in posix mode,
these builtins may appear in a command after one or more instances of
the command builtin and retain these assignment statement properties.

In the context where an assignment statement is assigning a value to a
shell variable or array index, the += operator can be used to append to
or add to the variable's previous value. This includes arguments to
builtin commands such as declare that accept assignment statements (de-
claration commands). When += is applied to a variable for which the
integer attribute has been set, value is evaluated as an arithmetic ex-
pression and added to the variable's current value, which is also eval-
uated. When += is applied to an array variable using compound assign-
ment (see Arrays below), the variable's value is not unset (as it is
when using =), and new values are appended to the array beginning at
one greater than the array's maximum index (for indexed arrays) or
added as additional key-value pairs in an associative array. When ap-
plied to a string-valued variable, value is expanded and appended to
the variable's value.

A variable can be assigned the nameref attribute using the -n option to
the declare or local builtin commands (see the descriptions of declare
and local below) to create a nameref, or a reference to another vari-
able. This allows variables to be manipulated indirectly. Whenever
the nameref variable is referenced, assigned to, unset, or has its at-
tributes modified (other than using or changing the nameref attribute
itself), the operation is actually performed on the variable specified
by the nameref variable's value. A nameref is commonly used within
shell functions to refer to a variable whose name is passed as an argu-
ment to the function. For instance, if a variable name is passed to a
shell function as its first argument, running
inside the function creates a nameref variable ref whose value is the
variable name passed as the first argument. References and assignments
to ref, and changes to its attributes, are treated as references, as-
signments, and attribute modifications to the variable whose name was
passed as $1. If the control variable in a for loop has the nameref
attribute, the list of words can be a list of shell variables, and a
name reference will be established for each word in the list, in turn,
when the loop is executed. Array variables cannot be given the nameref
attribute. However, nameref variables can reference array variables
and subscripted array variables. Namerefs can be unset using the -n
option to the unset builtin. Otherwise, if unset is executed with the
name of a nameref variable as an argument, the variable referenced by
the nameref variable will be unset.

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

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. In
# Expands to the number of positional parameters in decimal.
? Expands to the exit status of the most recently executed fore-
- Expands to the current option flags as specified upon invoca-
$ Expands to the process ID of the shell. In a subshell, it ex-
! Expands to the process ID of the job most recently placed into
0 Expands to the name of the shell or shell script. This is set

Shell Variables
The following variables are set by the shell:

_ At shell startup, set to the pathname used to invoke the shell
BASH Expands to the full filename used to invoke this instance of
BASHOPTS
BASHPID
BASH_ALIASES
BASH_ARGC
BASH_ARGV
BASH_ARGV0
BASH_CMDS
BASH_COMMAND
BASH_EXECUTION_STRING
BASH_LINENO
BASH_LOADABLES_PATH
BASH_REMATCH
BASH_SOURCE
BASH_SUBSHELL
BASH_VERSINFO
BASH_VERSION
COMP_CWORD
COMP_KEY
COMP_LINE
COMP_POINT
COMP_TYPE
COMP_WORDBREAKS
COMP_WORDS
COPROC An array variable (see Arrays below) created to hold the file
DIRSTACK
EPOCHREALTIME
EPOCHSECONDS
EUID Expands to the effective user ID of the current user, initial-
FUNCNAME

GROUPS An array variable containing the list of groups of which the
HISTCMD
HOSTNAME
HOSTTYPE
LINENO Each time this parameter is referenced, the shell substitutes a
MACHTYPE
MAPFILE
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-
PIPESTATUS
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, it expands to a random
READLINE_ARGUMENT
READLINE_LINE
READLINE_MARK
READLINE_POINT
REPLY Set to the line of input read by the read builtin command when
SECONDS
SHELLOPTS
SHLVL Incremented by one each time an instance of bash is started.
SRANDOM
UID Expands to the user ID of the current user, initialized at shell

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

BASH_COMPAT
BASH_ENV
BASH_XTRACEFD
CDPATH The search path for the cd command. This is a colon-separated
CHILD_MAX
COLUMNS
COMPREPLY
EMACS If bash finds this variable in the environment when the shell
ENV Expanded and executed similarly to BASH_ENV (see INVOCATION
EXECIGNORE
FCEDIT The default editor for the fc builtin command.
FIGNORE
FUNCNEST
GLOBIGNORE
HISTCONTROL
HISTFILE
HISTFILESIZE
HISTIGNORE
HISTSIZE
HISTTIMEFORMAT
HOME The home directory of the current user; the default argument for
HOSTFILE
IFS The Internal Field Separator that is used for word splitting af-
IGNOREEOF
INPUTRC
INSIDE_EMACS
LANG Used to determine the locale category for any category not
LC_ALL This variable overrides the value of LANG and any other LC_
LC_COLLATE
LC_CTYPE
LC_MESSAGES
LC_NUMERIC
LC_TIME
LINES Used by the select compound command to determine the column
MAIL If this parameter is set to a file or directory name and the
MAILCHECK
MAILPATH
OPTERR If set to the value 1, bash displays error messages generated by
PATH The search path for commands. It is a colon-separated list of
POSIXLY_CORRECT
PROMPT_COMMAND
PROMPT_DIRTRIM
PS0 The value of this parameter is expanded (see PROMPTING below)
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 select
PS4 The value of this parameter is expanded as with PS1 and the
SHELL This variable expands to the full pathname to the shell. If it
TIMEFORMAT



TMOUT If set to a value greater than zero, TMOUT is treated as the de-
TMPDIR If set, bash uses its value as the name of a directory in which
auto_resume
histchars

Arrays
Bash provides one-dimensional indexed and associative array variables.
Any variable may be used as an indexed 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 con-
tiguously. Indexed arrays are referenced using integers (including
arithmetic expressions) and are zero-based; associative arrays are ref-
erenced using arbitrary strings. Unless otherwise noted, indexed array
indices must be non-negative integers.

An indexed 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. To explicitly
declare an indexed array, use declare -a name (see SHELL BUILTIN COM-
MANDS below). declare -a name[subscript] is also accepted; the sub-
script is ignored.

Associative arrays are created using declare -A name.

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 may be of the form [sub-
script]=string. Indexed array assignments do not require anything but
string. Each value in the list is expanded using all the shell expan-
sions described below under EXPANSION. When assigning to indexed ar-
rays, 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.

When assigning to an associative array, the words in a compound assign-
ment may be either assignment statements, for which the subscript is
required, or a list of words that is interpreted as a sequence of al-
ternating keys and values: name=( key1 value1 key2 value2 ...). These
are treated identically to name=( [key1]=value1 [key2]=value2 ...).
The first word in the list determines how the remaining words are in-
terpreted; all assignments in a list must be of the same type. When
using key/value pairs, the keys may not be missing or empty; a final
missing value is treated like the empty string.

This syntax is also accepted by the declare builtin. Individual array
elements may be assigned to using the name[subscript]=value syntax in-
troduced above. When assigning to an indexed array, if name is sub-
scripted by a negative number, that number is interpreted as relative
to one greater than the maximum index of name, so negative indices
count back from the end of the array, and an index of -1 references the
last element.

The += operator will append to an array variable when assigning using
the compound assignment syntax; see PARAMETERS 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 sep-
arate word. When there are no array members, ${name[@]} expands to
nothing. If the double-quoted expansion occurs within a word, the ex-
pansion of the first parameter is joined with the beginning part of the
original word, and the expansion of the last parameter is joined with
the last part of the original word. 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 ar-
ray. If the subscript used to reference an element of an indexed array
evaluates to a number less than zero, it is interpreted as relative to
one greater than the maximum index of the array, so negative indices
count back from the end of the array, and an index of -1 references the
last element.

Referencing an array variable without a subscript is equivalent to ref-
erencing the array with a subscript of 0. Any reference to a variable
using a valid subscript is legal, and bash will create an array if nec-
essary.

An array variable is considered set if a subscript has been assigned a
value. The null string is a valid value.

It is possible to obtain the keys (indices) of an array as well as the
values. ${!name[@]} and ${!name[*]} expand to the indices assigned in
array variable name. The treatment when in double quotes is similar to
the expansion of the special parameters @ and * within double quotes.

The unset builtin is used to destroy arrays. unset name[subscript] de-
stroys the array element at index subscript, for both indexed and asso-
ciative arrays. Negative subscripts to indexed arrays are interpreted
as described above. Unsetting the last element of an array variable
does not unset the variable. unset name, where name is an array, re-
moves the entire array. unset name[subscript], where subscript is * or
@, behaves differently depending on whether name is an indexed or asso-
ciative array. If name is an associative array, this unsets the ele-
ment with subscript * or @. If name is an indexed array, unset removes
all of the elements but does not remove the array itself.

When using a variable name with a subscript as an argument to a com-
mand, such as with unset, without using the word expansion syntax de-
scribed above, the argument is subject to pathname expansion. If path-
name expansion is not desired, the argument should be quoted.

The declare, local, and readonly builtins each accept a -a option to
specify an indexed array and a -A option to specify an associative ar-
ray. If both options are supplied, -A takes precedence. 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
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 substitu-
tion, arithmetic expansion, word splitting, and pathname expansion.

The order of expansions is: brace expansion; tilde expansion, parameter
and variable expansion, arithmetic expansion, and command substitution
(done in a left-to-right fashion); word splitting; and pathname expan-
sion.

On systems that can support it, there is an additional expansion avail-
able: process substitution. This is performed at the same time as
tilde, parameter, variable, and arithmetic expansion and command sub-
stitution.

After these expansions are performed, quote characters present in the
original word are removed unless they have been quoted themselves
(quote removal).

Only brace expansion, word splitting, and pathname expansion can in-
crease the number of words of the expansion; other expansions expand a
single word to a single word. The only exceptions to this are the ex-
pansions of "$@" and "${name[@]}", and, in most cases, $* and
${name[*]} as explained above (see PARAMETERS).

Brace Expansion
Brace expansion is a mechanism by which arbitrary strings may be gener-
ated. This mechanism is similar to pathname expansion, but the file-
names generated need not exist. Patterns to be brace expanded take the
form of an optional preamble, followed by either a series of comma-sep-
arated strings or a sequence expression between a pair of braces, fol-
lowed 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[..incr]}, where x and y are
either integers or single letters, and incr, an optional increment, is
an integer. When integers are supplied, the expression expands to each
number between x and y, inclusive. Supplied integers may be prefixed
with 0 to force each term to have the same width. When either x or y
begins with a zero, the shell attempts to force all generated terms to
contain the same number of digits, zero-padding where necessary. When
letters are supplied, the expression expands to each character lexico-
graphically between x and y, inclusive, using the default C locale.
Note that both x and y must be of the same type (integer or letter).
When the increment is supplied, it is used as the difference between
each term. The default increment is 1 or -1 as appropriate.

Brace expansion is performed before any other expansions, and any char-
acters 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 or a valid sequence ex-
pression. 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 expan-
sion, the string ${ is not considered eligible for brace expansion, and
inhibits brace expansion until the closing }.

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

or

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 com-
mand (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 re-
places the tilde-prefix. If the tilde-prefix is a `~-', the value of
the shell variable OLDPWD, if it is set, is substituted. If the char-
acters 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 argu-
ment. If the characters following the tilde in the tilde-prefix con-
sist 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 immedi-
ately following a : or the first =. In these cases, tilde expansion is
also performed. Consequently, one may use filenames with tildes in as-
signments to PATH, MAILPATH, and CDPATH, and the shell assigns the ex-
panded value.

Bash also performs tilde expansion on words satisfying the conditions
of variable assignments (as described above under PARAMETERS) when they
appear as arguments to simple commands. Bash does not do this, except
for the declaration commands listed above, when in posix mode.

Parameter Expansion
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 em-
bedded arithmetic expansion, command substitution, or parameter expan-
sion.

${parameter}

If the first character of parameter is an exclamation point (!), and
parameter is not a nameref, it introduces a level of indirection. Bash
uses the value formed by expanding the rest of parameter as the new pa-
rameter; this is then expanded and that value is used in the rest of
the expansion, rather than the expansion of the original parameter.
This is known as indirect expansion. The value is subject to tilde ex-
pansion, parameter expansion, command substitution, and arithmetic ex-
pansion. If parameter is a nameref, this expands to the name of the
parameter referenced by parameter instead of performing the complete
indirect expansion. The exceptions to this are the expansions of
${!prefix*} and ${!name[@]} described below. The exclamation point
must immediately follow the left brace in order to introduce indirec-
tion.

In each of the cases below, word is subject to tilde expansion, parame-
ter expansion, command substitution, and arithmetic expansion.

When not performing substring expansion, using the forms documented be-
low (e.g., :-), bash tests for a parameter that is unset or null.
Omitting the colon results in a test only for a parameter that is un-
set.

${parameter:-word}
${parameter:=word}
${parameter:?word}
${parameter:+word}
${parameter:offset}
${parameter:offset:length}






${!prefix*}
${!prefix@}

${!name[@]}
${!name[*]}

${#parameter}

${parameter#word}
${parameter##word}

${parameter%word}
${parameter%%word}

${parameter/pattern/string}
${parameter//pattern/string}
${parameter/#pattern/string}
${parameter/%pattern/string}




${parameter^pattern}
${parameter^^pattern}
${parameter,pattern}
${parameter,,pattern}

${parameter@operator}




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

or

Bash performs the expansion by executing command in a subshell environ-
ment 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 com-
mand 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 sub-
stitution. 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
Arithmetic expansion allows the evaluation of an arithmetic expression
and the substitution of the result. The format for arithmetic expan-
sion is:


The old format $[expression] is deprecated and will be removed in up-
coming versions of bash.

The expression undergoes the same expansions as if it were within dou-
ble quotes, but double quote characters in expression are not treated
specially and are removed. All tokens in the expression undergo para-
meter and variable expansion, command substitution, and quote removal.
The result is treated as the arithmetic expression to be evaluated.
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 message
indicating failure and no substitution occurs.

Process Substitution
Process substitution allows a process's input or output to be referred
to using a filename. It takes the form of <(list) or >(list). The
process list is run asynchronously, and its input or output appears as
a filename. This filename is passed as an argument to the current com-
mand 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. Process substitution is supported on systems that sup-
port named pipes (FIFOs) or the /dev/fd method of naming open files.

When available, process substitution is performed simultaneously with
parameter and variable expansion, command substitution, and arithmetic
expansion.

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 using these characters as
field terminators. If IFS is unset, or its value is exactly
, the default, then sequences of , ,
and at the beginning and end of the results of the previous
expansions are ignored, and any sequence of IFS characters not at the
beginning or end serves to delimit words. If IFS has a value other
than the default, then sequences of the whitespace characters space,
tab, and newline are ignored at the beginning and end of the word, as
long as the whitespace character is in the value of IFS (an IFS white-
space 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 and passed to commands
as empty strings. Unquoted implicit null arguments, resulting from the
expansion of parameters that have no values, are removed. If a parame-
ter with no value is expanded within double quotes, a null argument re-
sults and is retained and passed to a command as an empty string. When
a quoted null argument appears as part of a word whose expansion is
non-null, the null argument is removed. That is, the word -d'' becomes
-d after word splitting and null argument removal.

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, and is not quoted, then the word is regarded as a pattern, and
replaced with an alphabetically sorted list of filenames matching the
pattern (see Pattern Matching below). If no matching filenames are
found, and the shell option nullglob is not enabled, 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 per-
formed without regard to the case of alphabetic characters. Note that
when using range expressions like [a-z] (see below), letters of the
other case may be included, depending on the setting of LC_COLLATE.
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. In order to match
the filenames ``.'' and ``..'', the pattern must begin with ``.'' (for
example, ``.?''), even if dotglob is set. If the globskipdots shell
option is enabled, the filenames ``.'' and ``..'' are never matched,
even if the pattern begins with a ``.''. When not matching pathnames,
the ``.'' character is not treated specially. When matching a path-
name, the slash character must always be matched explicitly by a slash
in the pattern, but in other matching contexts it can be matched by a
special pattern character as described below under Pattern Matching.
See the description of shopt below under SHELL BUILTIN COMMANDS for a
description of the nocaseglob, nullglob, globskipdots, failglob, 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. If the nocaseglob option is set, the match-
ing against the patterns in GLOBIGNORE is performed without regard to
case. The filenames ``.'' and ``..'' are always ignored when GLOBIG-
NORE 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
filenames beginning with a ``.'' will match. To get the old behavior
of ignoring filenames beginning with a ``.'', make ``.*'' one of the
patterns in GLOBIGNORE. The dotglob option is disabled when GLOBIGNORE
is unset. The pattern matching honors the setting of the extglob shell
option.

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. A backslash escapes the following character; 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:





If the extglob shell option is enabled using the shopt builtin, the
shell recognizes several extended pattern matching operators. 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:


Theextglob option changes the behavior of the parser, since the paren-
theses are normally treated as operators with syntactic meaning. To
ensure that extended matching patterns are parsed correctly, make sure
that extglob is enabled before parsing constructs containing the pat-
terns, including shell functions and command substitutions.

When matching filenames, the dotglob shell option determines the set of
filenames that are tested: when dotglob is enabled, the set of file-
names includes all files beginning with ``.'', but ``.'' and ``..''
must be matched by a pattern or sub-pattern that begins with a dot;
when it is disabled, the set does not include any filenames beginning
with ``.'' unless the pattern or sub-pattern begins with a ``.''. As
above, ``.'' only has a special meaning when matching filenames.

Complicated extended pattern matching against long strings is slow, es-
pecially when the patterns contain alternations and the strings contain
multiple matches. Using separate matches against shorter strings, or
using arrays of strings instead of a single long string, may be faster.

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

REDIRECTION
Before a command is executed, its input and output may be redirected
using a special notation interpreted by the shell. Redirection allows
commands' file handles to be duplicated, opened, closed, made to refer
to different files, and can change the files the command reads from and
writes to. Redirection may also be used to modify file handles in the
current shell execution environment. The following redirection opera-
tors may precede or appear anywhere within a simple command or may fol-
low a command. Redirections are processed in the order they appear,
from left to right.

Each redirection that may be preceded by a file descriptor number may
instead be preceded by a word of the form {varname}. In this case, for
each redirection operator except >&- and <&-, the shell will allocate a
file descriptor greater than or equal to 10 and assign it to varname.
If >&- or <&- is preceded by {varname}, the value of varname defines
the file descriptor to close. If {varname} is supplied, the redirec-
tion persists beyond the scope of the command, allowing the shell pro-
grammer to manage the file descriptor's lifetime manually. The
varredir_close shell option manages this behavior.

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 and variable 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


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 from the standard output before the standard out-
put was redirected to dirlist.

Bash handles several filenames specially when they are used in redirec-
tions, as described in the following table. If the operating system on
which bash is running provides these special files, bash will use them;
otherwise it will emulate them internally with the behavior described
below.


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

Redirections using file descriptors greater than 9 should be used with
care, as they may conflict with file descriptors the shell uses inter-
nally.

Note that the exec builtin command can make redirections take effect in
the current shell.

Redirecting Input
Redirection of input causes the file whose name results from the expan-
sion 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 ex-
pansion 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 re-
sults from the expansion of word to be opened for appending on file de-
scriptor 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
This construct 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.

There are two formats for redirecting standard output and standard er-
ror:

and

Of the two forms, the first is preferred. This is semantically equiva-
lent to


When using the second form, word may not expand to a number or -. If
it does, other redirection operators apply (see Duplicating File De-
scriptors below) for compatibility reasons.

Appending Standard Output and Standard Error
This construct allows both the standard output (file descriptor 1) and
the standard error output (file descriptor 2) to be appended to the
file whose name is the expansion of word.

The format for appending standard output and standard error is:


This is semantically equivalent to


(see Duplicating File Descriptors below).

Here Documents
This type of redirection instructs the shell to read input from the
current source until a line containing only delimiter (with no trailing
blanks) is seen. All of the lines read up to that point are then used
as the standard input (or file descriptor n if n is specified) for a
command.

The format of here-documents is:


No parameter and variable expansion, command substitution, arithmetic
expansion, or pathname expansion is performed on word. If any part of
word is quoted, the delimiter is the result of quote removal on word,
and the lines in the here-document are not expanded. If word is un-
quoted, all lines of the here-document are subjected to parameter ex-
pansion, command substitution, and arithmetic expansion, the character
sequence \ is ignored, and \ must be used to quote the charac-
ters \, $, and `.

If the redirection operator is <<-, then all leading tab characters are
stripped from input lines and the line containing delimiter. This al-
lows here-documents within shell scripts to be indented in a natural
fashion.

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


The word undergoes tilde expansion, parameter and variable expansion,
command substitution, arithmetic expansion, and quote removal. Path-
name expansion and word splitting are not performed. The result is
supplied as a single string, with a newline appended, to the command on
its standard input (or file descriptor n if n is specified).

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 de-
scriptor 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


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. If word evaluates to -, file descriptor n is
closed. As a special case, if n is omitted, and word does not expand
to one or more digits or -, 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
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 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, use a shell function (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, and
all lines that make up a compound command, before executing any of the
commands on that line or the compound command. 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 command. As a
consequence, aliases defined in a function are not available until af-
ter that function is executed. To be safe, always put alias defini-
tions on a separate line, and do not use alias in compound commands.

For almost every purpose, aliases are superseded by shell functions.

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 executed
in the context of the current shell; no new process is created to in-
terpret 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 func-
tion while the function is executing.

All other aspects of the shell execution environment are identical be-
tween a function and its caller with these exceptions: the DEBUG and
RETURN traps (see the description of the trap builtin under SHELL
BUILTIN COMMANDS below) are 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 and RETURN
traps), and the ERR trap is not inherited unless the -o errtrace shell
option has been enabled.

Variables local to the function may be declared with the local builtin
command (local variables). Ordinarily, variables and their values are
shared between the function and its caller. If a variable is declared
local, the variable's visible scope is restricted to that function and
its children (including the functions it calls).

In the following description, the current scope is a currently- execut-
ing function. Previous scopes consist of that function's caller and so
on, back to the "global" scope, where the shell is not executing any
shell function. Consequently, a local variable at the current scope is
a variable declared using the local or declare builtins in the function
that is currently executing.

Local variables "shadow" variables with the same name declared at pre-
vious scopes. For instance, a local variable declared in a function
hides a global variable of the same name: references and assignments
refer to the local variable, leaving the global variable unmodified.
When the function returns, the global variable is once again visible.

The shell uses dynamic scoping to control a variable's visibility
within functions. With dynamic scoping, visible variables and their
values are a result of the sequence of function calls that caused exe-
cution to reach the current function. The value of a variable that a
function sees depends on its value within its caller, if any, whether
that caller is the "global" scope or another shell function. This is
also the value that a local variable declaration "shadows", and the
value that is restored when the function returns.

For example, if a variable var is declared as local in function func1,
and func1 calls another function func2, references to var made from
within func2 will resolve to the local variable var from func1, shadow-
ing any global variable named var.

The unset builtin also acts using the same dynamic scope: if a variable
is local to the current scope, unset will unset it; otherwise the unset
will refer to the variable found in any calling scope as described
above. If a variable at the current local scope is unset, it will re-
main so (appearing as unset) until it is reset in that scope or until
the function returns. Once the function returns, any instance of the
variable at a previous scope will become visible. If the unset acts on
a variable at a previous scope, any instance of a variable with that
name that had been shadowed will become visible (see below how the lo-
calvar_unset shell option changes this behavior).

The FUNCNEST variable, if set to a numeric value greater than 0, de-
fines a maximum function nesting level. Function invocations that ex-
ceed the limit cause the entire command to abort.

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 be-
fore 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 type-
set will list the function names only (and optionally the source file
and line number, if the extdebug shell option is enabled). Functions
may be exported so that child shell processes (those created when exe-
cuting a separate shell invocation) automatically have them defined
with the -f option to the export builtin. A function definition may be
deleted using the -f option to the unset builtin.

Functions may be recursive. The FUNCNEST variable may be used to limit
the depth of the function call stack and restrict the number of func-
tion invocations. By default, no limit is imposed on the number of re-
cursive calls.

ARITHMETIC EVALUATION
The shell allows arithmetic expressions to be evaluated, under certain
circumstances (see the let and declare builtin commands, the (( com-
pound command, 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 fol-
lowing list of operators is grouped into levels of equal-precedence op-
erators. The levels are listed in order of decreasing precedence.

id++ id--
- + unary minus and plus
++id --id
! ~ 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
expr?expr:expr
= *= /= %= += -= <<= >>= &= ^= |=
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 arithmetic 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 integer attribute turned on
to be used in an expression.

Integer constants follow the C language definition, without suffixes or
character constants. Constants with a leading 0 are interpreted as oc-
tal numbers. A leading 0x or 0X denotes hexadecimal. Otherwise, num-
bers take the form [base#]n, where the optional base is a decimal num-
ber between 2 and 64 representing the arithmetic base, and n is a num-
ber in that base. If base# is omitted, then base 10 is used. When
specifying n, if a non-digit is required, 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 up-
percase letters may be used interchangeably to represent numbers be-
tween 10 and 35.

Operators are evaluated in order of precedence. Sub-expressions in
parentheses are evaluated first and may override the precedence rules
above.

CONDITIONAL EXPRESSIONS
Conditional expressions are used by the [[ compound command and the
test and [ builtin commands to test file attributes and perform string
and arithmetic comparisons. The test and [ commands determine their
behavior based on the number of arguments; see the descriptions of
those commands for any other command-specific actions.

Expressions are formed from the following unary or binary primaries.
Bash handles several filenames specially when they are used in expres-
sions. If the operating system on which bash is running provides these
special files, bash will use them; otherwise it will emulate them in-
ternally with this behavior: 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.

Unless otherwise specified, primaries that operate on files follow sym-
bolic links and operate on the target of the link, rather than the link
itself.

When used with [[, the < and > operators sort lexicographically using
the current locale. The test command sorts using ASCII ordering.

-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
-G file
-L file
-N file
-O file
-S file
file1 -ef file2
file1 -nt file2
file1 -ot file2
-o optname
-v varname
-R varname
-z string
string
-n string

string1 == string2
string1 = string2

string1 != string2

string1 < string2

string1 > string2

arg1 OP arg2

SIMPLE COMMAND EXPANSION
When a simple command is executed, the shell performs the following ex-
pansions, assignments, and redirections, from left to right, in the
following order.

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

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

If no command name results, the variable assignments affect the current
shell environment. In the case of such a command (one that consists
only of assignment statements and redirections), assignment statements
are performed before redirections. Otherwise, the variables are added
to the environment of the executed command and do not affect the cur-
rent 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 af-
fect 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.

COMMAND EXECUTION
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
taken.

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 re-
member 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 searches for a defined shell function
named command_not_found_handle. If that function exists, it is invoked
in a separate execution environment with the original command and the
original command's arguments as its arguments, and the function's exit
status becomes the exit status of that subshell. If that function is
not defined, the shell prints an error message and returns an exit sta-
tus 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 execu-
tion environment. Argument 0 is set to the name given, and the remain-
ing 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, and the shell creates a new instance of
itself 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 exe-
cutable 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.

COMMAND EXECUTION ENVIRONMENT
The shell has an execution environment, which consists of the follow-
ing:

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

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

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

o current traps set by trap

o shell parameters that are set by variable assignment or with set

o shell functions defined during execution or inherited from the

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

o options enabled by shopt

o shell aliases defined with alias

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

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

o the current working directory

o the file creation mode mask

o shell variables and functions marked for export, along with

o traps caught by the shell are reset to the values inherited from

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

A subshell is a copy of the shell process.

Command substitution, commands grouped with parentheses, and asynchro-
nous commands are invoked in a subshell environment that is a duplicate
of the shell environment, except that traps caught by the shell are re-
set to the values that the shell inherited from its parent at invoca-
tion. Builtin commands that are invoked as part of a pipeline are also
executed in a subshell environment. Changes made to the subshell envi-
ronment cannot affect the shell's execution environment.

Subshells spawned to execute command substitutions inherit the value of
the -e option from the parent shell. When not in posix mode, bash
clears the -e option in such subshells.

If a command is followed by a & and job control is not active, the de-
fault standard input for the command is the empty file /dev/null. Oth-
erwise, the invoked command inherits the file descriptors of the call-
ing shell as modified by redirections.

ENVIRONMENT
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
name=value.

The shell provides several ways to manipulate the environment. On in-
vocation, 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 envi-
ronment is modified, the new value becomes part of the environment, re-
placing the old. The environment inherited by any executed command
consists of the shell's initial environment, whose values may be modi-
fied 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 envi-
ronment 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 filename of the command and passed to that command in its environ-
ment.

EXIT STATUS
The exit status of an executed command is the value returned by the
waitpid system call or equivalent function. Exit statuses fall between
0 and 255, though, as explained below, the shell may use values above
125 specially. Exit statuses from shell builtins and compound commands
are also limited to this range. Under certain circumstances, the shell
will use special values to indicate specific failure modes.

For the shell's purposes, a command which exits with a zero exit status
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 re-
turns 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, generally in-
valid options or missing arguments.

The exit status of the last command is available in the special parame-
ter $?.

Bash itself returns the exit status of the last command executed, un-
less a syntax error occurs, in which case it exits with a non-zero
value. See also the exit builtin command below.

SIGNALS
When bash is interactive, in the absence of any traps, it ignores
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 ig-
nores SIGTTIN, SIGTTOU, and SIGTSTP.

Non-builtin commands run by bash have signal handlers set to the values
inherited by the shell from its parent. When job control is not in ef-
fect, asynchronous commands ignore SIGINT and SIGQUIT in addition to
these inherited handlers. Commands run as a result of command substi-
tution ignore the keyboard-generated job control signals SIGTTIN, SIGT-
TOU, 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 us-
ing 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 bash is waiting for a command to complete and receives a signal for
which a trap has been set, the trap will not be executed until the com-
mand 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 sta-
tus greater than 128, immediately after which the trap is executed.

When job control is not enabled, and bash is waiting for a foreground
command to complete, the shell receives keyboard-generated signals such
as SIGINT (usually generated by ^C) that users commonly intend to send
to that command. This happens because the shell and the command are in
the same process group as the terminal, and ^C sends SIGINT to all
processes in that process group.

When bash is running without job control enabled and receives SIGINT
while waiting for a foreground command, it waits until that foreground
command terminates and then decides what to do about the SIGINT:

1. If the command terminates due to the SIGINT, bash concludes that

2. If the command does not terminate due to SIGINT, the program

JOB CONTROL
Job control refers to the ability to selectively stop (suspend) the ex-
ecution of processes and continue (resume) their execution at a later
point. A user typically employs this facility via an interactive in-
terface supplied jointly by the operating system kernel's terminal dri-
ver and bash.

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 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-gen-
erated signals. Only foreground processes are allowed to read from or,
if the user so specifies with stty tostop, write to the terminal.
Background processes which attempt to read from (write to when stty
tostop is in effect) the terminal are sent a SIGTTIN (SIGTTOU) signal
by the kernel's 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 (typ-
ically ^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 re-
turned 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 charac-
ter % introduces a job specification (jobspec). 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 job whose command name be-
gins with ce. 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 %-. If there is only a single job, %+ and %- can
both be used to refer to that job. 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 -. A single % (with no accompanying
job specification) also refers to the current job.

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 ex-
its.

If an attempt to exit bash is made while jobs are stopped (or, if the
checkjobs shell option has been enabled using the shopt builtin, run-
ning), the shell prints a warning message, and, if the checkjobs option
is enabled, lists the jobs and their statuses. 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 any stopped jobs are terminated.

When the shell is waiting for a job or process using the wait builtin,
and job control is enabled, wait will return when the job changes
state. The -f option causes wait to wait until the job or process ter-
minates before returning.

PROMPTING
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 displays PS0 after it
reads a command but before executing it. Bash displays PS4 as de-
scribed above before tracing each command when the -x option is en-
abled. 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 be-
low), while the command number is the position in the sequence of com-
mands 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). This can have unwanted side effects if
escaped portions of the string appear within command substitution or
contain characters special to word expansion.

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

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 Control-N. Simi-
larly, meta keys are denoted by M-key, so M-x means Meta-X. (On key-
boards 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 ~/.in-
putrc. If that file does not exist or cannot be read, the ultimate
default is /etc/inputrc. When a program which uses the readline li-
brary 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

or
into the inputrc would make M-C-u execute the readline command univer-
sal-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).

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-argument.
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 func-
tion 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 behav-
ior. A variable may be set in the inputrc file with a statement of the
form

or using the bind builtin command (see SHELL BUILTIN COMMANDS below).

Except where noted, readline variables can take the values On or Off
(without regard to case). Unrecognized variable names are ignored.
When a variable value is read, empty or null values, "on" (case-insen-
sitive), and "1" are equivalent to On. All other values are equivalent
to Off. The variables and their default values are:

active-region-start-color
active-region-end-color
bell-style (audible)
bind-tty-special-chars (On)
blink-matching-paren (Off)
colored-completion-prefix (Off)
colored-stats (Off)
comment-begin (``#'')
completion-display-width (-1)
completion-ignore-case (Off)
completion-map-case (Off)
completion-prefix-display-length (0)
completion-query-items (100)
convert-meta (On)
disable-completion (Off)
echo-control-characters (On)
editing-mode (emacs)
emacs-mode-string (@)
enable-active-region (On)
enable-bracketed-paste (On)
enable-keypad (Off)
enable-meta-key (On)
expand-tilde (Off)
history-preserve-point (Off)
history-size (unset)
horizontal-scroll-mode (Off)
input-meta (Off)
isearch-terminators (``C-[C-J'')
keymap (emacs)
keyseq-timeout (500)
mark-directories (On)
mark-modified-lines (Off)
mark-symlinked-directories (Off)
match-hidden-files (On)
menu-complete-display-prefix (Off)
output-meta (Off)
page-completions (On)
print-completions-horizontally (Off)
revert-all-at-newline (Off)
show-all-if-ambiguous (Off)
show-all-if-unmodified (Off)
show-mode-in-prompt (Off)
skip-completed-text (Off)
vi-cmd-mode-string ((cmd))
vi-ins-mode-string ((ins))
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 $if

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

$include


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

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 accom-
panying key sequence are unbound by default. In the following descrip-
tions, 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)
shell-forward-word
shell-backward-word
previous-screen-line
next-screen-line
clear-display (M-C-l)
clear-screen (C-l)
redraw-current-line

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->)
operate-and-get-next (C-o)
fetch-history
reverse-search-history (C-r)
forward-search-history (C-s)
non-incremental-reverse-search-history (M-p)
non-incremental-forward-search-history (M-n)
history-search-forward
history-search-backward
history-substring-search-backward
history-substring-search-forward
yank-nth-arg (M-C-y)
yank-last-arg (M-., M-_)
shell-expand-line (M-C-e)
history-expand-line (M-^)
magic-space
alias-expand-line
history-and-alias-expand-line
insert-last-argument (M-., M-_)
edit-and-execute-command (C-x C-e)

Commands for Changing Text
end-of-file (usually C-d)
delete-char (C-d)
backward-delete-char (Rubout)
forward-backward-delete-char
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)
overwrite-mode

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

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

Completing
complete (TAB)
possible-completions (M-?)
insert-completions (M-*)
menu-complete
menu-complete-backward
delete-char-or-list
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)
dabbrev-expand
complete-into-braces (M-{)

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

Miscellaneous
re-read-init-file (C-x C-r)
abort (C-g)
do-lowercase-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-])
skip-csi-sequence
insert-comment (M-#)
spell-correct-word (C-x s)
glob-complete-word (M-g)
glob-expand-word (C-x *)
glob-list-expansions (C-x g)
dump-functions
dump-variables
dump-macros
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 programma-
ble completion facilities are invoked.

First, the command name is identified. If the command word is the
empty string (completion attempted at the beginning of an empty line),
any compspec defined with the -E option to complete is used. 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.
If those searches do not result in a compspec, any compspec defined
with the -D option to complete is used as the default. If there is no
default compspec, bash attempts alias expansion on the command word as
a final resort, and attempts to find a compspec for the command word
from any successful expansion.

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 pathname expansion pattern to the -G op-
tion 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, and arithmetic 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, COMP_POINT, COMP_KEY, and COMP_TYPE
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 ($1) is the name of the command whose arguments are be-
ing completed, the second argument ($2) is the word being completed,
and the third argument ($3) is the word preceding the word being com-
pleted on the current command line. No filtering of the generated com-
pletions 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, one per array element.

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 match-
ing the pattern will be removed. If the nocasematch shell option is
enabled, the match is performed without regard to the case of alpha-
betic characters.

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 de-
fined, 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 sup-
plied to complete when the compspec was defined, the bash default com-
pletions 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 compspec (and,
if attempted, the default bash completions) generate 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.

There is some support for dynamically modifying completions. This is
most useful when used in combination with a default completion speci-
fied with complete -D. It's possible for shell functions executed as
completion handlers to indicate that completion should be retried by
returning an exit status of 124. If a shell function returns 124, and
changes the compspec associated with the command on which completion is
being attempted (supplied as the first argument when the function is
executed), programmable completion restarts from the beginning, with an
attempt to find a new compspec for that command. This allows a set of
completions to be built dynamically as completion is attempted, rather
than being loaded all at once.

For instance, assuming that there is a library of compspecs, each kept
in a file corresponding to the name of the command, the following de-
fault completion function would load completions dynamically:

_completion_loader()
{
. "/etc/bash_completion.d/$1.sh" >/dev/null 2>&1 && return 124
}
complete -D -F _completion_loader -o bashdefault -o default

HISTORY
When the -o history option to the set builtin is enabled, the shell
provides access to the command history, the list of commands previously
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 com-
mands (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 vari-
able 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. If HISTFILE-
SIZE is unset, or set to null, a non-numeric value, or a numeric value
less than zero, the history file is not truncated. When the history
file is read, lines beginning with the history comment character fol-
lowed immediately by a digit are interpreted as timestamps for the fol-
lowing history line. These timestamps are optionally displayed depend-
ing on the value of the HISTTIMEFORMAT variable. When a shell with
history enabled 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 un-
writable, the history is not saved. If the HISTTIMEFORMAT variable is
set, time stamps are written to the history file, marked with the his-
tory comment character, so they may be preserved across shell sessions.
This uses the history comment character to distinguish timestamps from
other history lines. After saving the history, the history file is
truncated to contain no more than HISTFILESIZE lines. If HISTFILESIZE
is unset, or set to null, a non-numeric value, or a numeric value less
than zero, the history file is not truncated.

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 his-
tory builtin may be used to display or modify the history list and ma-
nipulate 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 op-
tions.

HISTORY EXPANSION
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 com-
mand (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, and is performed on each
line individually without taking quoting on previous lines into ac-
count. 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 avail-
able to manipulate the selected words. The line is broken into words
in the same fashion as when reading input, so that several metacharac-
ter-separated words surrounded by quotes are considered one word. His-
tory expansions are introduced by the appearance of the history expan-
sion character, which is ! by default. Only backslash (\) and single
quotes can quote the history expansion character, but the history ex-
pansion character is also treated as quoted if it immediately precedes
the closing double quote in a double-quoted string.

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 op-
tion is enabled (see the description of the shopt builtin below), 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). The shell uses the history comment character to mark his-
tory timestamps when writing the history file.

Event Designators
An event designator is a reference to a command line entry in the his-
tory list. Unless the reference is absolute, events are relative to
the current position in the history list.

! Start a history substitution, except when followed by a blank,
!n Refer to command line n.
!-n Refer to the current command minus n.
!! Refer to the previous command. This is a synonym for `!-1'.
!string
!?string[?]
^string1^string2^
!# 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 word. This is usually the last argument, but will ex-
% The first word matched by the most recent `?string?' search, if
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 x is miss-

If a word designator is supplied without an event specification, the
previous command is used as the event.

Modifiers
After the optional word designator, there may appear a sequence of one
or more of the following modifiers, each preceded by a `:'. These mod-
ify, or edit, the word or words selected from the history event.

h Remove a trailing filename component, leaving only the head.
t Remove all leading filename components, leaving the tail.
r Remove a trailing suffix of the form .xxx, leaving the basename.
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
s/old/new/
& Repeat the previous substitution.
g Cause changes to be applied over the entire event line. This is
G Apply the following `s' or `&' modifier once to each word in the

SHELL BUILTIN COMMANDS
Unless otherwise noted, each builtin command documented in this section
as accepting options preceded by - accepts -- to signify the end of the
options. The :, true, false, and test/[ builtins do not accept options
and do not treat -- specially. The exit, logout, return, break, con-
tinue, let, and shift builtins accept and process arguments beginning
with - without requiring --. Other builtins that accept arguments but
are not specified as accepting options interpret arguments beginning
with - as invalid options and require -- to prevent this interpreta-
tion.
: [arguments]

. filename [arguments]
source filename [arguments]

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

bg [jobspec ...]

bind [-m keymap] [-lpsvPSVX]
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 [-m keymap] keyseq:readline-command
bind readline-command-line


break [n]

builtin shell-builtin [arguments]

caller [expr]

cd [-L|[-P [-e]] [-@]] [dir]

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

compgen [option] [word]



complete [-abcdefgjksuv] [-o comp-option] [-DEI] [-A action] [-G glob-
pat] [-W wordlist]
complete -pr [-DEI] [name ...]




compopt [-o option] [-DEI] [+o option] [name]


continue [n]

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


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


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

echo [-neE] [arg ...]

enable [-a] [-dnps] [-f filename] [name ...]

eval [arg ...]

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

exit [n]

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

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




fg [jobspec]

getopts optstring name [arg ...]







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

help [-dms] [pattern]


history [n]
history -c
history -d offset
history -d start-end
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|-L [sigspec | exit_status]

let arg [arg ...]

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

logout Exit a login shell.

mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C
callback] [-c quantum] [array]
readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C
callback] [-c quantum] [array]




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




printf [-v var] format [arguments]





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




pwd [-LP]

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


readonly [-aAf] [-p] [name[=word] ...]

return [n]

set [-abefhkmnptuvxBCEHPT] [-o option-name] [--] [-] [arg ...]
set [+abefhkmnptuvxBCEHPT] [+o option-name] [--] [-] [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 [-HS] -a
ulimit [-HS] [-bcdefiklmnpqrstuvxPRT [limit]]


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

unalias [-a] [name ...]

unset [-fv] [-n] [name ...]

wait [-fn] [-p varname] [id ...]

SHELL COMPATIBILITY MODE
Bash-4.0 introduced the concept of a shell compatibility level, speci-
fied as a set of options to the shopt builtin ( compat31, compat32,
compat40, compat41, and so on). There is only one current compatibil-
ity level -- each option is mutually exclusive. The compatibility
level is intended to allow users to select behavior from previous ver-
sions that is incompatible with newer versions while they migrate
scripts to use current features and behavior. It's intended to be a
temporary solution.

This section does not mention behavior that is standard for a particu-
lar version (e.g., setting compat32 means that quoting the rhs of the
regexp matching operator quotes special regexp characters in the word,
which is default behavior in bash-3.2 and subsequent versions).

If a user enables, say, compat32, it may affect the behavior of other
compatibility levels up to and including the current compatibility
level. The idea is that each compatibility level controls behavior
that changed in that version of bash, but that behavior may have been
present in earlier versions. For instance, the change to use locale-
based comparisons with the [[ command came in bash-4.1, and earlier
versions used ASCII-based comparisons, so enabling compat32 will enable
ASCII-based comparisons as well. That granularity may not be suffi-
cient for all uses, and as a result users should employ compatibility
levels carefully. Read the documentation for a particular feature to
find out the current behavior.

Bash-4.3 introduced a new shell variable: BASH_COMPAT. The value as-
signed to this variable (a decimal version number like 4.2, or an inte-
ger corresponding to the compatNN option, like 42) determines the com-
patibility level.

Starting with bash-4.4, Bash has begun deprecating older compatibility
levels. Eventually, the options will be removed in favor of BASH_COM-
PAT.

Bash-5.0 is the final version for which there will be an individual
shopt option for the previous version. Users should use BASH_COMPAT on
bash-5.0 and later versions.

The following table describes the behavior changes controlled by each
compatibility level setting. The compatNN tag is used as shorthand for
setting the compatibility level to NN using one of the following mecha-
nisms. For versions prior to bash-5.0, the compatibility level may be
set using the corresponding compatNN shopt option. For bash-4.3 and
later versions, the BASH_COMPAT variable is preferred, and it is re-
quired for bash-5.1 and later versions.

compat31

compat32

compat40

compat41

compat42

compat43

compat44

compat50

compat51

RESTRICTED SHELL
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:

o changing directories with cd

o setting or unsetting the values of SHELL, PATH, HISTFILE, ENV,

o specifying command names containing /

o specifying a filename containing a / as an argument to the .

o specifying a filename containing a slash as an argument to the

o specifying a filename containing a slash as an argument to the

o importing function definitions from the shell environment at

o parsing the value of SHELLOPTS from the shell environment at

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

o using the exec builtin command to replace the shell with another

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

o using the enable builtin command to enable disabled shell

o specifying the -p option to the command builtin command

o turning off restricted mode with set +r or shopt -u re-

These restrictions are enforced after any startup files are read.

When a command that is found to be a shell script is executed (see COM-
MAND EXECUTION above), rbash turns off any restrictions in the shell
spawned to execute the script.

SEE ALSO
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 --
http://tiswww.case.edu/~chet/bash/POSIX -- a description of posix mode
sh, ksh, csh
emacs, vi
readline(3)

FILES
/bin/bash
/etc/profile
/etc/bash.bashrc
/etc/bash.bash.logout
~/.bash_profile
~/.bashrc
~/.bash_logout
~/.bash_history
~/.inputrc

AUTHORS
Brian Fox, Free Software Foundation
bfox@gnu.org

Chet Ramey, Case Western Reserve University
chet.ramey@case.edu

BUG REPORTS
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
ftp://ftp.gnu.org/pub/gnu/bash/ and http://git.savan-
nah.gnu.org/cgit/bash.git/snapshot/bash-master.tar.gz.

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:

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.ramey@case.edu.

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

Array variables may not (yet) be exported.

There may be only one active coprocess at a time.