SEARCH
NEW RPMS
DIRECTORIES
ABOUT
FAQ
VARIOUS
BLOG
DONATE


YUM REPOSITORY

 
 

MAN page from RedHat 6.X bash-1.14.7-23.6x.i386.rpm

BASH

Section: User Commands (1)
Updated: 1995 May 5
Index 

NAME

bash - GNU Bourne-Again SHell 

SYNOPSIS

bash[options][file] 

COPYRIGHT

Bash is Copyright (C) 1989, 1991 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 ultimately 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 flags when it is invoked:

-c string
If the -cflag 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-iflag is present, the shell isinteractive.
-s
If the-sflag 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.
-
A single-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 an argument of -.

Bashalso interprets a number of multi-character options. These options mustappear on the command line before the single-character options to berecognized.

-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.
-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,bashnormally reads these files when it is invoked as a login shell (seeINVOCATIONbelow).
-rcfile file
Execute commands fromfileinstead of the standard personal initialization file~/.bashrc,if the shell is interactive (seeINVOCATIONbelow).
-version
Show the version number of this instance ofbashwhen starting.
-quiet
Do not be verbose when starting up (do not show the shell version or anyother information). This is the default.
-login
Makebashact as if it had been invoked as a login shell.
-nobraceexpansion
Do not perform curly brace expansion (seeBrace Expansionbelow).
-nolineediting
Do not use the GNUreadlinelibrary to read command lines if interactive.
-posix
Change the behavior of bash where the default operation differsfrom the Posix 1003.2 standard to match the standard
 

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. Ifbashis 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'sexit status is the exit status of the last command executedin the script. 

DEFINITIONS

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 (seeSHELL GRAMMARbelow) or the third word of a case orforcommand:

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

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. The remaining words arepassed 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:

[ ! ] command [ | command2 ... ]

The standard output ofcommandis connected 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.

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 terminated by one of;,&,or<newline>.

Of these list operators,&&and||have equal precedence, followed by;and&,which have equal precedence.

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

command && command2

command2is executed if, and only if,commandreturns an exit status of zero.

An OR list has the form

command || command2

command2is executed if and only ifcommandreturns 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. This isknown as a group command. The return status is the exit status oflist.
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 inword is omitted, the for command executes list once for each positional parameter that is set (seePARAMETERSbelow).
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 the 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 abreakorreturncommand 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 nopatterns are 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-o interactive-commentsoption to the set builtin is enabled, a word beginning with#causes that word and all remaining characters on that line tobe ignored. An interactive shell without the-o interactive-commentsoption enabled does not allow comments. 

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 they are torepresent themselves. 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 quoted, the \<newline>is treated as a line continuation (that is, it is 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). 

PARAMETERS

Aparameteris an entity that stores values, somewhat like avariable in a conventional programming language. It can be aname,a number, or one of the special characters listed below underSpecial Parameters.For the shell's purposes, avariableis a parameter denoted by aname.

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, commandsubstitution, arithmetic expansion, and quote removal. Ifthe variable has its-iattribute set (seedeclarebelow inSHELLBUILTINCOMMANDS)thenvalueis subject to arithmetic expansion even if the $[...] syntax doesnot appear. Word splitting is not performed, with the exceptionof "$@" as explained below underSpecial Parameters.Pathname expansion is not performed. 

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 null or unset, the parameters are separated by spaces.
@
Expands to the positional parameters, starting from one. When theexpansion occurs within double quotes, each parameter expands as 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-iflag).
$
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 pathname used to invokebash,as given by argument zero.
_
Expands to the last argument to the previous command, after expansion.Also set to the full pathname of each command executed and placed inthe environment exported to that command.
 

Shell Variables

The following variables are set by the shell:

PPID
The process ID of the shell's parent.
PWD
The current working directory as set by thecdcommand.
OLDPWD
The previous working directory as set by thecdcommand.
REPLY
Set to the line of input read by thereadbuiltin command when no arguments are supplied.
UID
Expands to the user ID of the current user, initialized at shell startup.
EUID
Expands to the effective user ID of the current user, initialized atshell startup.
BASH
Expands to the full pathname used to invoke this instance ofbash.
BASH_VERSION
Expands to the version number of this instance ofbash.
SHLVL
Incremented by one each time an instance ofbashis started.
RANDOM
Each time this parameter is referenced, a random integer 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.
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.
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. When in a function, the value is notthe number of the source line that the command appearson (that information has been lost by the time the function isexecuted), but is an approximation of the number ofsimple commandsexecuted in the current function.IfLINENOis 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.
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).
HOSTTYPE
Automatically set to a string that uniquelydescribes the type of machine on whichbashis executing. The default is system-dependent.
OSTYPE
Automatically set to a string thatdescribes the operating system on whichbashis executing. The default is system-dependent.

