Bash Reference Manual - 5. Bash Features
5. Bash Features
This section describes features unique to Bash.
5.1 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 5.5 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
gettextPO (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 8. 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 5.14 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 5.13 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 5.13 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
CorPOSIX(see section 3.1.2.5 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 3.8 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.
5.2 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 3.5.2 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.
5.3 Is This Shell Interactive?
As defined in section 5.1 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
5.4 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 8. 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, andvi-insert.viis equivalent tovi-command;emacsis equivalent toemacs-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.
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 thePATHare executed. If there is a shell function namedls, running `command ls' within the function will execute the external commandlsinstead of calling the function recursively. The `-p' option means to use a default value for$PATHthat 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 5.10 Arrays).
-f- Use function names only.
-i- The variable is to be treated as an integer; arithmetic evaluation (see section 5.8 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.
declaremakes each name local, as with thelocalcommand. 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 5.10 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.echointerprets 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
ASCIIcode is the octal value nnn (one to three digits) \xnnn-
the character whose
ASCIIcode 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 thetestbinary found via$PATHinstead 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 restrictsenableto 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,helpgives 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]
Theletbuiltin allows arithmetic to be performed on shell variables. Each expression is evaluated according to the rules given below in section 5.8 Shell Arithmetic. If the last expression evaluates to 0,letreturns 1; otherwise 0 is returned. local-
local name[=value]
For each argument, a local variable named name is created, and assigned value.localcan 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 unlesslocalis 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-
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 standardprintfformat [arguments]printf(1)formats, `%b' causesprintfto expand backslash escape sequences in the corresponding argument, and `%q' causesprintfto 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 theIFSvariable are used to split the line into words. If no names are supplied, the line read is assigned to the variableREPLY. 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 8. 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
setbuiltin (see section 5.5 The Set Builtin).
shoptoptions 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 ofshoptoptions is:cdable_vars-
If this is set, an argument to the
cdbuiltin 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
cdcommand 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
LINESandCOLUMNS. 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
execbuiltin command. An interactive shell does not exit ifexecfails. expand_aliases- If set, aliases are expanded as described below< under Aliases (see section 5.9 Aliases). This option is enabled by default for interactive shells.
extglob- If set, the extended pattern matching features described above (see section 3.5.8.1 Pattern Matching) are enabled.
histappend-
If set, the history list is appended to the file named by the value
of the
HISTFILEvariable 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 8.3.6 Letting Readline Type For You). This option is enabled by default.
huponexit-
If set, Bash will send
SIGHUPto all jobs when an interactive login shell exits (see section 3.7.6 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
cmdhistoption 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 5.12 Controlling the Prompt). This option is enabled by default.
shift_verbose-
If this is set, the
shiftbuiltin prints an error message when the shift count exceeds the number of positional parameters. sourcepath-
If set, the
sourcebuiltin uses the value ofPATHto find the directory containing the file supplied as an argument. This option is enabled by default.
source-
source filename
A synonym for.(see section 4.1 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,typeprints 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, andtypereturns a failure status. If the `-p' option is used,typeeither 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,typereturns 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]]
Thetypesetcommand is supplied for compatibility with the Korn shell; however, it has been deprecated in favor of thedeclarebuiltin command. ulimit-
ulimit [-acdflmnpstuvSH] [limit]
ulimitprovides 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.
unlimitedis supplied as a limit, or an error occurs while setting a new limit.
5.5 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,setdisplays 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 3.2.1 Simple Commands) exits
with a non-zero status, unless the command that fails is part of an
untilorwhileloop, part of anifstatement, 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 6. 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 8. Command Line Editing). errexit-
Same as
-e. hashall-
Same as
-h. histexpand-
Same as
-H. history- Enable command history, as described in section 7.1 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 5.14 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_ENVand$ENVfiles are not processed, shell functions are not inherited from the environment, and theSHELLOPTSvariable, 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 3.5.1 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 7.3 History Expansion). This option is on by default for interactive shells.
-P-
If set, do not follow symbolic links when performing commands such as
cdwhich 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
Ifset -Pis 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.
$-. 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.
5.6 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
setbuiltin (see section 5.5 The Set Builtin). -z string- True if the length of string is zero.
-n stringstring- 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-
OPis 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.
5.7 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 5.2 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 5.10 Arrays)
containing the current contents of the directory stack.
Directories appear in the stack in the order they are displayed by the
dirsbuiltin. Assigning to members of this array variable may be used to modify directories already in the stack, but thepushdandpopdbuiltins must be used to add and remove directories. Assignment to this variable will not change the current directory. IfDIRSTACKis 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
fcbuiltin 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
FIGNOREis 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 7.3 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
HISTCMDis 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
HISTCONTROLare 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 ofHISTIGNORE.HISTIGNOREsubsumes the function ofHISTCONTROL. A pattern of `&' is identical toignoredups, and a pattern of `[ ]*' is identical toignorespace. Combining these two patterns, separating them with a colon, provides the functionality ofignoreboth. 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
EOFcharacter as the sole input. If set, the value denotes the number of consecutiveEOFcharacters 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, thenEOFsignifies 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
LANGand any otherLC_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 3.5.8 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 3.5.8 Filename Expansion).
LC_MESSAGES- This variable determines the locale used to translate double-quoted strings preceded by a `$' (see section 3.1.2.5 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
MAILPATHorMAILvariables. OLDPWD-
The previous working directory as set by the
cdbuiltin. OPTERR-
If set to the value 1, Bash displays error messages
generated by the
getoptsbuiltin command. OSTYPE- A string describing the operating system Bash is running on.
PIPESTATUS- An array variable (see section 5.10 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
selectcommand. If this variable is not set, theselectcommand prompts with `#? ' PS4-
This is the prompt printed before the command line is echoed
when the `-x' option is set (see section 5.5 The Set Builtin).
The first character of
PS4is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is `+ '. PWD-
The current working directory as set by the
cdbuiltin. 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
readbuiltin. 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
setbuiltin command (see section 5.5 The Set Builtin). The options appearing inSHELLOPTSare 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
timereserved 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.
lspecifies 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
If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed.$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS' 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.
5.8 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.
5.9 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 3.3 Shell Functions).
Aliases are not expanded when the shell is not interactive,
unless the expand_aliases shell option is set using
shopt (see section 5.4 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.
5.9.1 Alias Builtins
alias-
alias [
Without arguments or with the `-p' option,-p] [name[=value] ...]aliasprints 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.
5.10 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.
5.11 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 thepushdcommand; thepopdcommand removes directories from the list.+N-
Displays the Nth directory (counting from the left of the
list printed by
dirswhen invoked without options), starting with zero. -N-
Displays the Nth directory (counting from the right of the
list printed by
dirswhen 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
dirsto print the directory stack with one entry per line. -v-
Causes
dirsto 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, andcdto the new top directory. When no arguments are given,popdremoves the top directory from the stack and performs acdto the new top directory. The elements are numbered from 0 starting at the first directory listed withdirs; i.e.,popdis equivalent topopd +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 thencdto dir. With no arguments,pushdexchanges 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 `
cddir'.cds to dir.
5.12 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.
5.13 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:
-
Changing directories with the
cdbuiltin. -
Setting or unsetting the values of the
SHELLorPATHvariables. - Specifying command names containing slashes.
-
Specifying a filename containing a slash as an argument to the
.builtin command. - Importing function definitions from the shell environment at startup.
-
Parsing the value of
SHELLOPTSfrom the shell environment at startup. - Redirecting output using the `>', `>|', `<>', `>&', `&>', and `>>' redirection operators.
-
Using the
execbuiltin to replace the shell with another command. -
Adding or deleting builtin commands with the
`-f' and `-d' options to the
enablebuiltin. -
Specifying the `-p' option to the
commandbuiltin. - Turning off restricted mode with `set +r' or `set +o restricted'.
5.14 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:
-
When a command in the hash table no longer exists, Bash will re-search
$PATHto find the new location. This is also available with `shopt -s checkhash'. - The `>&' redirection does not redirect stdout and stderr.
- The message printed by the job control code and builtins when a job exits with a non-zero status is `Done(status)'.
- Reserved words may not be aliased.
-
The POSIX.2
PS1andPS2expansions of `!' to the history number and `!!' to `!' are enabled, and parameter expansion is performed on the values ofPS1andPS2regardless of the setting of thepromptvarsoption. - Interactive comments are enabled by default. (Bash has them on by default anyway.)
-
The POSIX.2 startup files are executed (
$ENV) rather than the normal Bash files. - Tilde expansion is only performed on assignments preceding a command name, rather than on all assignment statements on the line.
-
The default history file is `~/.sh_history' (this is the
default value of
$HISTFILE). - The output of `kill -l' prints all the signal names on a single line, separated by spaces.
-
Non-interactive shells exit if filename in
.filename is not found. - Non-interactive shells exit if a syntax error in an arithmetic expansion results in an invalid expression.
- Redirection operators do not perform filename expansion on the word in the redirection unless the shell is interactive.
-
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. - POSIX.2 `special' builtins are found before shell functions during command lookup.
- 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.
-
If the
cdbuiltin finds a directory to change to using$CDPATH, the value it assigns to thePWDvariable does not contain any symbolic links, as if `cd -P' had been executed. -
If
$CDPATHis set, thecdbuiltin will not implicitly append the current directory to it. This means thatcdwill 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 tocdexists in the current directory. - 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.
-
A non-interactive shell exits with an error status if the iteration
variable in a
forstatement or the selection variable in aselectstatement is a readonly variable. - Process substitution is not available.
- Assignment statements preceding POSIX.2 special builtins persist in the shell environment after the builtin completes.
-
The
exportandreadonlybuiltin commands display their output in the format required by POSIX.2.
There is other POSIX.2 behavior that Bash does not implement. Specifically:
- Assignment statements affect the execution environment of all builtins, not just special ones.
Go to the first, previous, next, last section, table of contents.