Go to the first, previous, next, last section, table of contents.


Bash Features

This section describes features unique to Bash.

Invoking Bash

bash [long-opt] [-ir] [-abefhkmnptuvxdBCDHP] [-o option] [argument ...]
bash [long-opt] [-abefhkmnptuvxdBCDHP] [-o option] -c string [argument ...]
bash [long-opt] -s [-abefhkmnptuvxdBCDHP] [-o option] [argument ...]

In addition to the single-character shell command-line options (see section The Set Builtin), there are several multi-character options that you can use. These options must appear on the command line before the single-character options in order for them to be recognized.

--dump-strings
Equivalent to `-D'.
--help
Display a usage message on standard output and exit sucessfully.
--login
Make this shell act as if it were directly invoked by login. This is equivalent to `exec -l bash' but can be issued from another shell, such as csh. If you wanted to replace your current login shell with a Bash login shell, you would say `exec bash --login'.
--noediting
Do not use the GNU Readline library (see section Command Line Editing) to read interactive command lines.
--noprofile
Don't load the system-wide startup file `/etc/profile' or any of the personal initialization files `~/.bash_profile', `~/.bash_login', or `~/.profile' when Bash is invoked as a login shell.
--norc
Don't read the `~/.bashrc' initialization file in an interactive shell. This is on by default if the shell is invoked as sh.
--posix
Change the behavior of Bash where the default operation differs from the POSIX 1003.2 standard to match the standard. This is intended to make Bash behave as a strict superset of that standard. See section Bash POSIX Mode, for a description of the Bash POSIX mode.
--rcfile filename
Execute commands from filename (instead of `~/.bashrc') in an interactive shell.
--restricted
Make the shell a restricted shell (see section The Restricted Shell).
--verbose
Equivalent to `-v'.
--version
Show version information for this instance of Bash on the standard output and exit successfully.

There are several single-character options you can give which are not available with the set builtin.

-c string
Read and execute commands from string after processing the options, then exit. Any remaining arguments are assigned to the positional parameters, starting with $0.
-i
Force the shell to run interactively.
-r
Make the shell restricted.
-s
If this flag is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell.
-D
A list of all double-quoted strings preceded by `$' is printed on the standard ouput. These are the strings that are subject to language translation when the current locale is not C or POSIX (see section Locale-Specific Translation). This implies the `-n' option; no commands will be executed.

An interactive shell is one whose input and output are both connected to terminals (as determined by isatty()), or one started with the `-i' option.

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 (see section Shell Scripts). When Bash is invoked in this fashion, $0 is set to the name of the file, and the positional parameters are set to the remaining arguments. Bash reads and executes commands from this file, then exits. Bash's exit status is the exit status of the last command executed in the script. If no commands are executed, the exit status is 0.

Bash Startup Files

This section describs how Bash executes its startup files. If any of the files exist but cannot be read, Bash reports an error. Tildes are expanded in file names as described above under Tilde Expansion (see section Tilde Expansion).

When Bash is invoked as an interactive login shell, it first reads and executes commands from the file `/etc/profile', if that file exists. After reading that file, it looks for `~/.bash_profile', `~/.bash_login', and `~/.profile', in that order, and reads and executes commands from the first one that exists and is readable. The `--noprofile' option may be used when the shell is started to inhibit this behavior.

When a login shell exits, Bash reads and executes commands from the file `~/.bash_logout', if it exists.

When an interactive shell that is not a login shell is started, Bash reads and executes commands from `~/.bashrc', if that file exists. This may be inhibited by using the `--norc' option. The `--rcfile file' option will force Bash to read and execute commands from file instead of `~/.bashrc'.

So, typically, your `~/.bash_profile' contains the line

if [ -f `~/.bashrc' ]; then . `~/.bashrc'; fi

after (or before) any login-specific initializations.

When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:

if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi

but the value of the PATH variable is not used to search for the file name.

If Bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well.

When invoked as a login shell, it first attempts to read and execute commands from `/etc/profile' and `~/.profile', in that order. The `--noprofile' option may be used to inhibit this behavior. When invoked as an interactive shell with the name sh, bash looks for the variable ENV, expands its value if it is defined, and uses the expanded value as the name of a file to read and execute. Since a shell invoked as sh does not attempt to read and execute commands from any other startup files, the `--rcfile' option has no effect. A non-interactive shell invoked with the name sh does not attempt to read any 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, the ENV variable is expanded and commands are read and executed from the file whose name is the expanded value. No other startup files are read. This is done by interactive shells only.

Bash attempts to determine when it is being run by the remote shell daemon, usually rshd. If Bash determines it is being run by rshd, it reads and executes commands from `~/.bashrc', if that file exists and is readable. It will not do this if invoked as sh. The `--norc' option may be used to inhibit this behavior, and the `--rcfile' option may be used to force another file to be read, but rshd does not generally invoke the shell with those options or allow them to be specified.

Is This Shell Interactive?

As defined in section Invoking Bash, an interactive shell is one whose input and output are both connected to terminals (as determined by isatty(3)), or one started with the `-i' option.

You may wish to determine within a startup script whether Bash is running interactively or not. To do this, examine the variable $PS1; it is unset in non-interactive shells, and set in interactive shells. Thus:

if [ -z "$PS1" ]; then
        echo This shell is not interactive
else
        echo This shell is interactive
fi

Alternatively, you may test the value of the `-' special parameter. It contains i when the shell is interactive. For example:

case "$-" in
*i*)	echo This shell is interactive ;;
*)	echo This shell is not interactive ;;
esac

Bash Builtin Commands

This section describes builtin commands which are unique to or have been extended in Bash.

bind
bind [-m keymap] [-lpsvPSV] [-q name] [-r keyseq]
bind [-m keymap] -f filename
bind [-m keymap] keyseq:function-name
Display current Readline (see section Command Line Editing) key and function bindings, or bind a key sequence to a Readline function or macro. The binding syntax accepted is identical to that of `.inputrc' (@xref{Readline Init File}), but each binding must be passed as a separate argument: e.g., `"\C-x\C-r":re-read-init-file'. Options, if supplied, have the following meanings:
-m keymap
Use keymap as the keymap to be affected by the subsequent bindings. Acceptable keymap names are emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-command, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard.
-l
List the names of all Readline functions
-p
Display Readline function names and bindings in such a way that they can be re-read
-P
List current Readline function names and bindings
-v
Display Readline variable names and values in such a way that they can be re-read
-V
List current Readline variable names and values
-s
Display Readline key sequences bound to macros and the strings they output in such a way that they can be re-read
-S
Display Readline key sequences bound to macros and the strings they output
-f filename
Read key bindings from filename
-q
Query about which keys invoke the named function
-r keyseq
Remove any current binding for keyseq
builtin
builtin [shell-builtin [args]]
Run a shell builtin. This is useful when you wish to define a shell function with the same name as a shell builtin, but need the functionality of the builtin within the function itself.
command
command [-pVv] command [args ...]
Runs command with arg ignoring shell functions. If you have a shell function called ls, and you wish to call the command ls, you can say `command ls'. The `-p' option means to use a default value for $PATH that is guaranteed to find all of the standard utilities. If either the `-V' or `-v' option is supplied, a description of command is printed. The `-v' option causes a single word indicating the command or file name used to invoke command to be printed; the `-V' option produces a more verbose description.
declare
declare [-afFrxi] [-p] [name[=value]]
Declare variables and give them attributes. If no names are given, then display the values of variables instead. The `-p' option will display the attributes and values of each name. When `-p' is used, additional options are ignored. The `-F' option inhibits the display of function definitions; only the function name and attributes are printed. `-F' implies `-f'. The following options can be used to restrict output to variables with the specified attributes or to give variables attributes:
-a
Each name is an array variable (see section Arrays).
-f
Use function names only.
-i
The variable is to be treated as an integer; arithmetic evaluation (see section Shell Arithmetic) is performed when the variable is assigned a value.
-r
Make names readonly. These names cannot then be assigned values by subsequent assignment statements.
-x
Mark each name for export to subsequent commands via the environment.
Using `+' instead of `-' turns off the attribute instead. When used in a function, declare makes each name local, as with the local command.
echo
echo [-neE] [arg ...]
Output the args, separated by spaces, terminated with a newline. The return status is always 0. If `-n' is specified, the trailing newline is suppressed. If the `-e' option is given, interpretation of the following backslash-escaped characters is enabled. The `-E' option disables the interpretation of these escape characters, even on systems where they are interpreted by default. echo interprets the following escape sequences:
\a
alert (bell)
\b
backspace
\c
suppress trailing newline
\e
escape
\f
form feed
\n
new line
\r
carriage return
\t
horizontal tab
\v
vertical tab
\\
backslash
\nnn
the character whose ASCII code is nnn (octal)
enable
enable [-n] [-p] [-f filename] [-ads] [name ...]
Enable and disable builtin shell commands. This allows you to use a disk command which has the same name as a shell builtin. If `-n' is used, the names become disabled. Otherwise names are enabled. For example, to use the test binary found via $PATH instead of the shell builtin version, type `enable -n test'. If the `-p' option is supplied, or no name arguments appear, a list of shell builtins is printed. With no other arguments, the list consists of all enabled shell builtins. The `-a' option means to list each builtin with an indication of whether or not it is enabled. The `-f' option means to load the new builtin command name from shared object filename, on systems that support dynamic loading. The `-d' option will delete a builtin loaded with `-f'. If there are no options, a list of the shell builtins is displayed. The `-s' option restricts enable to the POSIX.2 special builtins. If `-s' is used with `-f', the new builtin becomes a special builtin.
help
help [pattern]
Display helpful information about builtin commands. If pattern is specified, help gives detailed help on all commands matching pattern, otherwise a list of the builtins is printed.
local
local name[=value]
For each argument, create a local variable called name, and give it value. local can only be used within a function; it makes the variable name have a visible scope restricted to that function and its children.
logout
logout [n]
Exit a login shell, returning a status of n to the shell's parent.
read
read [-a aname] [-p prompt] [-er] [name ...]
One line is read from the standard input, and the first word is assigned to the first name, the second word to the second name, and so on, with leftover words assigned to the last name. Only the characters in the value of the IFS variable are recognized as word delimiters. If no names are supplied, the line read is assigned to the variable REPLY. The return code is zero, unless end-of-file is encountered. Options, if supplied, have the following meanings:
-r
If this option is given, a backslash-newline pair is not ignored, and the backslash is considered to be part of the line.
-p prompt
Display prompt, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal.
-a aname
The words are assigned to sequential indices of the array variable aname, starting at 0.
-e
Readline (see section Command Line Editing) is used to obtain the line.
shopt
shopt [-pqsu] [-o] [optname ...]
Toggle the values of variables controlling optional shell behavior. With no options, or with the `-p' option, a list of all settable options is displayed, with an indication of whether or not each is set. Other options have the following meanings:
-s
Enable (set) each optname
-u
Disable (unset) each optname.
-q
Suppresses normal output; the return status indicates whether the optname is set or unset. If multiple optname arguments are given with `-q', the return status is zero if all optnames are enabled; non-zero otherwise.
-o
Restricts the values of optname to be those defined for the `-o' option to the set builtin (see section The Set Builtin).
If either of `-s' or `-u' is used with no optname arguments, the display is limited to those options which are set or unset, respectively. Unless otherwise noted, the shopt options are disabled (off) by default. The return status when listing options is zero if all optnames are enabled, non-zero otherwise. When setting or unsetting options, the return status is zero unless an optname is not a legal shell option. The list of shopt options is:
cdable_vars
If this is set, an argument to the cd builtin command that is not a directory is assumed to be the name of a variable whose value is the directory to change to.
cdspell
If set, minor errors in the spelling of a directory component in a cd command will be corrected. The errors checked for are transposed characters, a missing character, and a character too many. If a correction is found, the corrected path is printed, and the command proceeds. This option is only used by interactive shells.
checkhash
If this is set, Bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed.
checkwinsize
If set, Bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS.
cmdhist
If set, Bash attempts to save all lines of a multiple-line command in the same history entry. This allows easy re-editing of multi-line commands.
dotglob
If set, Bash includes filenames beginning with a `.' in the results of filename expansion.
execfail
If this is set, a non-interactive shell will not exit if it cannot execute the file specified as an argument to the exec builtin command. An interactive shell does not exit if exec fails.
histappend
If set, the history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file.
histreedit
If set, and Readline is being used, a user is given the opportunity to re-edit a failed history substitution.
histverify
If set, and Readline is being used, the results of history substitution are not immediately passed to the shell parser. Instead, the resulting line is loaded into the Readline editing buffer, allowing further modification.
hostcomplete
If set, and Readline is being used, Bash will attempt to perform hostname completion when a word beginning with `@' is being completed (see section Letting Readline Type For You). This option is enabled by default.
interactive_comments
Allow a word beginning with `#' to cause that word and all remaining characters on that line to be ignored in an interactive shell. This option is enabled by default.
lithist
If enabled, and the cmdhist option is enabled, multi-line commands are saved to the history with embedded newlines rather than using semicolon separators where possible.
mailwarn
If set, and a file that Bash is checking for mail has been accessed since the last time it was checked, the message "The mail in mailfile has been read" is displayed.
nullglob
If set, Bash allows filename patterns which match no files to expand to a null string, rather than themselves.
promptvars
If set, prompt strings undergo variable and parameter expansion after being expanded (see section Controlling the Prompt). This option is enabled by default.
shift_verbose
If this is set, the shift builtin prints an error message when the shift count exceeds the number of positional parameters.
sourcepath
If set, the source builtin uses the value of PATH to find the directory containing the file supplied as an argument. This is enabled by default.
type
type [-all] [-type | -path] [name ...]
For each name, indicate how it would be interpreted if used as a command name. If the `-type' flag is used, type returns a single word which is one of `alias', `function', `builtin', `file' or `keyword', if name is an alias, shell function, shell builtin, disk file, or shell reserved word, respectively. If the name is not found, then nothing is printed, and type returns a failure status. If the `-path' flag is used, type either returns the name of the disk file that would be executed, or nothing if `-type' would not return `file'. If the `-all' flag is used, returns all of the places that contain an executable named file. This includes aliases and functions, if and only if the `-path' flag is not also used. type accepts `-a', `-t', and `-p' as equivalent to `-all', `-type', and `-path', respectively.
ulimit
ulimit [-acdflmnpstuvSH] [limit]
ulimit provides control over the resources available to processes started by the shell, on systems that allow such control. If an option is given, it is interpreted as follows:
-S
change and report the soft limit associated with a resource.
-H
change and report the hard limit associated with a resource.
-a
all current limits are reported.
-c
the maximum size of core files created.
-d
the maximum size of a process's data segment.
-f
the maximum size of files created by the shell.
-l
The maximum size that may be locked into memory.
-m
the maximum resident set size.
-n
the maximum number of open file descriptors.
-p
the pipe buffer size.
-s
the maximum stack size.
-t
the maximum amount of cpu time in seconds.
-u
the maximum number of processes available to a single user.
-v
the maximum amount of virtual memory available to the process.
If limit is given, it is the new value of the specified resource. Otherwise, the current value of the soft limit for the specified resource is printed, unless the `-H' option is supplied. When setting new limits, if neither `-H' nor `-S' is supplied, both the hard and soft limits are set. If no option is given, then `-f' is assumed. Values are in 1024-byte increments, except for `-t', which is in seconds, `-p', which is in units of 512-byte blocks, and `-n' and `-u', which are unscaled values.

The Set Builtin

This builtin is so overloaded that it deserves its own section.

set
set [-abefhkmnptuvxdBCHP] [-o option] [argument ...]
-a
Mark variables which are modified or created for export.
-b
Cause the status of terminated background jobs to be reported immediately, rather than before printing the next primary prompt.
-e
Exit immediately if a simple command exits with a non-zero status.
-f
Disable file name generation (globbing).
-h
Locate and remember (hash) commands as they are looked up for execution.
-k
All arguments in the form of assignment statements are placed in the environment for a command, not just those that precede the command name.
-m
Job control is enabled (see section Job Control).
-n
Read commands but do not execute them.
-o option-name
Set the flag corresponding to option-name:
allexport
same as -a.
braceexpand
same as -B.
emacs
use an emacs-style line editing interface (see section Command Line Editing).
errexit
same as -e.
hashall
same as -h.
histexpand
same as -H.
history
Enable command history, as described in section Bash History Facilities. This option is on by default in interactive shells.
ignoreeof
the shell will not exit upon reading EOF.
keyword
same as -k.
monitor
same as -m.
noclobber
same as -C.
noexec
same as -n.
noglob
same as -f.
notify
same as -b.
nounset
same as -u.
onecmd
same as -t.
physical
same as -P.
posix
change the behavior of Bash where the default operation differs from the POSIX 1003.2 standard to match the standard. This is intended to make Bash behave as a strict superset of that standard.
privileged
same as -p.
verbose
same as -v.
vi
use a vi-style line editing interface.
xtrace
same as -x.
-p
Turn on privileged mode. In this mode, the $BASH_ENV file is not processed, and shell functions are not inherited from the environment. This is enabled automatically on startup if the effective user (group) id is not equal to the real user (group) id. Turning this option off causes the effective user and group ids to be set to the real user and group ids.
-t
Exit after reading and executing one command.
-u
Treat unset variables as an error when substituting.
-v
Print shell input lines as they are read.
-x
Print commands and their arguments as they are executed.
-B
The shell will perform brace expansion (see section Brace Expansion). This option is on by default.
-C
Disallow output redirection to existing files.
-H
Enable `!' style history substitution (see section Interactive History Expansion). This flag is on by default for interactive shells.
-P
If set, do not follow symbolic links when performing commands such as cd which change the current directory. The physical directory is used instead. By default, Bash follows the logical chain of directories when performing commands which change the current directory. For example, if `/usr/sys' is a link to `/usr/local/sys' then:
$ cd /usr/sys; echo $PWD
/usr/sys
$ cd ..; pwd
/usr
If set -P is on, then:
$ cd /usr/sys; echo $PWD
/usr/local/sys
$ cd ..; pwd
/usr/local
--
If no arguments follow this flag, then the positional parameters are unset. Otherwise, the positional parameters are set to the arguments, even if some of them begin with a `-'.
-
Signal the end of options, cause all remaining arguments to be assigned to the positional parameters. The `-x' and `-v' options are turned off. If there are no arguments, the positional parameters remain unchanged.
Using `+' rather than `-' causes these flags to be turned off. The flags can also be used upon invocation of the shell. The current set of flags may be found in $-. The remaining N arguments are positional parameters and are assigned, in order, to $1, $2, ... $N. If no arguments are given, all shell variables are printed.

Bash Conditional Expressions

Conditional expressions are used by the test and [ builtins.

Expressions may be unary or binary. Unary expressions are often used to examine the status of a file. There are string operators and numeric comparison operators as well. Each operator and operand must be a separate argument. If file is of the form `/dev/fd/N', then file descriptor N is checked. Expressions are composed of the following primaries:

-b file
True if file exists and is a block special file.
-c file
True if file exists and is a character special file.
-d file
True if file exists and is a directory.
-e file
True if file exists.
-f file
True if file exists and is a regular file.
-g file
True if file exists and is set-group-id.
-k file
True if file has its "sticky" bit set.
-L file
True if file exists and is a symbolic link.
-p file
True if file exists and is a named pipe.
-r file
True if file exists and is readable.
-s file
True if file exists and has a size greater than zero.
-S file
True if file exists and is a socket.
-t fd
True if fd is opened on a terminal.
-u file
True if file exists and its set-user-id bit is set.
-w file
True if file exists and is writable.
-x file
True if file exists and is executable.
-O file
True if file exists and is owned by the effective user id.
-G file
True if file exists and is owned by the effective group id.
file1 -nt file2
True if file1 is newer (according to modification date) than file2.
file1 -ot file2
True if file1 is older than file2.
file1 -ef file2
True if file1 and file2 have the same device and inode numbers.
-o optname
True if shell option optname is enabled. The list of options appears in the description of the `-o' option to the set builtin (see section The Set Builtin).
-z string
True if the length of string is zero.
-n string
string
True if the length of string is non-zero.
string1 = string2
True if the strings are equal. `==' may be used in place of `='.
string1 != string2
True if the strings are not equal.
string1 < string2
True if string1 sorts before string2 lexicographically.
string1 > string2
True if string1 sorts after string2 lexicographically.
! expr
True if expr is false.
expr1 -a expr2
True if both expr1 and expr2 are true.
expr1 -o expr2
True if either expr1 and expr2 is true.
arg1 OP arg2
OP is one of `-eq', `-ne', `-lt', `-le', `-gt', or `-ge'. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers.

The Bash test and [ builtins evaluate conditional expressions using a set of rules based on the number of arguments. These are the rules:

0 arguments
The expression is false.
1 argument
The expression is true if and only if the argument is not null.
2 arguments
If the first argument is `!', the expression is true if and only if the second argument is null. If the first argument is one of the listed unary operators, the expression is true if the unary test is true. If the first argument is not a legal unary operator, the expression is false.
3 arguments
If the first argument is `!', the value is the negation of the two-argument test using the second and third arguments. If the second argument is one of the binary operators, the result of the expression is the result of the binary test using the first and third arguments as operands. If the first argument is exactly `(' and the third argument is exactly `)', the result is the one-argument test of the second argument. Otherwise, the expression is false. The `-a' and `-o' operators are considered binary operators in this case.
4 arguments
If the first argument is `!', the result is the negation of the three-argument expression composed of the remaining arguments. Otherwise, the expression is parsed and evaluated according to precedence. `-a' has a higher precedence than `-o'.
5 or more arguments
The expression is parsed and evaluated according to precedence, with `-a' having a higher precedence than `-o'.

Bash Variables

These variables are set or used by Bash, but other shells do not normally treat them specially.

BASH_ENV
If this variable is set when Bash is invoked to execute a shell script, its value is expanded and used as the name of a startup file to read before executing the script. See section Bash Startup Files.
TIMEFORMAT
The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The `%' character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.
%%
A literal `%'.
%[p][l]R
The elapsed time in seconds.
%[p][l]U
The number of CPU seconds spent in user mode.
%[p][l]S
The number of CPU seconds spent in system mode.
%P
The CPU percentage, computed as (%U + %S) / %R.
The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used. The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included. If this variable is not set, bash acts as if it had the value
$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'.
If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.
HISTCONTROL
Set to a value of `ignorespace', it means don't enter lines which begin with a space or tab into the history list. Set to a value of `ignoredups', it means don't enter lines which match the last entered line. A value of `ignoreboth' combines the two options. Unset, or set to any other value than those above, means to save all lines on the history list.
HISTIGNORE
A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must fully specify the line (no implicit `*' is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be escaped using a backslash. The backslash is removed before attempting a match. HISTIGNORE subsumes the function of HISTCONTROL. A pattern of `&' is identical to ignoredups, and a pattern of `[ ]*' is identical to ignorespace. Combining these two patterns, separating them with a colon, provides the functionality of ignoreboth.
HISTFILE
The name of the file to which the command history is saved. The default is `~/.bash_history'.
HISTSIZE
If set, this is the maximum number of commands to remember in the history.
HISTFILESIZE
The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines. The default value is 500. The history file is also truncated to this size after writing it when an interactive shell exits.
histchars
Up to three characters which control history expansion, quick substitution, and tokenization (see section Interactive History Expansion). The first character is the history-expansion-char, that is, the character which signifies the start of a history expansion, normally `!'. The second character is the character which signifies `quick substitution' when seen as the first character on a line, normally `^'. The optional third character is the character which signifies the remainder of the line is a comment, when found as the first character of a word, usually `#'. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment.
HISTCMD
The history number, or index in the history list, of the current command. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset.
HOSTFILE
Contains the name of a file in the same format as `/etc/hosts' that should be read when the shell needs to complete a hostname. You can change the file interactively; the next time you attempt to complete a hostname, Bash will add the contents of the new file to the already existing database.
MAILCHECK
How often (in seconds) that the shell should check for mail in the files specified in MAILPATH.
PROMPT_COMMAND
If present, this contains a string which is a command to execute before the printing of each primary prompt ($PS1).
UID
The numeric real user id of the current user.
EUID
The numeric effective user id of the current user.
GROUPS
An array variable containing the list of groups of which the current user is a member.
PPID
The process id of the shell's parent process.
HOSTNAME
The name of the current host.
HOSTTYPE
A string describing the machine Bash is running on.
OSTYPE
A string describing the operating system Bash is running on.
MACHTYPE
A string that fully describes the system type on which Bash is executing, in the standard GNU cpu-company-system format.
SHELLOPTS
A colon-separated list of enabled shell options. Each word in the list is a valid argument for the `-o' option to the set builtin command (see section The Set Builtin). The options appearing in SHELLOPTS are those reported as `on' by `set -o'. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly.
FIGNORE
A colon-separated list of suffixes to ignore when performing filename completion. A file name whose suffix matches one of the entries in FIGNORE is excluded from the list of matched file names. A sample value is `.o:~'
GLOBIGNORE
A colon-separated list of patterns defining the set of filenames to be ignored by filename expansion. If a filename matched by a filename expansion pattern also matches one of the patterns in GLOBIGNORE, it is removed from the list of matches.
DIRSTACK
An array variable (see section Arrays) containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset.
PIPESTATUS
An array variable (see section Arrays) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).
INPUTRC
The name of the Readline startup file, overriding the default of `~/.inputrc'.
BASH
The full filename used to execute the current instance of Bash.
BASH_VERSION
The version number of the current instance of Bash.
BASH_VERSINFO
An array variable whose members hold version information for this instance of Bash. The values assigned to the array members are as follows:
BASH_VERSINFO[0]
The major version number (the release).
BASH_VERSINFO[1]
The minor version number (the version).
BASH_VERSINFO[2]
The patch level.
BASH_VERSINFO[3]
The build version.
BASH_VERSINFO[4]
The release status (e.g., beta1).
BASH_VERSINFO[5]
The value of MACHTYPE.
SHLVL
Incremented by one each time a new instance of Bash is started. This is intended to be a count of how deeply your Bash shells are nested.
OPTERR
If set to the value 1, Bash displays error messages generated by the getopts builtin command.
LANG
Used to determine the locale category for any category not specifically selected with a variable starting with LC_.
LC_ALL
This variable overrides the value of LANG and any other LC_ variable specifying a locale category.
LC_COLLATE
This variable determines the collation order used when sorting the results of filename expansion (see section Filename Expansion).
LC_MESSAGES
This variable determines the locale used to translate double-quoted strings preceded by a `$' (see section Locale-Specific Translation).
IGNOREEOF
Controls the action of the shell on receipt of an EOF character as the sole input. If set, then the value of it is the number of consecutive EOF characters that can be read as the first character on an input line before the shell will exit. If the variable exists but does not have a numeric value (or has no value) then the default is 10. If the variable does not exist, then EOF signifies the end of input to the shell. This is only in effect for interactive shells.

Shell Arithmetic

Bash includes several mechanisms to evaluate arithmetic expressions and display the result or use it as part of a command.

Arithmetic Evaluation

The shell allows arithmetic expressions to be evaluated, as one of the shell expansions or by the let builtin.

Evaluation is done in long integers with no check for overflow, though division by 0 is trapped and flagged as an error. The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence.

- +
unary minus and plus
! ~
logical and bitwise negation
* / %
multiplication, division, remainder
+ -
addition, subtraction
<< >>
left and right bitwise shifts
<= >= < >
comparison
== !=
equality and inequality
&
bitwise AND
^
bitwise exclusive OR
|
bitwise OR
&&
logical AND
||
logical OR
expr ? expr : expr
conditional evaluation
= *= /= %= += -= <<= >>= &= ^= |=
assignment

Shell variables are allowed as operands; parameter expansion is performed before the expression is evaluated. The value of a parameter is coerced to a long integer within an expression. A shell variable need not have its integer attribute turned on to be used in an expression.

Constants with a leading 0 are interpreted as octal numbers. A leading `0x' or `0X' denotes hexadecimal. Otherwise, numbers take the form [base#]n, where base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base is omitted, then base 10 is used. The digits greater than 9 are represented by the lowercase letters, the uppercase letters, `_', and `@', in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangably to represent numbers between 10 and 35.

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

Arithmetic Expansion

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:

$(( expression ))

The expression is treated as if it were within double quotes, but a double quote inside the braces or parentheses is not treated specially. All tokens in the expression undergo parameter expansion, command substitution, and quote removal. Arithmetic substitutions may be nested.

The evaluation is performed according to the rules listed above. If the expression is invalid, Bash prints a message indicating failure and no substitution occurs.

Arithmetic Builtins

let
let expression [expression]
The let builtin allows arithmetic to be performed on shell variables. Each expression is evaluated according to the rules given previously (see section Arithmetic Evaluation). If the last expression evaluates to 0, let returns 1; otherwise 0 is returned.

Arrays

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

An array is created automatically if any variable is assigned to using the syntax

name[subscript]=value

The subscript is treated as an arithmetic expression that must evaluate to a number greater than or equal to zero. To explicitly declare an array, use

declare -a name

The syntax

declare -a name[subscript]

is also accepted; the subscript is ignored. Attributes may be specified for an array variable using the declare and readonly builtins. Each attribute applies to all members of an array.

Arrays are assigned to using compound assignments of the form

name=(value1 ... valuen)

where each value is of the form [[subscript]=]string. If the optional subscript is supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero. This syntax is also accepted by the declare builtin. Individual array elements may be assigned to using the name[subscript]=value syntax introduced above.

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with the shell's filename expansion operators. If the subscript is `@' or `*', the word expands to all members of the array 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 variable, and ${name[@]} expands each element of name to a separate word. When there are no array members, ${name[@]} expands to nothing. This is analogous to the expansion of the special parameters `@' and `*'. ${#name[subscript]} expands to the length of ${name[subscript]}. If subscript is `@' or `*', the expansion is the number of elements in the array. Referencing an array variable without a subscript is equivalent to referencing element zero.

The unset builtin is used to destroy arrays. unset name[subscript] destroys the array element at index subscript. unset name, where name is an array, removes the entire array. A subscript of `*' or `@' also removes the entire array.

The declare, local, and readonly builtins each accept a `-a' option to specify an array. The read builtin accepts a `-a' option to assign a list of words read from the standard input to an array, and can read values from the standard input into individual array elements. The set and declare builtins display array values in a way that allows them to be reused as input.

Controlling the Prompt

The value of the variable PROMPT_COMMAND is examined just before Bash prints each primary prompt. If it is set and non-null, then the value is executed just as if you had typed it on the command line.

In addition, the following table describes the special characters which can appear in the prompt variables:

\a
a bell character.
\d
the date, in "Weekday Month Date" format (e.g., "Tue May 26").
\e
an escape character.
\h
the hostname, up to the first `.'.
\H
the hostname.
\n
newline.
\s
the name of the shell, the basename of $0 (the portion following the final slash).
\t
the time, in 24-hour HH:MM:SS format.
\T
the time, in 12-hour HH:MM:SS format.
\@
the time, in 12-hour am/pm format.
\v
the version of Bash (e.g., 2.00)
\V
the release of Bash, version + patchlevel (e.g., 2.00.0)
\w
the current working directory.
\W
the basename of $PWD.
\u
your username.
\!
the history number of this command.
\#
the command number of this command.
\$
if the effective uid is 0, #, otherwise $.
\nnn
the character corresponding to the octal number nnn.
\\
a backslash.
\[
begin a sequence of non-printing characters. This could be used to embed a terminal control sequence into the prompt.
\]
end a sequence of non-printing characters.

The Restricted Shell

If Bash is started with the name rbash, or the `--restricted' 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. A restricted shell behaves identically to bash with the exception that the following are disallowed:

Bash POSIX Mode

Starting Bash with the `--posix' command-line option or executing `set -o posix' while Bash is running will cause Bash to conform more closely to the POSIX.2 standard by changing the behavior to match that specified by POSIX.2 in areas where the Bash default differs.

The following list is what's changed when `POSIX mode' is in effect:

  1. When a command in the hash table no longer exists, Bash will re-search $PATH to find the new location. This is also available with `shopt -s checkhash'.
  2. The `>&' redirection does not redirect stdout and stderr.
  3. The message printed by the job control code and builtins when a job exits with a non-zero status is `Done(status)'.
  4. Reserved words may not be aliased.
  5. The POSIX.2 PS1 and PS2 expansions of `!' to the history number and `!!' to `!' are enabled, and parameter expansion is performed on the value regardless of the setting of the promptvars option.
  6. Interactive comments are enabled by default. (Note that Bash has them on by default anyway.)
  7. The POSIX.2 startup files are executed ($ENV) rather than the normal Bash files.
  8. Tilde expansion is only performed on assignments preceding a command name, rather than on all assignment statements on the line.
  9. The default history file is `~/.sh_history' (this is the default value of $HISTFILE).
  10. The output of `kill -l' prints all the signal names on a single line, separated by spaces.
  11. Non-interactive shells exit if filename in . filename is not found.
  12. Redirection operators do not perform filename expansion on the word in the redirection unless the shell is interactive.
  13. Function names must be valid shell names. That is, they may not contain characters other than letters, digits, and underscores, and may not start with a digit. Declaring a function with an illegal name causes a fatal syntax error in non-interactive shells.
  14. POSIX.2 `special' builtins are found before shell functions during command lookup.
  15. If a POSIX.2 special builtin returns an error status, a non-interactive shell exits. The fatal errors are those listed in the POSIX.2 standard, and include things like passing incorrect options, redirection errors, variable assignment errors for assignments preceding the command name, and so on.
  16. If the cd builtin finds a directory to change to using $CDPATH, the value it assigns to the PWD variable does not contain any symbolic links, as if `cd -P' had been executed.
  17. A non-interactive shell exits with an error status if a variable assignment error occurs when no command name follows the assignment statements. A variable assignment error occurs, for example, when trying to assign a value to a read-only variable.
  18. A non-interactive shell exits with an error status if the iteration variable in a for statement or the selection variable in a select statement is a read-only variable.
  19. Process substitution is not available.
  20. Assignment statements preceding POSIX.2 special builtins persist in the shell environment after the builtin completes.
  21. The export and readonly builtin commands display their output in the format required by POSIX.2.

There is other POSIX.2 behavior that Bash does not implement. Specifically:

  1. Assignment statements affect the execution environment of all builtins, not just special ones.


Go to the first, previous, next, last section, table of contents.