The following variables are used by the shell. In some cases,bashassigns a default value to a variable; these cases are notedbelow.

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>''.
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:.''.
HOME
The home directory of the current user; the default argument for thecd builtin command.
CDPATH
The search path for thecdcommand. This is a colon-separatedlist of directories in which the shell looks for destination directoriesspecified by thecdcommand. A sample value is``.:~:/usr''.
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 ofENVis subjected to parameter expansion, command substitution, and arithmeticexpansion before being interpreted as a pathname.PATHis not used to search for the resultant pathname.
MAIL
If this parameter is set to a filename 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 prompting.If this variable is unset, the shell disables mail checking.
MAILPATH
A colon-separated list of pathnames to be checked for mail. The message to be printed may be specified by separating the pathname fromthe message with a `?'. $_ stands for the name of the current mailfile. Example:

MAILPATH='/usr/spool/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., /usr/spool/mail/$USER).

MAIL_WARNING
If set, and a file that bash is checking for mail has beenaccessed since the last time it was checked, the message ``The mail inmailfile has been read'' is printed.
PS1
The value of this parameter is expanded (seePROMPTINGbelow) and used as the primary prompt string. The default value is``bash\$ ''.
PS2
The value of this parameter is expandedand 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 expandedand 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 ``+ ''.
HISTSIZE
The number of commands to remember in the command history (seeHISTORYbelow). The default value is 500.
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.
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.
PROMPT_COMMAND
If set, the value is executed as a command prior to issuing each primaryprompt.
IGNOREEOF
Controls theaction of the shell on receipt of anEOFcharacter as the sole input. If set, the value is the number ofconsecutiveEOFcharacters typed 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. This is only in effect forinteractive shells.
TMOUT
If set to a value greater than zero, 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.
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 samplevalue is ``.o:~''.
INPUTRC
The filename for the readline startup file, overriding the defaultof~/.inputrc(seeREADLINEbelow).
notify
If set,bashreports terminated background jobs immediately, rather than waitinguntil before printing the next primary prompt (see also the-boption to thesetbuiltin command).
history_control
HISTCONTROL
If set to a value ofignorespace,lines which begin with aspacecharacter are not entered on the history list. If set toa 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.
command_oriented_history
If set,bashattempts to save all lines of a multiple-linecommand in the same history entry. This allowseasy re-editing of multi-line commands.
glob_dot_filenames
If set,bashincludes filenames beginning with a `.' in the results of pathnameexpansion.
allow_null_glob_expansion
If set,bashallows pathname patterns which match nofiles (seePathname Expansionbelow)to expand to a null string, rather than themselves.
histchars
The two or three characters which control history expansionand tokenization (seeHISTORY EXPANSIONbelow). The first character is thehistory expansion character,that is, the character which signals the start of a historyexpansion, normally `!'.The second character is thequick 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 signifies 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.
nolinks
If set, the shell does not follow symbolic links when executingcommands that change the current working directory. It uses thephysical directory structure instead. By default,bashfollows the logical chain of directories when performing commandswhich change the current directory, such as cd.See also the description of the -P option to the setbuiltin (SHELL BUILTIN COMMANDSbelow).
hostname_completion_file
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 file may be changed interactively; the nexttime hostname completion is attemptedbashadds the contents of the new file to the already existing database.
noclobber
If set,bashdoes not overwrite an existing file with the>,>&,and<>redirection operators. This variable may be overridden when creating output files by using the redirection operator>|instead of>(see also the -C option to thesetbuiltin command).
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 id (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 id.
no_exit_on_failed_exec
If this variable exists, a non-interactive shell will not exit ifit cannot execute the file specified in theexecbuiltin command. An interactive shell does not exit ifexecfails.
cdable_vars
If this is set, an argument to thecdbuiltin command thatis not a directory is assumed to be the name of a variable whosevalue is the directory to change to.
 

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,andpathname expansion.

The order of expansions is: brace expansion, tilde expansion,parameter, variable, command, and arithmetic substitution (donein 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 single exception to this is the expansion of``$@'' 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 optionalpostamble.The preamble is prepended to each string containedwithin the braces, and the postamble 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.

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 withtraditional versions ofsh,the Bourne shell.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-nobraceexpansionflag (seeOPTIONSabove)or disable brace expansion with the+o braceexpandoption to thesetcommand (seeSHELL BUILTIN COMMANDSbelow). 

Tilde Expansion

If a word begins with a tilde character (`~'), all of the characterspreceding the first slash (or all characters, if there is no slash)are treated as a possible login name. If this login nameis the null string, the tilde is replaced with the value of theparameterHOME.IfHOMEis unset, the home directory ofthe user executing the shell is substituted instead.

