MAN page from Other bash-2.05b-15sls.i586.rpm
BASH
Section: User Commands (1)
Updated: 2002 July 15
Index NAME
bash - GNU Bourne-Again SHell
SYNOPSIS
bash[options][file]
COPYRIGHT
Bash is Copyright (C) 1989-2002 by the Free Software Foundation, Inc.
DESCRIPTION
Bashis an
sh-compatible command language interpreter thatexecutes commands read from the standard input or from a file.
Bashalso incorporates useful features from the
Korn and
Cshells (
ksh and
csh).
Bashis intended to be a conformant implementation of the IEEEPOSIX Shell and Tools specification (IEEE Working Group 1003.2).
OPTIONS
In addition to the single-character shell options documented in thedescription of the
set builtin command,
bashinterprets the following options when it is invoked:
- -c string
- If the-coption is present, then commands are read fromstring.If there are arguments after thestring,they are assigned to the positional parameters, starting with$0.
- -i
- If the-ioption is present, the shell isinteractive.
- -l
- Makebashact as if it had been invoked as a login shell (seeINVOCATIONbelow).
- -r
- If the-roption is present, the shell becomesrestricted(seeRESTRICTED SHELLbelow).
- -s
- If the-soption is present, or if no arguments remain after optionprocessing, then commands are read from the standard input.This option allows the positional parameters to be setwhen invoking an interactive shell.
- -D
- A list of all double-quoted strings preceded by $is printed on the standard ouput.These are the strings thatare subject to language translation when the current localeis not C or POSIX.This implies the -n option; no commands will be executed.
- [-+]O [shopt_option]
- shopt_option is one of the shell options accepted by theshopt builtin (seeSHELL BUILTIN COMMANDSbelow).If shopt_option is present, -O sets the value of that option;+O unsets it.If shopt_option is not supplied, the names and values of the shelloptions accepted by shopt are printed on the standard output.If the invocation option is +O, the output is displayed in a formatthat may be reused as input.
- --
- A--signals the end of options and disables further option processing.Any arguments after the--are treated as filenames and arguments. An argument of-is equivalent to --.
Bashalso interprets a number of multi-character options.These options must appear on the command line before thesingle-character options 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 successfully.
- --init-file file
- --rcfile file
- Execute commands fromfileinstead of the standard personal initialization file~/.bashrcif the shell is interactive (seeINVOCATIONbelow).
- --login
- Equivalent to -l.
- --noediting
- Do not use the GNUreadlinelibrary to read command lines when the shell is interactive.
- --noprofile
- Do not read either the system-wide startup file/etc/profileor any of the personal initialization files~/.bash_profile,~/.bash_login,or~/.profile.By default,bashreads these files when it is invoked as a login shell (seeINVOCATIONbelow).
- --norc
- Do not read and execute the personal initialization file~/.bashrcif the shell is interactive.This option is on by default if the shell is invoked assh.
- --posix
- Change the behavior of bash where the default operation differsfrom the POSIX 1003.2 standard to match the standard (posix mode).
- --restricted
- The shell becomes restricted (seeRESTRICTED SHELLbelow).
- --verbose
- Equivalent to -v.
- --version
- Show version information for this instance ofbashon the standard output and exit successfully.
ARGUMENTS
If arguments remain after option processing, and neither the
-cnor the
-soption has been supplied, the first argument is assumed tobe the name of a file containing shell commands.If
bashis invoked in this fashion,
$0is set to the name of the file, and the positional parametersare set to the remaining arguments.
Bashreads and executes commands from this file, then exits.
Bash's exit status is the exit status of the last commandexecuted in the script.If no commands are executed, the exit status is 0.An attempt is first made to open the file in the current directory, and,if no file is found, then the shell searches the directories in
PATHfor the script.
INVOCATION
A
login shell is one whose first character of argument zero is a
-,or one started with the
--loginoption.
An interactive shell is one started without non-option argumentsand without the-coptionwhose standard input and output areboth connected to terminals (as determined byisatty(3)),or one started with the-ioption.PS1is set and$-includesiifbashis interactive,allowing a shell script or a startup file to test this state.
The following paragraphs describe howbashexecutes its startup files.If any of the files exist but cannot be read,bashreports an error.Tildes are expanded in file names as described below underTilde Expansionin theEXPANSIONsection.
Whenbashis invoked as an interactive login shell, or as a non-interactive shellwith the --login option, it first reads andexecutes commands from the file /etc/profile, if thatfile exists.After reading that file, it looks for ~/.bash_profile,~/.bash_login, and ~/.profile, in that order, and readsand executes commands from the first one that exists and is readable.The--noprofileoption may be used when the shell is started to inhibit this behavior.
When a login shell exits,bashreads and executes commands from the file ~/.bash_logout, if itexists.
When an interactive shell that is not a login shell is started,bashreads and executes commands from ~/.bashrc, if that file exists.This may be inhibited by using the--norcoption.The --rcfile file option will forcebashto read and execute commands from file instead of ~/.bashrc.
Whenbashis started non-interactively, to run a shell script, for example, itlooks for the variableBASH_ENVin the environment, expands its value if it appears there, and uses theexpanded value as the name of a file to read and execute.Bashbehaves as if the following command were executed:
- if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
but the value of thePATHvariable is not used to search for the file name.
Ifbashis invoked with the namesh,it tries to mimic the startup behavior of historical versions ofshas closely as possible,while conforming to the POSIX standard as well.When invoked as an interactive login shell, or a non-interactiveshell with the --login option, it first attempts toread and execute commands from/etc/profileand~/.profile,in that order.The--noprofileoption may be used to inhibit this behavior.When invoked as an interactive shell with the namesh,bashlooks for the variableENV,expands its value if it is defined, and uses theexpanded value as the name of a file to read and execute.Since a shell invoked asshdoes not attempt to read and execute commands from any other startupfiles, the--rcfileoption has no effect.A non-interactive shell invoked with the nameshdoes not attempt to read any other startup files. When invoked assh,bashentersposixmode after the startup files are read.
Whenbashis started inposixmode, as with the--posixcommand line option, it follows the POSIX standard for startup files.In this mode, interactive shells expand theENVvariable and commands are read and executed from the filewhose name is the expanded value.No other startup files are read.
Bashattempts to determine when it is being run by the remote shelldaemon, usually rshd.Ifbashdetermines it is being run by rshd, it reads and executescommands from ~/.bashrc, if that file exists and is readable.It will not do this if invoked as sh.The--norcoption may be used to inhibit this behavior, and the--rcfileoption may be used to force another file to be read, butrshd does not generally invoke the shell with those optionsor allow them to be specified.
If the shell is started with the effective user (group) id not equal to thereal user (group) id, and the -p option is not supplied, no startupfiles are read, shell functions are not inherited from the environment, theSHELLOPTSvariable, if it appears in the environment, is ignored,and the effective user id is set to the real user id.If the -p option is supplied at invocation, the startup behavior isthe same, but the effective user id is not reset.
DEFINITIONS
The following definitions are used throughout the rest of thisdocument.
- blank
- A space or tab.
- word
- A sequence of characters considered as a single unit by the shell.Also known as atoken.
- name
- A wordconsisting only of alphanumeric characters and underscores, andbeginning with an alphabetic character or an underscore. Alsoreferred to as anidentifier.
- metacharacter
- A character that, when unquoted, separates words. One of the following:
| & ; ( ) < > space tab
- control operator
- A token that performs a control function. It is one of the followingsymbols:
|| & && ; ;; ( ) | <newline>
RESERVED WORDS
Reserved words are words that have a special meaning to the shell.The following words are recognized as reserved when unquoted and eitherthe first word of a simple command (see
SHELL GRAMMARbelow) or the third word of a
case or
forcommand:
! case do done elif else esac fi for function if in select then until while { } time [[ ]]
SHELL GRAMMAR
Simple Commands
A simple command is a sequence of optional variable assignmentsfollowed by blank-separated words and redirections, andterminated by a control operator. The first wordspecifies the command to be executed, and is passed as argument zero.The remaining words are passed as arguments to the invoked command.
The return value of a simple command is its exit status, or128+n if the command is terminated by signaln.
Pipelines
A pipeline is a sequence of one or more commands separated bythe character|.The format for a pipeline is:
[time [-p]] [ ! ] command [ | command2 ... ]
The standard output ofcommandis connected via a pipe to the standard input ofcommand2.This connection is performed before any redirections specified by thecommand (seeREDIRECTIONbelow).
If the reserved word!precedes a pipeline, the exit status of thatpipeline is the logical NOT of the exit status of the last command.Otherwise, the status of the pipeline is the exit status of the lastcommand.The shell waits for all commands in the pipeline toterminate before returning a value.
If thetimereserved word precedes a pipeline, the elapsed as well as user andsystem time consumed by its execution are reported when the pipelineterminates.The -p option changes the output format to that specified by POSIX.TheTIMEFORMATvariable may be set to a format string that specifies how the timinginformation should be displayed; see the description ofTIMEFORMATunderShell Variablesbelow.
Each command in a pipeline is executed as a separate process (i.e., in asubshell).
Lists
A list is a sequence of one or more pipelines separated by oneof the operators;,&,&&,or||,and optionally terminated by one of;,&,or<newline>.
Of these list operators,&&and||have equal precedence, followed by;and&,which have equal precedence.
A sequence of one or more newlines may appear in a list insteadof a semicolon to delimit commands.
If a command is terminated by the control operator&,the shell executes the command in the backgroundin a subshell. The shell does not wait for the command tofinish, and the return status is 0. Commands separated by a;are executed sequentially; the shell waits for eachcommand to terminate in turn. The return status is theexit status of the last command executed.
The control operators&&and||denote AND lists and OR lists, respectively.An AND list has the form
command1 && command2
command2is executed if, and only if,command1returns an exit status of zero.
An OR list has the form
command1 || command2
command2is executed if and only ifcommand1returns a non-zero exit status. The return status ofAND and OR lists is the exit status of the last commandexecuted in the list.
Compound Commands
A compound command is one of the following:
- (list)
- list is executed in a subshell. Variable assignments and builtincommands that affect the shell's environment do not remain in effectafter the command completes. The return status is the exit status oflist.
- { list; }
- list is simply executed in the current shell environment.list must be terminated with a newline or semicolon.This is known as a group command.The return status is the exit status oflist.Note that unlike the metacharacters ( and ), { and} are reserved words and must occur where a reservedword is permitted to be recognized. Since they do not cause a wordbreak, they must be separated from list by whitespace.
- ((expression))
- The expression is evaluated according to the rules describedbelow underARITHMETICEVALUATION.If the value of the expression is non-zero, the return status is 0;otherwise the return status is 1. This is exactly equivalent tolet "expression".
- [[ expression ]]
- Return a status of 0 or 1 depending on the evaluation ofthe conditional expression expression.Expressions are composed of the primaries described below underCONDITIONALEXPRESSIONS.Word splitting and pathname expansion are not performed on the wordsbetween the [[ and ]]; tilde expansion, parameter andvariable expansion, arithmetic expansion, command substitution, processsubstitution, and quote removal are performed.
When the == and != operators are used, the string to theright of the operator is considered a pattern and matched accordingto the rules described below under Pattern Matching.The return value is 0 if the string matches or does not matchthe pattern, respectively, and 1 otherwise.Any part of the pattern may be quoted to force it to be matched as astring.
Expressions may be combined using the following operators, listedin decreasing order of precedence:
- ( expression )
- Returns the value of expression.This may be used to override the normal precedence of operators.
- ! expression
- True ifexpressionis false.
- expression1 && expression2
- True if bothexpression1andexpression2are true.
- expression1 || expression2True if eitherexpression1orexpression2is true.
The && and||operators do not evaluate expression2 if the value ofexpression1 is sufficient to determine the return value ofthe entire conditional expression.
- for name [ in word ] ; do list ; done
- The list of words following in is expanded, generating a listof items.The variable name is set to each element of this listin turn, and list is executed each time.If the in word is omitted, the for command executeslist once for each positional parameter that is set (seePARAMETERSbelow).The return status is the exit status of the last command that executes.If the expansion of the items following in results in an emptylist, no commands are executed, and the return status is 0.
- for (( expr1 ; expr2 ; expr3 )) ; do list ; done
- First, the arithmetic expression expr1 is evaluated accordingto the rules described below underARITHMETICEVALUATION.The arithmetic expression expr2 is then evaluated repeatedlyuntil it evaluates to zero.Each time expr2 evaluates to a non-zero value, list isexecuted and the arithmetic expression expr3 is evaluated.If any expression is omitted, it behaves as if it evaluates to 1.The return value is the exit status of the last command in listthat is executed, or false if any of the expressions is invalid.
- select name [ in word ] ; do list ; done
- The list of words following in is expanded, generating a listof items. The set of expanded words is printed on the standarderror, each preceded by a number. If the inword is omitted, the positional parameters are printed (seePARAMETERSbelow). ThePS3prompt is then displayed and a line read from the standard input.If the line consists of a number corresponding to one ofthe displayed words, then the value ofnameis set to that word. If the line is empty, the words and promptare displayed again. If EOF is read, the command completes. Anyother value read causesnameto be set to null. The line read is saved in the variableREPLY.Thelistis executed after each selection until abreakcommand is executed.The exit status ofselectis the exit status of the last command executed inlist,or zero if no commands were executed.
- case word in [ [(] pattern [ | pattern ]
- A case command first expands word, and tries to matchit against each pattern in turn, using the same matching rulesas for pathname expansion (seePathname Expansionbelow). When a match is found, thecorresponding list is executed. After the first match, nosubsequent matches are attempted. The exit status is zero if nopattern matches. Otherwise, it is the exit status of thelast command executed in list.
- if list; then list; [ elif list; then list; ] ... [ else list; ] fi
- Theif listis executed. If its exit status is zero, thethen list is executed. Otherwise, each eliflist is executed in turn, and if its exit status is zero,the corresponding then list is executed and thecommand completes. Otherwise, the else list isexecuted, if present. The exit status is the exit status of thelast command executed, or zero if no condition tested true.
- while list; do list; done
- until list; do list; done
- The while command continuously executes the dolist as long as the last command in list returnsan exit status of zero. The until command is identicalto the while command, except that the test is negated;thedolistis executed as long as the last command inlistreturns a non-zero exit status.The exit status of the while and until commandsis the exit statusof the last do list command executed, or zero ifnone was executed.
- [ function ] name () { list; }
- This defines a function named name. The body of thefunction is thelistof commands between { and }. This listis executed whenever name is specified as thename of a simple command. The exit status of a function isthe exit status of the last command executed in the body. (SeeFUNCTIONSbelow.)
COMMENTS
In a non-interactive shell, or an interactive shell in which the
interactive_commentsoption to the
shoptbuiltin is enabled (see
SHELL BUILTIN COMMANDSbelow), a word beginning with
#causes that word and all remaining characters on that line tobe ignored. An interactive shell without the
interactive_commentsoption enabled does not allow comments. The
interactive_commentsoption is on by default in interactive shells.
QUOTING
Quoting is used to remove the special meaning of certaincharacters or words to the shell. Quoting can be used to disable special treatment for special characters, to preventreserved words from being recognized as such, and to preventparameter expansion.
Each of the metacharacters listed above underDEFINITIONShas special meaning to the shell and must be quoted if it is torepresent itself.
When the command history expansion facilities are being used, thehistory expansion character, usually !, must be quotedto prevent history expansion.
There are three quoting mechanisms: theescape character,single quotes, and double quotes.
A non-quoted backslash (\) is theescape character.It preserves the literal value of the next character that follows,with the exception of <newline>. If a \<newline> pairappears, and the backslash is not itself quoted, the \<newline>is treated as a line continuation (that is, it is removed from theinput stream and effectively ignored).
Enclosing characters in single quotes preserves the literal valueof each character within the quotes. A single quote may not occurbetween single quotes, even when preceded by a backslash.
Enclosing characters in double quotes preserves the literal valueof all characters within the quotes, with the exception of$,`,and\.The characters$and`retain their special meaning within double quotes. The backslashretains its special meaning only when followed by one of the followingcharacters:$,`,",\,or<newline>.A double quote may be quoted within double quotes by preceding it witha backslash.
The special parameters*and@have special meaning when in doublequotes (seePARAMETERSbelow).
Words of the form $'string' are treated specially. Theword expands to string, with backslash-escaped characters replacedas specifed by the ANSI C standard. Backslash escape sequences, ifpresent, are decoded as follows:
- \a
- alert (bell)
- \b
- backspace
- \e
- an escape character
- \f
- form feed
- \n
- new line
- \r
- carriage return
- \t
- horizontal tab
- \v
- vertical tab
- \\
- backslash
- \'
- single quote
- \nnn
- the eight-bit character whose value is the octal value nnn(one to three digits)
- \xHH
- the eight-bit character whose value is the hexadecimal value HH(one or two hex digits)
- \cx
- a control-x character
The expanded result is single-quoted, as if the dollar sign hadnot been present.
A double-quoted string preceded by a dollar sign ($) will causethe string to be translated according to the current locale.If the current locale is C or POSIX, the dollar signis ignored.If the string is translated and replaced, the replacement isdouble-quoted.
PARAMETERS
A
parameteris an entity that stores values.It can be a
name,a number, or one of the special characters listed below under
Special Parameters.For the shell's purposes, a
variableis a parameter denoted by a
name.A variable has a
value and zero or more
attributes.Attributes are assigned using the
declarebuiltin command (see
declarebelow in
SHELLBUILTINCOMMANDS).A parameter is set if it has been assigned a value. The null string isa valid value. Once a variable is set, it may be unset only by usingtheunsetbuiltin command (seeSHELL BUILTIN COMMANDSbelow).
Avariablemay be assigned to by a statement of the form
name=[value]
Ifvalueis not given, the variable is assigned the null string. Allvaluesundergo tilde expansion, parameter and variable expansion,command substitution, arithmetic expansion, and quoteremoval (seeEXPANSIONbelow). If the variable has itsintegerattribute set, thenvalueis subject to arithmetic expansion even if the $((...)) expansion isnot used (seeArithmetic Expansionbelow).Word splitting is not performed, with the exceptionof "$@" as explained below underSpecial Parameters.Pathname expansion is not performed.Assignment statements may also appear as arguments to thedeclare,typeset,export,readonly,andlocalbuiltin commands.
Positional Parameters
Apositional parameteris a parameter denoted by one or moredigits, other than the single digit 0. Positional parameters areassigned from the shell's arguments when it is invoked,and may be reassigned using thesetbuiltin command. Positional parameters may not be assigned towith assignment statements. The positional parameters aretemporarily replaced when a shell function is executed (seeFUNCTIONSbelow).
When a positional parameter consisting of more than a singledigit is expanded, it must be enclosed in braces (seeEXPANSIONbelow).
Special Parameters
The shell treats several parameters specially. These parameters mayonly be referenced; assignment to them is not allowed.
- *
- Expands to the positional parameters, starting from one. When theexpansion occurs within double quotes, it expands to a single wordwith the value of each parameter separated by the first characterof the IFSspecial variable. That is, "$*" is equivalentto "$1c$2c...", wherecis the first character of the value of theIFSvariable. IfIFSis unset, the parameters are separated by spaces.IfIFSis null, the parameters are joined without intervening separators.
- @
- Expands to the positional parameters, starting from one. When theexpansion occurs within double quotes, each parameter expands to aseparate word. That is, "$@" is equivalent to"$1" "$2" ...When there are no positional parameters, "$@" and $@expand to nothing (i.e., they are removed).
- #
- Expands to the number of positional parameters in decimal.
- ?
- Expands to the status of the most recently executed foregroundpipeline.
- -
- Expands to the current option flags as specified upon invocation, by thesetbuiltin command, or those set by the shell itself(such as the-ioption).
- $
- Expands to the process ID of the shell. In a () subshell, itexpands to the process ID of the current shell, not thesubshell.
- !
- Expands to the process ID of the most recently executed background(asynchronous) command.
- 0
- Expands to the name of the shell or shell script. This is set atshell initialization. Ifbashis invoked with a file of commands,$0is set to the name of that file. Ifbashis started with the-coption, then$0is set to the first argument after the string to beexecuted, if one is present. Otherwise, it is setto the file name used to invokebash,as given by argument zero.
- _
- At shell startup, set to the absolute file name of the shell or shellscript being executed as passed in the argument list.Subsequently, expands to the last argument to the previous command,after expansion.Also set to the full file name of each command executed and placed inthe environment exported to that command.When checking mail, this parameter holds the name of the mail filecurrently being checked.
Shell Variables
The following variables are set by the shell:
- BASH
- Expands to the full file name used to invoke this instance ofbash.
- BASH_VERSINFO
- A readonly array variable whose members hold version information forthis instance ofbash.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.
- BASH_VERSION
- Expands to a string describing the version of this instance ofbash.
- COMP_CWORD
- An index into ${COMP_WORDS} of the word containing the currentcursor position.This variable is available only in shell functions invoked by theprogrammable completion facilities (see Programmable Completionbelow).
- COMP_LINE
- The current command line.This variable is available only in shell functions and externalcommands invoked by theprogrammable completion facilities (see Programmable Completionbelow).
- COMP_POINT
- The index of the current cursor position relative to the beginning ofthe current command.If the current cursor position is at the end of the current command,the value of this variable is equal to ${#COMP_LINE}.This variable is available only in shell functions and externalcommands invoked by theprogrammable completion facilities (see Programmable Completionbelow).
- COMP_WORDS
- An array variable (see Arrays below) consisting of the individualwords in the current command line.This variable is available only in shell functions invoked by theprogrammable completion facilities (see Programmable Completionbelow).
- DIRSTACK
- An array variable (seeArraysbelow) containing the current contents of the directory stack.Directories appear in the stack in the order they are displayed by thedirsbuiltin.Assigning to members of this array variable may be used to modifydirectories 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 issubsequently reset.
- EUID
- Expands to the effective user ID of the current user, initialized atshell startup. This variable is readonly.
- FUNCNAME
- The name of any currently-executing shell function.This variable exists only when a shell function is executing.Assignments toFUNCNAMEhave no effect and return an error status.IfFUNCNAMEis unset, it loses its special properties, even if it issubsequently reset.
- GROUPS
- An array variable containing the list of groups of which the currentuser is a member.Assignments to GROUPShave no effect and return an error status.IfGROUPSis unset, it loses its special properties, even if it issubsequently reset.
- HISTCMD
- The history number, or index in the history list, of the currentcommand.IfHISTCMDis unset, it loses its special properties, even if it issubsequently reset.
- HOSTNAME
- Automatically set to the name of the current host.
- HOSTTYPE
- Automatically set to a string that uniquelydescribes the type of machine on whichbashis executing.The default is system-dependent.
- LINENO
- Each time this parameter is referenced, the shell substitutesa decimal number representing the current sequential line number(starting with 1) within a script or function. When not in ascript or function, the value substituted is not guaranteed tobe meaningful.IfLINENOis unset, it loses its special properties, even if it issubsequently reset.
- MACHTYPE
- Automatically set to a string that fully describes the systemtype on whichbashis executing, in the standard GNU cpu-company-system format.The default is system-dependent.
- OLDPWD
- The previous working directory as set by thecdcommand.
- OPTARG
- The value of the last option argument processed by thegetoptsbuiltin command (seeSHELL BUILTIN COMMANDSbelow).
- OPTIND
- The index of the next argument to be processed by thegetoptsbuiltin command (seeSHELL BUILTIN COMMANDSbelow).
- OSTYPE
- Automatically set to a string thatdescribes the operating system on whichbashis executing.The default is system-dependent.
- PIPESTATUS
- An array variable (seeArraysbelow) containing a list of exit status values from the processesin the most-recently-executed foreground pipeline (which maycontain only a single command).
- PPID
- The process ID of the shell's parent. This variable is readonly.
- PWD
- The current working directory as set by thecdcommand.
- RANDOM
- Each time this parameter is referenced, a random integer between0 and 32767 isgenerated. The sequence of random numbers may be initialized by assigninga value toRANDOM.IfRANDOMis unset, it loses its special properties, even if it issubsequently reset.
- REPLY
- Set to the line of input read by thereadbuiltin command when no arguments are supplied.
- SECONDS
- Each time this parameter isreferenced, the number of seconds since shell invocation is returned. If avalue is assigned to SECONDS,the value returned upon subsequentreferences isthe number of seconds since the assignment plus the value assigned.IfSECONDSis unset, it loses its special properties, even if it issubsequently reset.
- SHELLOPTS
- A colon-separated list of enabled shell options. Each word inthe list is a valid argument for the-ooption to thesetbuiltin command (seeSHELL BUILTIN COMMANDSbelow). The options appearing inSHELLOPTSare those reported asonby set -o.If this variable is in the environment whenbashstarts up, each shell option in the list will be enabled beforereading any startup files.This variable is read-only.
- SHLVL
- Incremented by one each time an instance ofbashis started.
- UID
- Expands to the user ID of the current user, initialized at shell startup.This variable is readonly.
The following variables are used by the shell. In some cases,bashassigns a default value to a variable; these cases are notedbelow.
- BASH_ENV
- If this parameter is set when bash is executing a shell script,its value is interpreted as a filename containing commands toinitialize the shell, as in~/.bashrc.The value ofBASH_ENVis subjected to parameter expansion, command substitution, and arithmeticexpansion before being interpreted as a file name.PATHis not used to search for the resultant file name.
- CDPATH
- The search path for thecdcommand.This is a colon-separated list of directories in which the shell looksfor destination directories specified by thecdcommand.A sample value is".:~:/usr".
- COLUMNS
- Used by the select builtin command to determine the terminal widthwhen printing selection lists. Automatically set upon receipt of a SIGWINCH.
- COMPREPLY
- An array variable from which bash reads the possible completionsgenerated by a shell function invoked by the programmable completionfacility (see Programmable Completion below).
- FCEDIT
- The default editor for thefcbuiltin command.
- FIGNORE
- A colon-separated list of suffixes to ignore when performingfilename completion (seeREADLINEbelow).A filename whose suffix matches one of the entries in FIGNOREis excluded from the list of matched filenames.A sample value is".o:~".
- GLOBIGNORE
- A colon-separated list of patterns defining the set of filenames tobe ignored by pathname expansion.If a filename matched by a pathname expansion pattern also matches oneof the patterns inGLOBIGNORE,it is removed from the list of matches.
- HISTCONTROL
- If set to a value ofignorespace,lines which begin with aspacecharacter are not entered on the history list.If set to a value ofignoredups,lines matching the last history line are not entered.A value ofignorebothcombines the two options.If unset, or if set to any other value than those above,all lines readby the parser are saved on the history list, subject to the valueofHISTIGNORE.This variable's function is superseded byHISTIGNORE.The second and subsequent lines of a multi-line compound command arenot tested, and are added to the history regardless of the value ofHISTCONTROL.
- HISTFILE
- The name of the file in which command history is saved (seeHISTORYbelow). The default value is ~/.bash_history. If unset, thecommand history is not saved when an interactive shell exits.
- HISTFILESIZE
- The maximum number of lines contained in the history file. When thisvariable is assigned a value, the history file is truncated, ifnecessary, to contain no more than that number of lines. The defaultvalue is 500. The history file is also truncated to this size afterwriting it when an interactive shell exits.
- HISTIGNORE
- A colon-separated list of patterns used to decide which command linesshould be saved on the history list. Each pattern is anchored at thebeginning of the line and must match the complete line (no implicit`*' is appended). Each pattern is tested against the lineafter the checks specified byHISTCONTROLare applied.In addition to the normal shell pattern matching characters, `&'matches the previous history line. `&' may be escaped using abackslash; the backslash is removed before attempting a match.The second and subsequent lines of a multi-line compound command arenot tested, and are added to the history regardless of the value ofHISTIGNORE.
- HISTSIZE
- The number of commands to remember in the command history (seeHISTORYbelow). The default value is 500.
- HOME
- The home directory of the current user; the default argument for thecd builtin command.The value of this variable is also used when performing tilde expansion.
- HOSTFILE
- Contains the name of a file in the same format as/etc/hoststhat should be read when the shell needs to complete ahostname.The list of possible hostname completions may be changed while theshell is running;the next time hostname completion is attempted after thevalue is changed,bashadds the contents of the new file to the existing list.IfHOSTFILEis set, but has no value, bash attempts to read/etc/hoststo obtain the list of possible hostname completions.WhenHOSTFILEis unset, the hostname list is cleared.
- IFS
- TheInternal Field Separatorthat is usedfor word splitting after expansion and tosplit lines into words with thereadbuiltin command. The default value is``<space><tab><newline>''.
- IGNOREEOF
- Controls theaction of an interactive shell on receipt of anEOFcharacter as the sole input. If set, the value is the number ofconsecutiveEOFcharacters which must betyped as the first characters on an input line beforebashexits. If the variable exists but does not have a numeric value, orhas no value, the default value is 10. If it does not exist,EOFsignifies the end of input to the shell.
- INPUTRC
- The filename for thereadlinestartup file, overriding the default of~/.inputrc(seeREADLINEbelow).
- LANG
- Used to determine the locale category for any category not specificallyselected with a variable starting with LC_.
- LC_ALL
- This variable overrides the value of LANG and any otherLC_ variable specifying a locale category.
- LC_COLLATE
- This variable determines the collation order used when sorting theresults of pathname expansion, and determines the behavior of rangeexpressions, equivalence classes, and collating sequences withinpathname expansion and pattern matching.
- LC_CTYPE
- This variable determines the interpretation of characters and thebehavior of character classes within pathname expansion and patternmatching.
- LC_MESSAGES
- This variable determines the locale used to translate double-quotedstrings preceded by a $.
- LC_NUMERIC
- This variable determines the locale category used for number formatting.
- LINES
- Used by the select builtin command to determine the column lengthfor printing selection lists. Automatically set upon receipt of a SIGWINCH.
- MAIL
- If this parameter is set to a file name and theMAILPATHvariable is not set,bashinforms the user of the arrival of mail in the specified file.
- MAILCHECK
- Specifies howoften (in seconds)bashchecks for mail. The default is 60 seconds. When it is time to checkfor mail, the shell does so before displaying the primary prompt.If this variable is unset, or set to a value that is not a numbergreater than or equal to zero, the shell disables mail checking.
- MAILPATH
- A colon-separated list of file names to be checked for mail. The message to be printed when mail arrives in a particular filemay be specified by separating the file name from the message with a `?'.When used in the text of the message, $_ expands to the name ofthe current mailfile. Example:
MAILPATH='/var/mail/bfox?"You have mail":~/shell-mail?"$_ has mail!"'
Bashsupplies a default value for this variable, but the location of the usermail files that it uses is system dependent (e.g., /var/mail/$USER).
- OPTERR
- If set to the value 1,bashdisplays error messages generated by thegetoptsbuiltin command (seeSHELL BUILTIN COMMANDSbelow).OPTERRis initialized to 1 each time the shell is invoked or a shellscript is executed.
- PATH
- The search path for commands. Itis a colon-separated list of directories in whichthe shell looks for commands (seeCOMMAND EXECUTIONbelow). The default path is system-dependent,and is set by the administrator who installsbash.A common value is``/usr/gnu/bin:/usr/local/bin:/usr/ucb:/bin:/usr/bin:.''.
- POSIXLY_CORRECT
- If this variable is in the environment when bash starts, the shellenters posix mode before reading the startup files, as if the--posixinvocation option had been supplied. If it is set while the shell isrunning, bash enables posix mode, as if the commandset -o posixhad been executed.
- PROMPT_COMMAND
- If set, the value is executed as a command prior to issuing each primaryprompt.
- PS1
- The value of this parameter is expanded (seePROMPTINGbelow) and used as the primary prompt string. The default value is``\s-\v\$ ''.
- PS2
- The value of this parameter is expanded as withPS1and used as the secondary prompt string. The default is``> ''.
- PS3
- The value of this parameter is used as the prompt for theselectcommand (seeSHELL GRAMMARabove).
- PS4
- The value of this parameter is expanded as withPS1and the value is printed before each commandbashdisplays during an execution trace. The first character ofPS4is replicated multiple times, as necessary, to indicate multiplelevels of indirection. The default is ``+ ''.
- TIMEFORMAT
- The value of this parameter is used as a format string specifyinghow the timing information for pipelines prefixed with thetimereserved word should be displayed.The % character introduces an escape sequence that isexpanded to a time value or other information.The escape sequences and their meanings are as follows; thebraces 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, includingminutes, of the form MMmSS.FFs.The value of p determines whether or not the fraction isincluded.
- If this variable is not set, bash acts as if it had thevalue $'\nreal\t%3lR\nuser\t%3lU\nsys %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, TMOUT is treated as thedefault timeout for the read builtin.The select command terminates if input does not arriveafter TMOUT seconds when input is coming from a terminal.In an interactive shell, the value is interpreted as thenumber of seconds to wait for input after issuing the primary prompt.Bashterminates after waiting for that number of seconds if input doesnot arrive.
- auto_resume
- This variable controls how the shell interacts with the user andjob control. If this variable is set, single word simplecommands without redirections are treated as candidates for resumptionof an existing stopped job. There is no ambiguity allowed; if there ismore than one job beginning with the string typed, the job most recentlyaccessed is selected. Thenameof a stopped job, in this context, is the command line used tostart it.If set to the valueexact,the string supplied must match the name of a stopped job exactly;if set tosubstring,the string supplied needs to match a substring of the name of astopped job. Thesubstringvalue provides functionality analogous to the%?job identifier (seeJOB CONTROLbelow). If set to any other value, the supplied string mustbe a prefix of a stopped job's name; this provides functionalityanalogous to the%job identifier.
- histchars
- The two or three characters which control history expansionand tokenization (seeHISTORY EXPANSIONbelow). The first character is the history expansion character,the character which signals the start of a historyexpansion, normally `!'.The second character is the quick substitutioncharacter, which is used as shorthand for re-running the previouscommand entered, substituting one string for another in the command.The default is `^'.The optional third character is the characterwhich indicates that the remainder of the line is a comment when foundas the first character of a word, normally `#'. The historycomment character causes history substitution to be skipped for theremaining words on the line. It does not necessarily cause the shellparser to treat the rest of the line as a comment.
Arrays
Bashprovides one-dimensional array variables. Any variable may be used asan array; the
declarebuiltin will explicitly declare an array. There is no maximumlimit on the size of an array, nor any requirement that membersbe indexed or assigned contiguously. Arrays are indexed usingintegers and are zero-based.
An array is created automatically if any variable is assigned to usingthe syntax name[subscript]=value. Thesubscriptis treated as an arithmetic expression that must evaluate to a numbergreater than or equal to zero. To explicitly declare an array, usedeclare -a name(seeSHELL BUILTIN COMMANDSbelow).declare -a name[subscript]is also accepted; the subscript is ignored. Attributes may bespecified for an array variable using thedeclareandreadonlybuiltins. Each attribute applies to all members of an array.
Arrays are assigned to using compound assignments of the formname=(value1 ... valuen), where eachvalue is of the form [subscript]=string. Onlystring is required. Ifthe optional brackets and subscript are supplied, that index is assigned to;otherwise the index of the element assigned is the last index assignedto by the statement plus one. Indexing starts at zero.This syntax is also accepted by thedeclarebuiltin. Individual array elements may be assigned to using thename[subscript]=value syntax introduced above.
Any element of an array may be referenced using${name[subscript]}. The braces are required to avoidconflicts with pathname expansion. Ifsubscript is @ or *, the word expands toall members of name. These subscripts differ only when theword appears within double quotes. If the word is double-quoted,${name[*]} expands to a singleword with the value of each array member separated by the firstcharacter of theIFSspecial variable, and ${name[@]} expands each element ofname to a separate word. When there are no array members,${name[@]} expands to nothing. This is analogous to the expansionof the special parameters * and @ (seeSpecial Parametersabove). ${#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 toreferencing element zero.
Theunsetbuiltin is used to destroy arrays. unset name[subscript]destroys the array element at index subscript.unset name, where name is an array, orunset name[subscript], wheresubscript is * or @, removes the entire array.
Thedeclare,local,andreadonlybuiltins each accept a-aoption to specify an array. Thereadbuiltin accepts a-aoption to assign a list of words read from the standard inputto an array. Thesetanddeclarebuiltins display array values in a way that allows them to bereused as assignments.
EXPANSION
Expansion is performed on the command line after it has been split intowords. There are seven kinds of expansion performed:
brace expansion,
tilde expansion,
parameter and variable expansion,
command substitution,
arithmetic expansion,
word splitting,and
pathname expansion.
The order of expansions is: brace expansion, tilde expansion,parameter, variable and arithmetic expansion andcommand substitution(done in a left-to-right fashion), word splitting, and pathnameexpansion.
On systems that can support it, there is an additional expansionavailable: process substitution.
Only brace expansion, word splitting, and pathname expansioncan change the number of words of the expansion; other expansionsexpand a single word to a single word.The only exceptions to this are the expansions of"$@" and "${name[@]}"as explained above (seePARAMETERS).
Brace Expansion
Brace expansionis a mechanism by which arbitrary stringsmay be generated. This mechanism is similar topathname expansion, but the filenames generatedneed not exist. Patterns to be brace expanded takethe form of an optionalpreamble,followed by a series of comma-separated stringsbetween a pair of braces, followed by an optionalpostscript.The preamble is prefixed to each string containedwithin the braces, and the postscript is then appendedto each resulting string, expanding left to right.
Brace expansions may be nested. The results of each expandedstring are not sorted; left to right order is preserved.For example, a{d,c,b}e expands into `ade ace abe'.
Brace expansion is performed before any other expansions,and any characters special to other expansions are preservedin the result. It is strictly textual.Bashdoes not apply any syntactic interpretation to the context of theexpansion or the text between the braces.
A correctly-formed brace expansion must contain unquoted openingand closing braces, and at least one unquoted comma.Any incorrectly formed brace expansion is left unchanged.A { or , may be quoted with a backslash to prevent itsbeing considered part of a brace expression.To avoid conflicts with parameter expansion, the string ${is not considered eligible for brace expansion.
This construct is typically used as shorthand when the commonprefix of the strings to be generated is longer than in theabove example:
mkdir /usr/local/src/bash/{old,new,dist,bugs}
or
- chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
Brace expansion introduces a slight incompatibility withhistorical versions ofsh.shdoes not treat opening or closing braces specially when theyappear as part of a word, and preserves them in the output.Bashremoves braces from words as a consequence of braceexpansion. For example, a word entered toshas file{1,2}appears identically in the output. The same word isoutput asfile1 file2after expansion bybash.If strict compatibility withshis desired, startbashwith the+B option or disable brace expansion with the+Boption to thesetcommand (seeSHELL BUILTIN COMMANDSbelow).
Tilde Expansion
If a word begins with an unquoted tilde character (`~'), all ofthe characters preceding the first unquoted slash (or all characters,if there is no unquoted slash) are considered a tilde-prefix.If none of the characters in the tilde-prefix are quoted, thecharacters in the tilde-prefix following the tilde are treated as apossible login name.If this login name is the null string, the tilde is replaced with thevalue of the shell parameterHOME.IfHOMEis unset, the home directory of the user executing the shell issubstituted instead.Otherwise, the tilde-prefix is replaced with the home directoryassociated with the specified login name.
If the tilde-prefix is a `~+', the value of the shell variablePWDreplaces the tilde-prefix.If the tilde-prefix is a `~-', the value of the shell variableOLDPWD,if it is set, is substituted.If the characters following the tilde in the tilde-prefix consistof a number N, optionally prefixedby a `+' or a `-', the tilde-prefix is replaced with the correspondingelement from the directory stack, as it would be displayed by thedirsbuiltin invoked with the tilde-prefix as an argument.If the characters following the tilde in the tilde-prefix consist of anumber without a leading `+' or `-', `+' is assumed.
If the login name is invalid, or the tilde expansion fails, the wordis unchanged.
Each variable assignment is checked for unquoted tilde-prefixes immediatelyfollowing a:or=.In these cases, tilde expansion is also performed.Consequently, one may use file names with tildes in assignments toPATH,MAILPATH,andCDPATH,and the shell assigns the expanded value.
Parameter Expansion
The `$' character introduces parameter expansion,command substitution, or arithmetic expansion. The parameter nameor symbol to be expanded may be enclosed in braces, whichare optional but serve to protect the variable to be expanded fromcharacters immediately following it which could beinterpreted as part of the name.
When braces are used, the matching ending brace is the first `}'not escaped by a backslash or within a quoted string, and not within anembedded arithmetic expansion, command substitution, or paramterexpansion.
- ${parameter}
- The value of parameter is substituted. The braces are requiredwhenparameteris a positional parameter with more than one digit,or whenparameteris followed by a character which is not to beinterpreted as part of its name.
If the first character of parameter is an exclamation point,a level of variable indirection is introduced.Bash uses the value of the variable formed from the rest ofparameter as the name of the variable; this variable is thenexpanded and that value is used in the rest of the substitution, ratherthan the value of parameter itself.This is known as indirect expansion.The exception to this is the expansion of ${!prefix*}described below.
In each of the cases below, word is subject to tilde expansion,parameter expansion, command substitution, and arithmetic expansion.When not performing substring expansion, bash tests for a parameterthat is unset or null; omitting the colon results in a test only for aparameter that is unset.
- ${parameter:-word}
- Use Default Values. Ifparameteris unset or null, the expansion ofwordis substituted. Otherwise, the value ofparameteris substituted.
- ${parameter:=word}
- Assign Default Values.Ifparameteris unset or null, the expansion ofwordis assigned toparameter.The value ofparameteris then substituted. Positional parameters and special parameters maynot be assigned to in this way.
- ${parameter:?word}
- Display Error if Null or Unset