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-po-strings
Equivalent to `-D', but the output is in the GNU gettext PO (portable object) file format.
--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. `exec bash --login' will replace the current shell with a Bash login shell.
--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 that may be supplied at invocation 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 a restricted shell (see section The Restricted Shell).
-s
If this option 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.
--
A -- signals the end of options and disables further option processing. Any arguments after the -- are treated as filenames and arguments.

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.

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 an interactive 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, interactive shells expand the ENV variable and commands are read and executed from the file whose name is the expanded value. No other startup files are read.

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

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.

To determine within a startup script whether Bash is running interactively or not, 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, startup scripts 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]
bind [-m keymap] [-q function] [-u function] [-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 function
Query about which keys invoke the named function.
-u function
Unbind all keys bound to the named function.
-r keyseq
Remove any current binding for keyseq.
The return status is zero unless an invalid option is supplied or an error occurs.
builtin
builtin [shell-builtin [args]]
Run a shell builtin, passing it args, and return its exit status. This is useful when defining a shell function with the same name as a shell builtin, retaining the functionality of the builtin within the function. The return status is non-zero if shell-builtin is not a shell builtin command.
command
command [-pVv] command [arguments ...]
Runs command with arguments ignoring any shell function named command. Only shell builtin commands or commands found by searching the PATH are executed. If there is a shell function named ls, running `command ls' within the function will execute the external command ls instead of calling the function recursively. The `-p' option means to use a default value for $PATH that is guaranteed to find all of the standard utilities. The return status in this case is 127 if command cannot be found or an error occurred, and the exit status of command otherwise. If either the `-V' or `-v' option is supplied, a description of command is printed. The `-v' option causes a single word indicating the command or file name used to invoke command to be displayed; the `-V' option produces a more verbose description. In this case, the return status is zero if command is found, and non-zero if not.
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 or unset.
-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. The return status is zero unless an invalid option is encountered, an attempt is made to define a function using -f foo=bar, an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax (see section Arrays), one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-existent function with `-f'.
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 the octal value nnn (one to three digits)
\xnnn
the character whose ASCII code is the hexadecimal value nnn (one to three digits)
enable
enable [-n] [-p] [-f filename] [-ads] [name ...]
Enable and disable builtin shell commands. Disabling a builtin allows a disk command which has the same name as a shell builtin to be executed with specifying a full pathname, even though the shell normally searches for builtins before disk commands. 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 special builtins. If `-s' is used with `-f', the new builtin becomes a special builtin. The return status is zero unless a name is not a shell builtin or there is an error loading a new builtin from a shared object.
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. The return status is zero unless no command matches pattern.
let
let expression [expression]
The let builtin allows arithmetic to be performed on shell variables. Each expression is evaluated according to the rules given below in section Shell Arithmetic. If the last expression evaluates to 0, let returns 1; otherwise 0 is returned.
local
local name[=value]
For each argument, a local variable named name is created, and assigned 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. The return status is zero unless local is used outside a function or an invalid name is supplied.
logout
logout [n]
Exit a login shell, returning a status of n to the shell's parent.
printf
printf format [arguments]
Write the formatted arguments to the standard output under the control of the format. The format is a character string which contains three types of objects: plain characters, which are simply copied to standard output, character escape sequences, which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. In addition to the standard printf(1) formats, `%b' causes printf to expand backslash escape sequences in the corresponding argument, and `%q' causes printf to output the corresponding argument in a format that can be reused as shell input. The format is reused as necessary to consume all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied.
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 and their intervening separators assigned to the last name. If there are fewer words read from the standard input than names, the remaining names are assigned empty values. The characters in the value of the IFS variable are used to split the line into words. 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. All elements are removed from aname before the assignment. Other name arguments are ignored.
-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. The `-p' option causes output to be displayed in a form that may be reused as input. 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 `-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 valid 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.
expand_aliases
If set, aliases are expanded as described below< under Aliases (see section Aliases). This option is enabled by default for interactive shells.
extglob
If set, the extended pattern matching features described above (see section Pattern Matching) are enabled.
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 containing a `@' is being completed (see section Letting Readline Type For You). This option is enabled by default.
huponexit
If set, Bash will send SIGHUP to all jobs when an interactive login shell exits (see section Signals).
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.
nocaseglob
If set, Bash matches filenames in a case-insensitive fashion when performing filename expansion.
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 option is enabled by default.
The return status when listing options is zero if all optnames are enabled, non-zero otherwise. When setting or unsetting options, the return status is zero unless an optname is not a valid shell option.
source
source filename
A synonym for . (see section Bourne Shell Builtins).
type
type [-atp] [name ...]
For each name, indicate how it would be interpreted if used as a command name. If the `-t' option is used, type prints 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 `-p' option is used, type either returns the name of the disk file that would be executed, or nothing if `-t' would not return `file'. If the `-a' option is used, type returns all of the places that contain an executable named file. This includes aliases and functions, if and only if the `-p' option is not also used. The return status is zero if any of the names are found, non-zero if none are found.
typeset
typeset [-afFrxi] [-p] [name[=value]]
The typeset command is supplied for compatibility with the Korn shell; however, it has been deprecated in favor of the declare builtin command.
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 return status is zero unless an invalid option is supplied, a non-numeric argument other than unlimited is supplied as a limit, or an error occurs while setting a new limit.

The Set Builtin

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

set
set [--abefhkmnptuvxBCHP] [-o option] [argument ...]
If no options or arguments are supplied, set displays the names and values of all shell variables and functions, sorted according to the current locale, in a format that may be reused as input. When options are supplied, they set or unset shell attributes. Options, if specified, have the following meanings:
-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 (see section Simple Commands) exits with a non-zero status, unless the command that fails is part of an until or while loop, part of an if statement, part of a && or || list, or if the command's return status is being inverted using !.
-f
Disable file name generation (globbing).
-h
Locate and remember (hash) commands as they are looked up for execution. This option is enabled by default.
-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; this may be used to check a script for syntax errors. This option is ignored by interactive shells.
-o option-name
Set the option 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
An interactive 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 (see section Bash POSIX Mode). 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 and $ENV files are not processed, shell functions are not inherited from the environment, and the SHELLOPTS variable, if it appears in the environment, is ignored. 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 performing parameter expansion. An error message will be written to the standard error, and a non-interactive shell will exit.
-v
Print shell input lines as they are read.
-x
Print a trace of simple commands and their arguments after they are expanded and before they are executed.
-B
The shell will perform brace expansion (see section Brace Expansion). This option is on by default.
-C
Prevent output redirection using `>', `>&', and `<>' from overwriting existing files.
-H
Enable `!' style history substitution (see section History Expansion). This option 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 symbolic 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 option, 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 options to be turned off. The options can also be used upon invocation of the shell. The current set of options may be found in $-. The remaining N arguments are positional parameters and are assigned, in order, to $1, $2, ... $N. The special parameter # is set to N. The return status is always zero unless an invalid option is supplied.

Bash Conditional Expressions

Conditional expressions are used by the [[ compound command and the test and [ builtin commands.

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. If any file argument to one of the primaries is of the form `/dev/fd/N', then file descriptor N is checked.

-a file
True if file exists.
-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 its set-group-id bit is set.
-k file
True if file exists and its "sticky" bit is set.
-p file
True if file exists and is a named pipe (FIFO).
-r file
True if file exists and is readable.
-s file
True if file exists and has a size greater than zero.
-t fd
True if file descriptor fd is open and refers to 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.
-L file
True if file exists and is a symbolic link.
-S file
True if file exists and is a socket.
-N file
True if file exists and has been modified since it was last read.
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 in the current locale.
string1 > string2
True if string1 sorts after string2 lexicographically in the current locale.
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.

Bash Variables

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

BASH
The full pathname used to execute the current instance of Bash.
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.
BASH_VERSION
The version number of the current instance of Bash.
BASH_VERSINFO
A readonly 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.
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.
EUID
The numeric effective user id of the current user. This variable is readonly.
FCEDIT
The editor used as a default by the `-e' option to the fc builtin command.
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.
GROUPS
An array variable containing the list of groups of which the current user is a member. This variable is readonly.
histchars
Up to three characters which control history expansion, quick substitution, and tokenization (see section 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 indicates that 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.
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. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL.
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. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE. 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
The maximum number of commands to remember on the history list. The default value is 500.
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.
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.
HOSTNAME
The name of the current host.
HOSTTYPE
A string describing the machine Bash is running on.
IGNOREEOF
Controls the action of the shell on receipt of an EOF character as the sole input. If set, the value denotes 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.
INPUTRC
The name of the Readline startup file, overriding the default of `~/.inputrc'.
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, and determines the behavior of range expressions, equivalence classes, and collating sequences within filename expansion and pattern matching (see section Filename Expansion).
LC_CTYPE
This variable determines the interpretation of characters and the behavior of character classes within filename expansion and pattern matching (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).
LINENO
The line number in the script or shell function currently executing.
MACHTYPE
A string that fully describes the system type on which Bash is executing, in the standard GNU cpu-company-system format.
MAILCHECK
How often (in seconds) that the shell should check for mail in the files specified in the MAILPATH or MAIL variables.
OLDPWD
The previous working directory as set by the cd builtin.
OPTERR
If set to the value 1, Bash displays error messages generated by the getopts builtin command.
OSTYPE
A string describing the operating system Bash is running on.
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).
PPID
The process id of the shell's parent process. This variable is readonly.
PROMPT_COMMAND
If present, this contains a string which is a command to execute before the printing of each primary prompt ($PS1).
PS3
The value of this variable is used as the prompt for the select command. If this variable is not set, the select command prompts with `#? '
PS4
This is the prompt printed before the command line is echoed when the `-x' option is set (see section The Set Builtin). The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is `+ '.
PWD
The current working directory as set by the cd builtin.
RANDOM
Each time this parameter is referenced, a random integer between 0 and 32767 is generated. Assigning a value to this variable seeds the random number generator.
REPLY
The default variable for the read builtin.
SECONDS
This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment.
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.
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.
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.
TMOUT
If set to a value greater than zero, the value is interpreted as the number of seconds to wait for input after issuing the primary prompt. Bash terminates after that number of seconds if input does not arrive.
UID
The numeric real user id of the current user. This variable is readonly.

Shell Arithmetic

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
**
exponentiation
* / %
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.

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.

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 alias name and the replacement text may contain any valid shell input, including shell metacharacters, with the exception that the alias name may not contain `='. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to "ls -F", for instance, and Bash does not try to recursively expand the replacement text. If the last character of the alias value is a space or tab character, 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, as in csh. If arguments are needed, a shell function should be used (see section Shell Functions).

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see section Bash Builtin Commands).

The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias. This behavior is also an issue when functions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands.

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

Alias Builtins

alias
alias [-p] [name[=value] ...]
Without arguments or with the `-p' option, alias prints the list of aliases on the standard output in a form that allows them to be reused as input. If arguments are supplied, an alias is defined for each name whose value is given. If no value is given, the name and value of the alias is printed.
unalias
unalias [-a] [name ... ]
Remove each name from the list of aliases. If `-a' is supplied, all aliases are removed.

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.

The Directory Stack

The directory stack is a list of recently-visited directories. The pushd builtin adds directories to the stack as it changes the current directory, and the popd builtin removes specified directories from the stack and changes the current directory to the directory removed. The dirs builtin displays the contents of the directory stack.

The contents of the directory stack are also visible as the value of the DIRSTACK shell variable.

dirs
dirs [+N | -N] [-clvp]
Display the list of currently remembered directories. Directories are added to the list with the pushd command; the popd command removes directories from the list.
+N
Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero.
-N
Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero.
-c
Clears the directory stack by deleting all of the elements.
-l
Produces a longer listing; the default listing format uses a tilde to denote the home directory.
-p
Causes dirs to print the directory stack with one entry per line.
-v
Causes dirs to print the directory stack with one entry per line, prefixing each entry with its index in the stack.
popd
popd [+N | -N] [-n]
Remove the top entry from the directory stack, and cd to the new top directory. When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0.
+N
Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero.
-N
Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero.
-n
Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated.
pushd
pushd [dir | +N | -N] [-n]
Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories.
+N
Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
-N
Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack.
-n
Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated.
dir
Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir'. cds to dir.

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 it had been typed 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
A newline.
\r
A carriage return.
\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.
\u
The username of the current user.
\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.
\!
The history number of this command.
\#
The command number of this command.
\$
If the effective uid is 0, #, otherwise $.
\nnn
The character whose ASCII code is the octal value 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 values of PS1 and PS2 regardless of the setting of the promptvars option.
  6. Interactive comments are enabled by default. (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. Non-interactive shells exit if a syntax error in an arithmetic expansion results in an invalid expression.
  13. Redirection operators do not perform filename expansion on the word in the redirection unless the shell is interactive.
  14. 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 invalid name causes a fatal syntax error in non-interactive shells.
  15. POSIX.2 `special' builtins are found before shell functions during command lookup.
  16. 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.
  17. 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.
  18. If $CDPATH is set, the cd builtin will not implicitly append the current directory to it. This means that cd will fail if no valid directory name can be constructed from any of the entries in $CDPATH, even if the a directory with the same name as the name given as an argument to cd exists in the current directory.
  19. 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 readonly variable.
  20. 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 readonly variable.
  21. Process substitution is not available.
  22. Assignment statements preceding POSIX.2 special builtins persist in the shell environment after the builtin completes.
  23. 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.