If a `+' follows the tilde, the value ofPWDreplaces the tilde and `+'. Ifa `-' follows, the value ofOLDPWDis substituted.If the value following the tilde is a valid login name,the tilde and login name are replaced with the home directoryassociated with that name. If the name is invalid, or the tildeexpansion fails, the word is unchanged.

Each variable assignment is checked for unquotedinstances of tildes following a:or=.In these cases, tilde substitution is also performed. Consequently, onemay use pathnames 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.

${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.

In each of the cases below, word is subject to tilde expansion,parameter expansion, command substitution, and arithmetic expansion.Bash tests for a parameter that is unset or null; omitting thecolon results in a test only for a parameter 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.Ifparameteris null or unset, the expansion of word (or a message to that effectifwordis not present) is written to the standard error and the shell, if itis not interactive, exits. Otherwise, the value of parameter issubstituted.
${parameter:+word}
Use Alternate Value.Ifparameteris null or unset, nothing is substituted, otherwise the expansion ofwordis substituted.
${#parameter}
The length in characters of the value of parameter is substituted.If parameter is*or @,the length substituted is the length of*expanded within double quotes.
${parameter#word}
${parameter##word}
The wordis expanded to produce a pattern just as in pathnameexpansion. If the pattern matches the beginning ofthe value ofparameter,then the expansion is the value ofparameterwith the shortest matching pattern deleted (the ``#''case) or the longestmatching pattern deleted (the ``##'' case).
${parameter%word}
${parameter%%word}
The word is expanded to produce a pattern just as inpathname expansion. If the pattern matches atrailing portion of the value ofparameter,then the expansion is the value ofparameterwith the shortest matching pattern deleted(the ``%'' case) or the longestmatching pattern deleted (the ``%%'' case).
 

Command Substitution

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

$(command)

or
`command`

Bashperforms the expansion by executing command andreplacing the command substitution with the standard output of thecommand, with any trailing newlines deleted.

When the old-style backquote form of substitution is used,backslash retains its literal meaning except when followed by$,`,or\.When using the $(command) form, all characters between theparentheses make up the command; none are treated specially.

Command substitutions may be nested. To nest when using the old form,escape the inner backquotes with backslashes.

If the substitution appears within double quotes, word splitting andpathname expansion are not performed on the results. 

Arithmetic Expansion

Arithmetic expansion allows the evaluation of an arithmetic expressionand the substitution of the result. There are two formats forarithmetic expansion:

$[expression]

$((expression))

Theexpressionis treated as if it were within double quotes, but a double quoteinside the braces or parenthesesis not treated specially. All tokens in theexpression undergo parameter expansion, command substitution,and quote removal. Arithmetic substitutions may be nested.

The evaluation is performed according to the rules listed below underARITHMETICEVALUATION.Ifexpressionis invalid,bashprints a message indicating failure and no substitution occurs. 

Process Substitution

Process substitution is supported on systems that support namedpipes (FIFOs) or the /dev/fd method of naming open files.It takes the form of<(list)or>(list).The process list is run with its input or output connected to aFIFO or some file in /dev/fd. The name of this file ispassed as an argument to the current command as the result of theexpansion. If the >(list) form is used, writing tothe file will provide input for list. If the<(list) form is used, the file passed as anargument should be read to obtain the output of list.

On systems that support it, process substitution is performedsimultaneously withparameter and variable expansion,command substitution,andarithmetic expansion. 

Word Splitting

The shell scans the results ofparameter expansion,command substitution,andarithmetic expansionthat did not occur within double quotes forword splitting.

The shell treats each character ofIFSas a delimiter, and splits the results of the otherexpansions into words on these characters. If thevalue ofIFSis exactly<space><tab><newline>,the default, thenany sequence ofIFScharacters serves to delimit words. IfIFShas a value other than the default, then sequences ofthe whitespace charactersspaceandtabare ignored at the beginning and end of theword, as long as the whitespace character is in thevalue ofIFS(anIFSwhitespace character).Any character inIFSthat is notIFSwhitespace, along with any adjacentIFSwhitespace characters, delimits a field.A sequence ofIFSwhitespace characters is also treated as a delimiter.If the value ofIFSis null, no word splitting occurs.IFScannot be unset.

Explicit null arguments ("" or '')are retained. Implicit null arguments, resulting from the expansionofparametersthat have no values, are removed.

Note that if no expansion occurs, no splittingis performed. 

Pathname Expansion

After word splitting,unless the-foption has been set,bashscans eachwordfor the characters*,?,and[.If one of these characters appears, then the word isregarded as apattern,and replaced with an alphabetically sorted list ofpathnames matching the pattern.If no matching pathnames are found,and the shell variableallow_null_glob_expansionis unset, the word is left unchanged.If the variable is set, and no matches are found,the word is removed.When a pattern is used for pathname generation,the character``.''at the start of a name or immediately following a slashmust be matched explicitly, unless the shell variableglob_dot_filenamesis set. The slash character must always be matchedexplicitly. In other cases, the``.''character is not treated specially.

The special pattern characters have the following meanings:

*
Matches any string, including the null string.
?
Matches any single character.
[...]
Matches any one of the enclosed characters. A pair of charactersseparated by a minus sign denotes arange;any character lexically between those two characters, inclusive,is matched. If the first character following the[is a!or a^then any character not enclosed is matched. A -or]may be matched by including it as the first or last characterin the set.
 

Quote Removal

After the preceding expansions, all unquoted occurrences of thecharacters\,`,and " are removed.  

REDIRECTION

Before a command is executed, its input and outputmay beredirectedusing a special notation interpreted by the shell.Redirection may also be used to open and close files for thecurrent shell execution environment. The following redirectionoperators may precede or appear anywhere within asimple commandor may follow acommand.Redirections are processed in the order they appear, fromleft to right.

In the following descriptions, if the file descriptor number isomitted, and the first character of the redirection operator is<,the redirection refers to the standard input (file descriptor0). If the first character of the redirection operator is>,the redirection refers to the standard output (file descriptor1).

The word that follows the redirection operator in the followingdescriptions is subjected to brace expansion, tilde expansion,parameter expansion, command substitution, arithmetic expansion,quote removal, and pathname expansion. If it expands to morethan one word,bashreports an error.

Note that the order of redirections is significant. For example, the command

ls > dirlist 2>&1

directs both standard output and standard error to the file dirlist,while the command

ls 2>&1 > dirlist

directs only the standard output to filedirlist,because the standard error was duplicated as standard outputbefore the standard output was redirected todirlist. 

Redirecting Input

Redirection of input causes the file whose name results fromthe expansion ofwordto be opened for reading on file descriptorn,or the standard input (file descriptor 0) ifnis not specified.

The general format for redirecting input is:

[n]<word

 

Redirecting Output

Redirection of output causes the file whose name results fromthe expansion ofwordto be opened for writing on file descriptorn,or the standard output (file descriptor 1) ifnis not specified. If the file does not exist it is created;if it does exist it is truncated to zero size.

The general format for redirecting output is:

[n]>word

If the redirection operator is>|,then the value of the-Coption to thesetbuiltin command is not tested, and file creation is attempted.(See also the description ofnoclobberunderShell Variablesabove.) 

Appending Redirected Output

Redirection of output in this fashioncauses the file whose name results fromthe expansion ofwordto be opened for appending on file descriptorn,or the standard output (file descriptor 1) ifnis not specified. If the file does not exist it is created.

The general format for appending output is:

[n]>>word

 

Redirecting Standard Output and Standard Error

Bashallows both thestandard output (file descriptor 1) andthe standard error output (file descriptor 2)to be redirected to the file whose name is theexpansion ofwordwith this construct.

There are two formats for redirecting standard output andstandard error:

&>word

and
>&word

Of the two forms, the first is preferred.This is semantically equivalent to

>word 2>&1

 

Here Documents

This type of redirection instructs the shell to read input from thecurrent source until a line containing onlyword(with no trailing blanks)is seen. All ofthe lines read up to that point are then used as the standardinput for a command.

The format of here-documents is as follows:

<<[-]word        here-documentdelimiter

No parameter expansion, command substitution, pathnameexpansion, or arithmetic expansion is performed onword.If any characters inwordare quoted, thedelimiteris the result of quote removal onword,and the lines in the here-document are not expanded. Otherwise,all lines of the here-document are subjected to parameter expansion,command substitution, and arithmetic expansion. In the lattercase, the pair\<newline>is ignored, and\must be used to quote the characters\,$,and`.

If the redirection operator is<<-,then all leading tab characters are stripped from input lines and theline containingdelimiter.This allowshere-documents within shell scripts to be indented in anatural fashion. 

Duplicating File Descriptors

The redirection operator

[n]<&word

is used to duplicate input file descriptors.Ifwordexpands to one or more digits, the file descriptor denoted bynis made to be a copy of that file descriptor. Ifwordevaluates to-,file descriptornis closed. Ifnis not specified, the standard input (file descriptor 0) is used.

The operator

[n]>&word

is used similarly to duplicate output file descriptors. Ifnis not specified, the standard output (file descriptor 1) is used.As a special case, if n is omitted, and word does notexpand to one or more digits, the standard output and standarderror are redirected as described previously. 

Opening File Descriptors for Reading and Writing

The redirection operator

[n]<>word

causes the file whose name is the expansion ofwordto be opened for both reading and writing on file descriptorn,or as the standard input and standard output if nis not specified. If the file does not exist, it is created. 

FUNCTIONS

A shell function, defined as described above underSHELLGRAMMAR,stores a series of commands for later execution.Functions are executed in the context of thecurrent shell; no new process is created to interpretthem (contrast this with the execution of a shell script).When a function is executed, the arguments to thefunction become the positional parametersduring its execution. The special parameter#is updated to reflect the change. Positional parameter 0is unchanged.

Variables local to the function may be declared with thelocalbuiltin command. Ordinarily, variables and their valuesare shared between the function and its caller.

If the builtin commandreturnis executed in a function, the function completes andexecution resumes with the next command after the functioncall. When a function completes, the values of thepositional parameters and the special parameter#are restored to the values they had prior to functionexecution.

Function names and definitions may be listed with the-foption to thedeclareortypesetbuiltin commands. Functions may be exported so that subshellsautomatically have them defined with the-foption to the exportbuiltin.

Functions may be recursive. No limit is imposed on the numberof recursive calls. 

ALIASES

The shell maintains a list ofaliasesthat may be set and unset with thealiasandunaliasbuiltin commands (seeSHELL BUILTIN COMMANDSbelow).The first word of each command, if unquoted,is checked to see if it has analias. If so, that word is replaced by the text of the alias.The alias name and the replacement text may contain any validshell input, including themetacharacterslisted above, with the exception that the alias name may notcontain =. The first word of the replacement text is testedfor aliases, but a word that is identical to an alias being expandedis not expanded a second time. This means that one may aliaslstols -F,for instance, andbashdoes not try to recursively expand the replacement text.If the last character of the alias value is ablank,then the next commandword following the alias is also checked for alias expansion.

Aliases are created and listed with thealiascommand, and removed with theunaliascommand.

There is no mechanism for using arguments in the replacement text,as incsh.If arguments are needed, a shell function should be used.

Aliases are not expanded when the shell is not interactive.

The rules concerning the definition and use of aliases aresomewhat confusing.Bashalways reads at least one complete lineof input before executing anyof the commands on that line. Aliases are expanded when acommand is read, not when it is executed. Therefore, analias definition appearing on the same line as anothercommand does not take effect until the next line of input is read.This means that the commands following the alias definitionon that line are not affected by the new alias.This behavior is also an issue when functions are executed.Aliases are expanded when the function definition is read,not when the function is executed, because a function definitionis itself a compound command. As a consequence, aliasesdefined in a function are not available until after thatfunction is executed. To be safe, always putalias definitions on a separate line, and do not usealiasin compound commands.

Note that for almost every purpose, aliases are superseded byshell functions. 

JOB CONTROL

Job controlrefers to the ability to selectively stop (suspend)the execution of processes and continue (resume)their execution at a later point. A user typically employsthis facility via an interactive interface supplied jointlyby the system's terminal driver andbash.

The shell associates ajobwith each pipeline. It keeps a table of currently executingjobs, which may be listed with thejobscommand. Whenbashstarts a job asynchronously (in thebackground),it prints a line that looks like:

[1] 25647

indicating that this job is job number 1 and that the process IDof the last process in the pipeline associated with this job is 25647.All of the processes in a single pipeline are members of the same job.Bashuses thejobabstraction as the basis for job control.

To facilitate the implementation of the user interface to jobcontrol, the system maintains the notion of a current terminalprocess group ID. Members of this process group (processes whoseprocess group ID is equal to the current terminal process group ID)receive keyboard-generated signals such asSIGINT.These processes are said to be in theforeground.Backgroundprocesses are those whose process group ID differs from the terminal's;such processes are immune to keyboard-generated signals.Only foreground processes are allowed to read from or write to theterminal. Background processes which attempt to read from (write to) theterminal are sent a SIGTTIN (SIGTTOU)signal by the terminal driver, which, unless caught, suspends the process.

If the operating system on whichbashis running supportsjob control,bashallows you to use it.Typing thesuspendcharacter (typically^Z,Control-Z) while a process is runningcauses that process to be stopped and returns you to bash.Typing thedelayed suspendcharacter (typically^Y,Control-Y) causes the process to be stopped when itattempts to read input from the terminal, and control tobe returned tobash.You may then manipulate the state of this job, using thebgcommand to continue it in the background, thefgcommand to continue it in the foreground, orthekillcommand to kill it. A ^Z takes effect immediately,and has the additional side effect of causing pending outputand typeahead to be discarded.

There are a number of ways to refer to a job in the shell.The character%introduces a job name. Job numbernmay be referred to as%n.A job may also be referred to using a prefix of the name used tostart it, or using a substring that appears in its command line.For example,%cerefers to a stoppedcejob. If a prefix matches more than one job,bashreports an error. Using%?ce,on the other hand, refers to any job containing the stringcein its command line. If the substring matches more than one job,bashreports an error. The symbols%%and%+refer to the shell's notion of thecurrent job,which is the last job stopped while it was inthe foreground.The previous jobmay be referenced using%-.In output pertaining to jobs (e.g., the output of thejobscommand), the current job is always flagged with a+,and the previous job with a-.

Simply naming a job can be used to bring it into theforeground:%1is a synonym for``fg %1'',bringing job 1 from the background into the foreground.Similarly,``%1 &''resumes job 1 in the background, equivalent to``bg %1''.

The shell learns immediately whenever a job changes state.Normally,bashwaits until it is about to print a prompt before reportingchanges in a job's status so as to not interruptany other output. If the -boption to thesetbuiltin commandis set,bashreports such changes immediately. (See also the description ofnotifyvariable underShell Variablesabove.)

If you attempt to exitbashwhile jobs are stopped, the shell prints a message warning you. Youmay then use thejobscommand to inspect their status. If you do this, or try to exitagain immediately, you are not warned again, and the stoppedjobs are terminated. 

SIGNALS

When bash is interactive, it ignoresSIGTERM(so that kill 0 does not kill an interactive shell),andSIGINTis caught and handled (so that the wait builtin is interruptible).In all cases, bash ignoresSIGQUIT.If job control is in effect,bashignoresSIGTTIN,SIGTTOU,andSIGTSTP.

Synchronous jobs started by bash have signals set to thevalues inherited by the shell from its parent. When job controlis not in effect, background jobs (jobs started with&)ignoreSIGINTandSIGQUIT.Commands run as a result of command substitution ignore thekeyboard-generated job control signalsSIGTTIN,SIGTTOU,andSIGTSTP. 

COMMAND EXECUTION

After a command has been split into words, if it results in asimple command and an optional list of arguments, the followingactions are taken.

If the command name contains no slashes, the shell attempts tolocate it. If there exists a shell function by that name, thatfunction is invoked as described above inFUNCTIONS.If the name does not match a function, the shell searches forit in the list of shell builtins. If a match is found, thatbuiltin is invoked.

If the name is neither a shell function nor a builtin,and contains no slashes,bashsearches each element of thePATHfor a directory containing an executable file by that name.If the search is unsuccessful, the shell prints an errormessage and returns a nonzero exit status.

If the search is successful, or if the command name containsone or more slashes, the shell executes the named program.Argument 0 is set to the name given, and the remaining argumentsto the command are set to the arguments given, if any.

If this execution fails because the file is not in executableformat, and the file is not a directory, it is assumed to bea shell script, a filecontaining shell commands. A subshell is spawned to executeit. This subshell reinitializes itself, sothat the effect is as if a new shell had been invokedto handle the script, with the exception that the locations ofcommands remembered by the parent (seehashbelow under