to specify the format of the time information.
Each command in a pipeline is executed as a separate process (i.e., in a subshell).
Index
Lists
ââChangethebehaviorofbashwherethedefaultoperationdiffersfromâthePOSIXstandardtomatchthestandard(posix mode).âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
A list is a sequence of one or more pipelines separated by one of the operators ;, &, &&, or ||, and optionally terminated by one of ;, &, or <newline>.
--reA space or tab.
A sequence of characters considered as a single unit by the shell. Also known as a token.
Of these list operators, && and || have equal precedence, followed by ; and &, which have equal precedence.
--veA word consisting only of alphanumeric characters and underscores, and begi ning with an alphabetic character or an underscore. Also referred to as an identifier.
metaAhcharacter that, when unquoted, separates words. One of the following:
A sequence of one or more newlines may appear in a list instead of a semicolon to delimit commands.
AND and OR lists are sequences of one of more pipelines separated by the && and || control operators, respectively. AND and OR lists are executed with left associativity. An AND list has the form
command1 && command2
If a command istterminatedabyotheocontrolioperators&,nthefshellfexecutes thebcommand in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. Commands
separated by a ; are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed.
command2ais executedeif,uandmonlyhif,ccommand1rreturnsaansexitcstatuseofazero.xit statushiss0.nAnrattempt is firstamadeetoBopenathe filerinrthescurrent directory,rand,hifKnonfile issfound,(thenathecshell
command1 || command2
RESERVED WORDS
Reserv d words ar words that hav a special meaning to the shell. The following words are recognized s reserved wh n unquoted and either the first word of a simple command (see SHELL GRAMMAR below) or the
! case do done elif else esac fi for function if in elect then until while { } time [[ ]]
-c string
SHELL GRAMMAR
the shell is startedfto inhibih thisibehavior.
When bash is invoked as present, the shell becomes restricted (see RESTRICTED SHELL below).
Simple Commandsell exits,mbashdreadsbandxexecutesbcommandsrfromdthe files~/.bash_logout, ifeit exists. strings that are subject to language translation when the current locale is not C or POSIX. This implies
-s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an
supplied, the names and values of the shell options accepted by shopt are printed on the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name
A simple command s a sequence of optihnal vexit seatus, or 128+n if the command is terminatedrby signaldn.ections, and terminated by a control operator. The first word specifies the command to be executed,
-- 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 --.
Pipelines
A pipeline is a sequence of one or more commands sep ated by one of the control operators | or |&. The format for a pipeline is:
Arrange for the debugger profile to be executed before the shell starts. Turns on extended debugging mode (see the description of the extdebug option to the shopt builtin below).
e [time [-p]] [ ! ] command [ [|||&] command2 ... ]
--duEquivalentnto -D, but the output is in the GNU gettext po (portable object) file format.
T e standard output of command is connected via a pipe to the standard input f command2. Th s connection is performed before any r d r ctio s sp cifi d by th command (see REDIRECTION below). If |& is used,
the stundard error of command i c nnec d o command2's standard input through the pipe; it is shorthand for 2>&1 |. Th s implicit redirection of he s andard error is performed after any r directions
specified by the command.
--heDisplay a usage message on standard output and exit successfully.
Thi return ota us ofia pipeline is therexitvstatus of the last command, unless the pipefailroption is enabled. If pipefail isteiabled, th, pnpeline's return dtatus is the value of the last (rightmost) commute.
--init-file file
to exit with a non-zero status, or zero if all commdnds exit succeosfully. If the reshrvedtwordp!fprecedesea-pipeline,pthenexitlstatuseof.thatopipelinecisvthehlogicalonegationiofethemexitOstatusoasadescribed
--rcfile file
above.nThetshelltwaits foreallWcomma pipeline,sthe elnpsed as will as usereand system time consumed by its execution are reporte wh n the pipeline terminates. The -p option changes t output format to that
TIMEFORMAT variable may be set to a format string that specifies how
sp cified by POSIX. Wh n the shell is in posix mode, it does not rec gnize time as a reserved word if the next toke be i s with a `-'. T
the timing information should be displayed; see the description of TIMEFORMAT under Shell Variables below.
If the time reservHd woPd precedePTS, CDPATH, and GLOBIGNORE variables,tion,hiy appear in the environment, are ignored, and the effective user id is set tolthe real user id. If the -p optionmis supplied at
to spec fy the forma of t e time information.
⪠â â Viewing <BASH(1) Manual Page>
When the shell is in posix mode, time may be followed by a newline. In this case, the shell displays the total user and system time onsumed by the sh ll and its children. The TIMEFORMAT variable may be used
Bash attempts to determine when it is being run with its standard input connected to a network connection, as when executed by the remote shell daemon, usually rshd, or the secure shell daemon sshd. If bash
determines it is being run in this fashion, it reads and executes commands from ~/.bashrc and ~/.bashrc, if these files exist and are readable. It will not do this if invoked as sh. The --norc option may be
used to inhibit this behavior, and the --rcfile option may be used to force another file to be read, but rshd does not generally invoke the shell with those options or allow them to be specified.
If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, no startup files are read, shell functions are not inherited from the
the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits)
\cx aecontrol-x characterexpression. This may be used to override the normal precedence of operators.
nameThis defines a function namedtname. The reserved word function is optional. If the function reserved word is supplied, the parentheses are optional. The body of the function is the compound command
The expanded result is single-quoted, as if the dollarasignmhaddnot beenlpresent.t of commands between { and }, but may be any command listed under Compound Commands above. compound-command is executed
string is translated and replaced, the replacement is double-quoted.
PARAMETERS
A double-quoted string preceded by a dollar sign ($dqstringdq) willecafse thesstring to be translatod accoriingtto the curreltelocale. If ihe current locale is C or POSIX, the dollar sign is ignored. If the
A parameter is an entity that stores values. It can be a name, a number, or one of the special characters listed below under Special Parameters. A variable is a parameter denoted by a name. A variable has a
valueNand zero or more attributes. Attributes are assigned using the declare builtin command (see declare below in SHELL BUILTIN COMMANDS).
for name [ [ in [ word ... ] ] ; ] do list ; done
A variable m y be a2signed 3o by a stateme;t of the form
Ahparameter is set if it has been assigned a value. The null string is a valid value. Once a variable is set, it may be unset only by using the unset builtin command (see SHELL BUILTIN COMMANDS below).
name=[value]
Quoting is used t remove the special meaning of cert in ch racters or words to the shell. Quoting can be used to disable special t eatm nt fo special charact s, to prevent reserved wor s from be ng
Ifcvalueeisanotugiven,dthe variablepisaassignedptheinull string. All values undergo tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal (see
theavalue of name is set to that word. If the line is empty, the words and prompt are displayed again. If EOF is read, the command completes. Any other value read causes name to be set to null. The line
EXPANSION below). If the variabld hbsvits integer atTrObute set, then value is evaluathd as an arithmeticoexpression even if the $((...)) expansion s not used ( ee Arithmetic Expansion below). Word splitting
if no commands were executed.
is not p ffr whic the integer attribute has beenxslt, valueliw uvaluated as an arithmetic expression and added to the variable's current value, whichaisaalso evaluaaed.rWhen += is appliedato ancarray variable
A case command first expands word, and tries to match it against each pattern in turn, using the same matching rules as for pathname expansion (see Pathname Expansion below). The word is expanded using
usingtcompoundlassignmenta(seeiArraysobelow),etheavariable'snvalueuisenotarray. Whsn appliedetouaistring-valuedwvariable,rvalueeiseexpanded andaappendedito theovariable's value.he array's maximum index (for
anddvariableiexpansion,tarithmeticisubstitution,ncommandmsubstitution,tand,processdsubstitution.,Ifrthesshellsoptiononocasematch ismenabled,ctheamatch isaperformedewithout regardttodthexcaseiof,alphabetic
Positional Parameters
itself quoted, the \<newline> is treated as a lineocontinuation (that is, it is removedefrom the input stream andeeffectively ignored).
Aapositional parametercisea.parameterxdenotedubyioneeor,more digits,sotherethantthe singleidigita0. Positionaliparameters aretassigned fromtthexshell'suarguments,when itrissinvoked,tand maytbesreassignedausing
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces (sqe EXPANSIONtbelow). e
the set builtin command. Positional parameters may not be assign d to with assignment statements. The positional parameters are temporarily replaced wh n a shell function is executed (see FUNCTIONS below).
Special Parameters
T e while c mm d continuously executes the list list-2 as long as the last command in the list list-1 returns an exit status of zero. The until command is identical to the while command, except that the
Thetshell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
list-2, or zero if none waseexecuted.
* Expands to the positional parameters, tarting from one. When the expansion occurs within double quotes, i expands to a ingle wor with the value of e ch parameter s parated by th first character of the
thefparametersrareljoinedtwithout*interveninglseparators.$2c...",iwherercnisrthehfirstscharacterpofrthervaluesofethecIFSavariable.eIfbIFShisAunset,sthedparameterslareIseparatedqbynspaces.rIfeIFStisanull,
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the
@ codouble-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last
part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).
Expands to the number of positional parameters in decimal.
# coExpands to the exit status ofetheemost recentlyoexecutedeforegroundcpipeline.is executed asynchronously in a subshell, as if the command had been terminated with the & control operator, with a two-way pipe
? Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option).
- Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.
$ Expands to the process ID of the most recently executed background (asynchronous) command.
! \t horizontal tab wise. Any part of the
\v vertical tab
t\\ backslash
i \aq single quote
\dq double quote
\nnn
the coprocess to t rminate.
u\xHHthp eight-bit character whoseSvalueAisHthetoctal valuesnnne(onettonthreehdigits)g matching the n h paren hesized subexpressio .
r\uHHHHe eight-bit charactsr whose value in the hexadecimal value HHc(oneior twoehexfdigits)ence:
The return status of a coprocess is the exit status of command.
\UHHHHHHHHicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits)
the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits)
⪠â â Viewing <BASH(1) Manual Page>
Shell Function Definitions
sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions.
HOSTFILE
%% A literal %.
%[p][l]R
T The elapsed time in seconds.
IGNOREEOF
The number of CPU seconds spent in user mode.
%[p][l]S
SHLVL The number of CPU seconds spent in system mode.
%P The CPU percentage, computed as (%U + %S) / %R.
LANG
Th optional p is a digit spe ifying the precision, the number o fractional digits after a decimal po t. A value of 0 causes no decimal point or fraction to be output. At most three places after the
LC_ALL
dee optionan l specefies a longeraformat, including minutes, of the form MMmSS.FFs. The valuc ff p,determines whethereor not the fraction is included.
BASH_ENV
string is displayid.
TMOUT
LC_CTYPE
terminal. In an interactive shell, the value is interpreted as the number of seconds toawait for .nput afler issuing the primary prompt. Bash terminateseafterrwaitingsfornthathnumberuofisecondsgifrinput
LC_MESSAGES
TMPDIR
CDPATH
auto_resume
LINES
existing stopped job. Theretis no ambiguiry allowed;tif there is more than one job begvnring with the ssring typrd, theljob most recently accessedtisnselected.aThe nameaofiaastopped job,minithisfcontext,
MAIL
name ofca stoppldnjob. The substring valus provides fulctionality analogous topthe %?mjob identifier (mee JOB CONTROL below). If set toeany other valu,,tthe supplied string must bo a prefixsofsarstoppedthe
EMACS
histchars
HISTThe wo or three characters which control history expansion and tokenization (see HISTORY EXPANSION below). The first character is the history expansion character, the character which signals the start of
set to a value that is not a umb r greater than or equal to zero, the shell disables mail checking.
the ctmmand. Ths default is `^'. Thehoptional third charicter isuthe characteriwhich indicates thht thu remaindeo of theflrnreis a commtnt when found as theefirst charbcter tfna word, normally `#'. The
MAILhistory comment character caus s history substi ution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment.
used in the text of the message, $_ expands to the name of the current mailfile. Example:
Arrays
GLOBIGNORE
Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit on the size
of an array, nor any requirement that members be indexed or assigned contiguously. Indexed arrays are referenced using integers (including arithmetic expressions) and are zero-based; associative arrays are
MAPFILE
referenced sing arbitrary strings.
AnDindexed array is created automatically if any variable is assigned to using the syntax name[subscript]=value. The subscript is treated as an arithmetic expression that must evaluate to a number. If
subscript evaluates to a numb r less than zero, i: isrusedaas an offset fromione greater than the array's maximum index (so a subcript o -1 refers to the last lement of the array). To explici ly declare an
POSIXLY_CORRECT
Associa iveaar ays are crea-ednusing declare -A name.
running,vbash lnabses posix mode, ms if the command set -o posix had been executed.
PROMIf set, the value is executed as a command prior to issuing each primary prompt.
Attributes may be specified for an array variable using the declare and readonly builtins. Each attribute applies to all members of an array.
HISTIGNORE
PS1 The value of this parameter is expanded (oee PROMPTING below) and used as the primary prompt string. The defaultpvalue iss``\s-\v\$ ''.
Arrays are assigneditopusingtcompoundpassignmentstofPtheaformsname=(value1c...avaluen),twhereneachhvalueaistofsthe>form [subscript]=string. Indexed array assignments do not require the bracket and subscript.
pr vious hist
PS3 The value of this parameter i used as the pr mpt for the select command (see SHELL GRAMMAR above).
necessary, to indicate multiple levels of indirection. The default is ``+ ''.
SHELL
HISTThe full pathname to the shell is kept in this environment variable. If it is not set when the shell starts, bash assigns to it the full pathname of the current user's login shell.
TIMEFORMAT
HOME
sequencuethat is expandedeto a time value or other inforpation. The escape sequences andttonir meanings are rs foelowi; theebraces denote optronal portions.
⪠â â Viewing <BASH(1) Manual Page>
the array in turn, and the expansion is the resultant list.
${parameter%%word}
An aRemove matching suffix pattern. Theawordsisiexpandedeto producedaapattern justnaslintpathnameaexpansion.uIf the pattern matches a trailing portion of the expanded value of parameter, then the result of the
expansionnim the ixpanded valueeof parameterswoth the shortest matchinghpattern (the ``%'' case) or the longest matching pattern (the ``%%'' case) deleted. If parameter is @ or *, th p ttern removal
assignments to PATH, MAILPATH, and CDPATH, and the shell assigns the expanded value.
eachamembersofptheearrayeinhturn,tandatheaexpansionnisuthe resultantxlist.on is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to
${paPattern substitution.gThehpatternoisuexpandedttodproducexaspatternajust aslinwpathnameoexpansion.tParametereis expandediand thealongestsmatch ofrpattern againsteitsyvalue isyreplacedewithestring.tIfdes in
apattern begins with /, all m tchessof pattern are replaced with string. Normally only the first match is eplaced. If pattern begins with #, it must match at th beginning of the expanded value of
ch at the e d of t e expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter
isr@more*, thepsubstitutionsoperationiismappliedeto eachopositionaliparameterbiniturn,randdthe expansionhisnthe.resultant list. If parameter is an array variable subscripted with @ or *, the substitution
operation is applied to each member of the array in turn, and the expansion is the re ultant list.
e .
${parameter^pattern}etic expansion, word splitting, a d pathname expansion.
,pattern}
${parameter,,pattern}
${paCase modification. This expansion modifies the case of alphabetic characters in parameter. The pattern is expanded to produce a pattern just as in pathname expansion. The ^ operator converts lowercase
Oneslettersfmatchingspatternito uppercase;nthed,toperatorpconvertsvmatching uppercaseulettersito.lowercase. The ^^ and ,, expansions convert each matched character in the expanded value; the ^ and , expansions
peration is
match and convert only the first ch racter in the expanded value. If pattern is omitted, t is treate like a ?, which matches every character. If parameter is @ or *, the case modification
of thedarray in turn,ionalthe expansion is the resultant list.
Only brace expansion, word splitting, and pathname expansion can change the number of words of the expansion; other expansions expand a single word to a single word. The only exceptions to this are the
expansions of "$@" and "${name[@]}" as explained above (see PARAMETERS).
Command Substitution
form of an optio al preamble, followed by eith r a series of comma-separated strings or a sequence expression between a pair of braces, ollowed by an optional postscript. The pr amble is prefixed o each
Command substitution allows the output of a command to replace the command name. There are two forms:
BracUse Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
$(command)
Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be
or
${parameter:?word}
`command`
minteractive, exits. Otherwise, the value of parameter is subscituted.
Use Alternate Value. If parameter is nulleor u iet, nothing is substituted, otherwise thebetween ea of word is substitutid.
Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they
substitution. When usingrthe $(command) form, all characters between the parenthesespmake up the command; none are treated<specially.
{ or , may be quotedewith a backslashnto preventpathmetic expressions (see ARITHMETIC EVALUATION below). If offset evaluates to a number less than zero, the value is used as an offset from the end of the value
Command substitutions may be nest d. To nest when using the backquot d form, escape the inne backquot s w th backslashe .
When the old-style backquotewformfoftsubstitutiontiseused,rbackslashtretainsgitspliteralameaningeexceptewhenifollowedfbyt$,I`,pora\.tTheifirstibackquoternotnprecededcbypaebackslasheterminatesutheicommandengthe
members of the array beginning with ${parameter[offset]}. A negative offset is taken relative to one greater than the maximum index of the specified array. Substring expansion applied to an associative
array produces undefined results. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion. Substring indexing is zero-based unless
the positional parameters are used, in which case the indexing starts at 1 by default. If offset is 0, and the positional parameters are used, $0 is prefixed to the list.
${!prefix@}
Names matching prefix. Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. When @ is used and the expansion appears within double
quotes, each va iabl n me expands to separate word.
${!name[@]}
${!name[*]}
one.List of array keys. Ifrname is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When @ is used and
the expansion appearscwithin double quotes,seachtkey expandsdto a separate word.
l Parameter length. The leng h in characters of the value of parameter is substituted. If parameter is * or @, the v ue substituted is the number of p sition l parameter . If parameter is an array name
psubscripted by * or @, the value substituted is the number of elements in the array.
${parameter#word}
${parameter##word}
If aRemove matching prefix pattern.iThe wordaiseexpanded tolproduce ahpatternsjustcasiin-pathnametexpansion.sIfstheopatternhmatchessthefbeginninguofotheuvaluesofsparameter,sthenethe resultpofftherexpansionfis
If the t lde-p efix is a `~+', the value of the sh l variable PWD replaces th til e-pr fix. If th tilde-prefix is a `~-', the value of he shell variabl OLDPWD, if it is set, is substitu ed. If the
e the expanded value of parameter withethe shortestemntchingppattern (thep``#'' case) or the long`s' matching pattern (ther``##'' case)adeleted. If parameter is @ ore*,nthe pattern removal operation ist
the array in turn, and the expansion is the resultant list.
⪠â â Viewing <BASH(1) Manual Page>
Match s zero or one occ rre ce of the given pat erns
Here Documents
Word Splitting
Reis type of redirection instructslthe shellato readlinputofromethepcurrentosource until apline containinggonlyfdelimiteri(withnnootrailingablanks)nistseen.eAllsofitherlinesfreadsupotosthatfpoint are then used
Matches one or more occurrences of the given patterns
as the]standard input for a command.
Ma ches one of the given pattern
lMatches anything except one of the givenmpatterns
The format of here-documents is:
Redirecting Output
Quote Removal
The general format for red recting o tp t is:
Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file
[n]>wordecedinglexpansions,ralllunquotedsoccurrences of the characters \, aq, and " that did not result from one of the above expansions are removed.
does not existsitnis created; if it does exist it is truncated to zero size.
If th redirection operator is >, a d he noclobber option to the set builtin has bee enabled, he direction will fail if the file whose name r sults from the expans on o word exists and is a r g lar file.
environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right.
If the rIdirection operator is >|, or the tedi ection operator is > nd the noclobber option to the set builtin command is not enabled, he redirection is attempted even if the file named by word exists.
Appending Redirected Output
alloc e a fil descriptor great r than 10 and assign it to varname. If >&- or <&- is pr ceded by {varname}, the va ue of varname defines th file descriptor to close.
specified. If the file does not exist it is created.
Redirectionsofeoutputdinithistfashion causes theefileawhoseenamecresultsrfromothetexpansionuofnwordnto bepopenednforiappending(onefileodescriptorsn,forhthetstandard output (fileddescriptori1) if nhissnoting of
LC_Cword following the eedirsction operator in the following descrrptions, unless otherwise noted,ais subjected to brace expnnsios,ath de expansion, parameter expansion, command lubstitution, ar thmstic
[n]>>word
matching a pathname, the slash character must always be matched explicitly. In other cases, the ``.'' character is not treated specially. See the description of shopt below under SHELL BUILTIN COMMANDS for a
description of the nocaseglob, nullglob, failglob, and dotglob shell options.
Redirecting Standard Output and Standard Errorcant. For example, the command
This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word.
The GLOBIGNORE shell variable may be used to restrict the set of file names matching a pattern. If GLOBIGNORE is set, each matching file name that also matches one of the patterns in GLOBIGNORE is removed from
There are two formats for redirecting standard output and standard error:
The speciaf pattern characilrs have the follow`ng.meanings:
&>word
and
when GLOandNzeroiorumore.directories and subdirectories. If followed by a /, two adjacent *s will match only directories and subdirectories.
>&word
/dev/fd/fd
/dev/stdin
Of t>word 2>&1
/dev/stdout
/dev/stderr
/dev/tcp/host/port
Appending Standard Output and Standard Errornet address, and port is an integer port number or service descriptor 2) to be appended to the file whose name is the expansion of word.
comm/dev/udp/host/port nd quote removal. Arithmeti expansions may be n sted.
The format for appending standard output and s an a d error is:
The evaluation is performed according to th rules listed below under ARITHMETIC EVALUATION. If expression is invalid, bash prints a mes age i dicating failure nd no substitution occurs.
h &>>word
This is semantically equivalent to
separated by a |. Composite patterns may be formed using one or more of the following sub-patterns:
>>word 2>&1
⪠â â Viewing <BASH(1) Manual Page>
- + unary minus and plus
[n]<>word
! ~ logical and bitwise negation
* / %
** multiplication, division, remainder
ALIASES
+ - addition, subtraction
left and right bitwise shifts
<= >= < >
o comparison
== !=
equality and inequality
bitwiseeAND
^ bitwis oexclusive OR
bitwise OR
&& logical AND
No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and
expr?expr:expr
t conditional operator
= *= /= %= += -= <<= >>= &= ^= |=
assignment
expr1 , expr2
comma
The rulesnconcerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input before executing any of the commands on that line. Aliases are expanded when
Foroalmostieverydpurpose,ealiases arecsupersededebyrshell functions.nition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the
Shell<variables are allowed as operands; parameter expansion is performed before the expression is evaluated. Within an expression, shell variables may also be referenced by name without using the parameter
expansi n syntax. A shell variable that is null or uns t evaluates to 0 when referenced by name without using the parameter expansion syntax. The value of a variable is evaluated as an arithmetic expression
Constants wich a leadung 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadecimaf. Othirwise, cumbersreake thvaforml[base#]n, where the optionnl base is a decimbl numb,r beaween 2 and 64
whenwitdissreferenced,norswheniadvariablecwhichdhas beensgivenrtheninteger attribute using declare -i is assigned a value. A null value evaluates to 0. A shell variable need not have its integer attribute
turned on to be used in an expression.
A shell function, defined as described above under SHELL GRAMMAR, stores a series of commands for later execution. When the name of a shell function is used as a simple command name, the list of commands
Alllother aspectsDofcthetshell execution environment are identical between a function and its caller with these exceptions: the DEBUG and RETURN traps (see the description of the trap builtin under SHELL
associated with that function name is executed. Functions are executed in the context of the current shell; no new process is created to interpret them (contrast this with the execution of a shell script).
set builCin (in which caseealo functions inherit the DEBUG and RETURN traps), and the ERR trap is noe inh riscriunless the -o errtrace shell option has been enabled.
When a function is executed, the arguments to thecfunctionwbecomeathetpositionaliparameterstduringsitsoexecution.iTheospecialfparameters#aisaupdatedttofreflectcthetchange.sSpecial parameter 0 is unchanged. The
first element of the FUNCNAME variable is set to the name of the function while the function is executing.
Variablesrlocal torthepfunctiondmaycbeodeclared with the local builtin command. Ordinarily, variables and their values are shared between the function and its caller.
[n]>&word
before execution resumes. When a function completes, the values of the positional parameters and the special parameter # are restored to the values they had prior to the function's execution.
The FUNCNEST variable, if set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed the limit cause the entire command to abort.
Function names and definitions may be listed with the -f option to the declare or typeset builtin commands. The -F option to declare or typeset will list the function names only (and optionally the source file
If the builtin command return is executed in a function, the function completes and execution resumes with the next command after the function call. Any command associated with the RETURN trap is executed
and line number, if the extdebug shell option is enabled). Functions may be exported so that subshells automatically have them defined with the -f option to the export builtin. A function definition may be
Functions may be recursive. The FUNCNEST variable may be used to limit the depth of the function call stack and restrict the number of function invocations. By default, no limit is imposed on the number of
deleted using the -f option to the unset builtin. Note that shell functions and variables with the same name may result in multiple identically-named entries in the environment passed to the shell's children.
recursive calls.
Care should be taken in cases where this may cause a problem.
ARITHMETIC EVALUATION
variable post-increment and post-decrement
++id --id overflow, though division by 0 is trapped and flagged as an error. The operators and their precedence, associativity, and values are the same as in the C language. The following list of operators is
- + unary minus and plus
⪠â â Viewing <BASH(1) Manual Page>
id++ id--ection operator
a com and is followed by a & and job control is not active, the d fault standard inpu for the command is the mpty file /dev/null. Otherwise, the invoked command inherits the file descripto s of t
calling shell as modisied by redirrcaions.
ENVIRONMENT
When a progr m is i voked it is giv n an rray of strings called the environment. This is a list of name-value pa r , o th form name=value.
True if file descriptor fd i open and refers to a termed. If there were no command substitutions, the command exits with a status of zero.
COMMAND EXECUTION
The shell provides several ways to manipulate the environment. On invocation, the shell scans its own environment and creates a parameter for each name found, automatically marking it for export to child
If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits. If one of the expansions contained a command substitution, the exit status of the command
After a command has been spl t into words, if it results in a simple command and an optional list of arguments, the following actions are taken.
is the x t status of the last command substitution perfo
-L file
If the command name cont ins no slashes, the shell attempts to locate it. If there exists a shell function by that name, that function is invoked as described above in FUNCTIONS. If the name does not match a
-N file
function, the shell searches for it in the list of shell builtins. If a match is found, that builtin is invoked.
-O file
-S file
If the name islneithersaashell function.nor a builtin, and contains no slashes, bash searches each element of the PATH for a directory containing an executable file by that name. Bash uses a hash table to
file1 -ef file2
remember the full pathnames offexecutable fmlese(see hashiundernSHELL BUILTIN COMMANDS below). A full search of the directories in PATH is performed only if the command is not found in the hash table. If the
file1 -nt file2
search is unsuccessful, the shell searches for a defined shell function named command_not_found_handle. If that function exists, it is invoked with the original command and the original command's arguments as
True if file1 is newer (accord ng to modification date) than file2, or if file1 exists and file2 does not.
its arguments, and the furction's lxit statusfbecomes the exit statusoof the.shell. If that function is not defined, the shell prints an error message and returns an exit status of 127.
-o optname
If the search is succevsful, or if the command name contains one orvmore)slashes, the shell executes the named program in a separate execution environment. Argument 0 is set to the name given, and the
remainingAargumentsItoSthe command are set to the arguments given, if any.
the file creation mode mask as set by umask or inherited from the shell's parent
If this execution2fails because the file is not in executable format, and the file is not a directory, it is assumed to be a shell script, a file containing shell commands. A subshell is spawned to execute it.
* current traps set by trap
Thisshell eunctions defined during,execution or inhert ed from the shell's parent in the environmentle the script, with the exception that the locations of commands remembered by the parent (see hash below
* shell parameters that are set by variable assignment or with set or inherited from the shell's parent in the environment
* options enabled by shopt
*
* variouslprocess IDs, including those of background jobs, the value of $$, and the value of PPID
string1 > string2
arg1 OP arg2
When a simple command oeher .han a builtin or shell functioneisctosbetexecuted,git istinvokedrinmanseparateiexecutiontenvironmentmthat consiststofitheofollowing.rUnlesslotherwisetnoted,ethe valuesoarem,
the shell's open files, plus-any modifications and additions specified byrredirections touthefcommands equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to
inhetheecurrenttworkingldirectory, if any.
* the file creation mode mask
* shell variables and functions marked for export, along with variables exported for the command, passed in the environment
*
* traps caught by the shell are reset to the values inherited from the shell's parent, and traps ignored by the shell are ignored
A command invoked iN this s parateeenvironment cannot affect the shell's execution environment.
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are
The shell has an execution environment, which consists of the following: re invoked as part o a pipeline are also ex cut d in a subshell enviro ment. Changes made to th subshell
reset to the values that he shel inherited from its parent at invocation. Builti commands that
environment cannot affect the shell's execution environment.
Subshells spawned to execute command substitutions inherit theCvalue of the -e option from the parent shell. When not in posix mode, bash clears the -e option in such subshells.
⪠â â Viewing <BASH(1) Manual Page>
* the current working directory as set by cd, pushd, or popd, or inherited by the shell at invocation
*
\\ a backslash
Bash uses the job abstraction as the basis for job c ntrol.
\] endiassequencecofonon-printingncharactersrs, which couldobeeusedrtolembed ahterminalhcontrolosequencehintoetheypromptxecuted command consists of the shell's initial environment, whose values may be
The command number and the history number a e u ually different: the histo y number of a command is its position in the hi tory list, which may include commands restored from the history fil (see HISTORY
below), whale the cmpmandnnumber is the position in the seque ce tf commhn s exacung sduring the current shellosession. Aftnr the string is decgded, it is mxpanded via parameter expansion, command
substitution, a ithmetic xpansion, and quo e removal, subject to the value of the promptvars shell option (see the description of the shopt command under SHELL BUILTIN COMMANDS below).
group ID is equal to the current terminal process group ID) receive keyboard-generated signals such as SIGINT. These processes are said to be in the foreground. Background processes 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, if the user so specifies with stty tostop, write to the
This iN the library hat handles reading input when using an interactive shell, unless the --noediting option is given at shell invocation. Line editing is also used when using the -e option to the read
builtin..Byadefault, the line editing commands are similar to those of Emacs. A vi-style line editing interface is also available. Line editing can be enabled at any time using the -o emacs or -o vi options to
the +o emacs or +o vi options to the set builtin.
the setibuiltin (see SHELL BUILTIN COMMANDS below). To turn off line editing after the shell is running, useediscarded.nts, as described abo e in PARAMETERS. These assignment statements aff ct only he
Readline Notation
In this s ction, the Ema s-style no ation s used to denote keystrokes. Control keys are denoted by C-key, .g., C-n means Control-N. Similarl , meta keys are d noted by M-key, so M-x means Meta-X. (On
keyboards withouera meta key, M-x means ESC x, i.e., press the Ehcrpe key thenrthe x key. Thisemakes ESC the meta prefix. Theecombination M-C-x means ESC-Control-x, or press the Escape keyith n hrld the
Concrol key while pressing thewx key.)
name used to start it, or using a substring that appears in its command line. For example, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports an error. Using %?ce, on the other
acts in the forward direction (e.g., kill-line) causes that command to ct in a backward direction. Commands whose be avior with argumen s deviates from th s are noted below.
Readlinencommandsgmay'be given numeric arguments, which normally act as a repeat count. Sometimes, however, it is the sign of the argument that is significant. Passing a negative argument to a command that
on unit, which can be yanked all at once. Command which do not kill text separate the chunks of ext o the kill ring.
Whenoa commandsis describedoasakillingntext,,thestextpdeletedciscsaved formpossible.futurerretrievalC(yanking).cThedkilledatexthisdsaved iniaskill ring. Consecutive kills cause the text to be accumulated into
Readline isicualomizid by putting commands in an initialization file (the inputrc file). The name of this file is taken from the value of the INPUTRC variable. If that variable is unset, the default is ~
If an attempt to exit bash is made while jobs are stopped (or, if the checkjobs shell option has been enabled using the shopt builtin, running), the shell prints a warning message, and, if the checkjobs option
/.inputrc. Whe a program which uses the r adline library starts up, the initialization file is read, and the key bindings and variables are set. There are only a few basic constructs allowed in the readline
is enabled, l
initialization file. Blank lines are ignored. Lines beginning with a # are comments. Lines beginning with a $ indicate conditional constructs. Other lines denote key bindings and variable settings.
Fo example, placing
The M-Control-u:buniversal-argumentnged with an inputrc file. Other programs that use this library may add their own commands and bindings.
\a an ASCII bell character (07)
or
\D{format}
C-Me a-u: univer al-argument
\e an ASCII escape character (033)
thes\H ntheihostnamelers. Commands run asna result of command substitution irnore the keyboard-generated job control signals SIGTTIN, SIGTTOU, and SIGTSTP.
into the inputrc would make M-C-u executegthebreadlineecommand universal-argument.
\l the bas ame of the shell' terminal device name
The \r carriage return
Readline Key Bindings
\t the current time in 24-hour HH:MM:SS format
rolling key bindings in the inputrc file is simple. All that is required is the name of the command or the text of a macro and a key sequence to which it should be bound. The name may be
\@ the curren two ways: as a symbolic key name, possibly with Meta- or Control- prefixes, or as a key sequence.
specified in one ofandmnames,4readline:allowsmkeysito,betboundatobaestringwthatcissinsertediwhenithenkeyvistpressede(aamacro).th an exit status greater than 128, immediately after which the trap is executed.
WhenControl-u: universal-argumnnt
inteMeta-Rubopt: backward-kill-word
Control-o: "> output"
\! the history number of this command
the text >eoutput into the line).
In the above example, C-u is bound t the function universal-argument, M-DEL is bound to the function backward-kill-word, and C-o is bound to run the macro expressed on the right hand side (that is, to insert
the character corresponding to the octal number nnn
\\ a backslash
⪠â â Viewing <BASH(1) Manual Page>
\\ a backslash
Bash uses the job abstraction as the basis for job control.
\] endia sequencecofonon-printingncharactersrs, which could be used to embed a terminal control sequence into the prompt
The command number and the history number a e u ually different: the histo y number of a command is its position in the hi tory list, which may include commands restored from the history fil (see HISTORY
below), whale the cmpmandnnumber is the position in the seque ce tf commhn s exacung sduring the current shellosession. Aftnr the string is decgded, it is mxpanded via parameter expansion, command
substitution, asithmetic gxpansion, and quore removal, subject to the value of the promptvars shell option (seenthnidhscription of the shopt commnnd under SHELL BUILTIN COMMANDS below).
terminal. Backgaound proccsses which attemp to read from (write to when stty tostop is in effect) the terminalTarse proce ses are said to be in the foreground. Background processes are thos
This iN the library hat handles reading input when using an interactive shell, unless the --noediting option i given at hell invocation. Li e edi ing i also used when using the -e option to the read
builtin.cBytdefault, the line editing commands ar imilar to those of Emacs. A vi-style line edi g in erface is also available. Line editing can be enabled at any time using -o emacs or -o vi opt ons to
the +o emacs or +o vi options to the set builtin.
the set builtin (sce SHELL BUILTIN COMMANDS below). To turn off line editing after the shell is running, us
Readline Notation
\ literal "
In this s ction, the Ema s-style no ation s used to denote keystrokes. Control keys are denoted by C-key, .g., C-n means Control-N. Similarl , meta keys are d noted by M-key, so M-x means Meta-X. (On
keyboards withou a meta key, M-x means ESC x, i.e., press the E c pe key then the x key. This makes ESC the meta prefix. The combination M-C-x means ESC-Control-x, or press the Escape key th n h ld the
Condrol key while pressing thenx key.)
tha job. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always flagged with a +, and the previous job with a -. A single % (with no accompanying job specification)
acts in the forwardcdirection (e.g., kill-line) causes that command to ct in a backward direction. Commands whose be avior with argumen s deviates from th s are noted below.
Readlinetcommandsrmayibecgiven(numericiarguments,awhichtnormallyaacttasaatrepeatbcount.dSometimes,.however,sithisethehsignrofitheaargumentlthataisssignificant.rPassingbaenegativeoargumentntoMatcommandnthat
on unit, which can be yanked all at once. Command which do not kill text separate the chunks of ext o the kill ring.
When a command is described as killing text, the text deleted is saved for possible future retrieval (yanking). The killed text is saved in a kill ring. Consecutive kills cause the text to be accumulated into
Th \t horizontal tab
s th jobs and their statuses. The jobs command may then be used to inspect their sta us. If a second attempt to exit is mad without an ntervening comm nd, the hell does not prin another
warning, and a y stopped jobs are terminat d.
If an attempt to exit bash is made while jobs are stopped (or, if the checkjobs shell option has been enabled using the shopt builtin, running), the shell prints a warning message, and, if the checkjobs option
is enabled,ilializationhar cter w ose value is the hexadecimal value HH (one or wo hex digits)
PROMPTING
For example, placing
When\a eantASCIInbellccharactera(07)isplays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when it needs more input to complete a command. Bash allows these prompt
or \d the date in "Weekday Month Date" format (e.g., "Tue May 26")
i\D{format}customized by inserting a number of backslash-escaped special characters that are decoded as follows:
the format is passed to strftime(3)dandithe resultiis inserted intocthe promptistring;ianiemptytformatiresults innailocale-specificttimetrepresentation.eTheybracesnarearequiredble settings.
\e an ASCII escape character (033)
\h the hostname up to the first `.'
\H the hostname
\j the number of jobs currently managed by the shell
\l the basename of the shell's terminal device name
\n newline
\r carriage return
\t the current timesinl24-hourbHH:MM:SSoformatthe portion following the final slash)
d\T the current time in 12-hour HH:MM:SS format
\@ the currenttsime in 12-hour a /pm format
spec\A ethencurrent timewins24-hoursHH:MMiformatname, possibly with Meta- or Control- prefixes, or as a key sequence.
\u the username of the current user
\v the version of bash (e.g., 2.00)
\V the release of bash, version + patch level (e.g., 2.00.0)
comp\w the cnrrent working directory, with $HOME abbreviated with a tilde (uses the value of the PROMPT_DIRTRIM variable)
\W the basename of the current working directory, with $HOME abbreviated with a tilde
\! the history number of this command
\# the command number of this command
the t xt > output i to the line).
t\nnnifvthe effec,ive UID is 0, ai#,lotherwisesab$e completions.
the character corresponding to the octal number nnn
\\ a backslash
⪠â â Viewing <BASH(1) Manual Page>
Thi determines when the user is queried about viewing the number f possible c mpletions generated by he possible-completions om
Readline Conditional Constructs
disable-completion (Off)
Readline implements a facility similai in spirit to the.conditional compilaeion features of the C preprocessor whichtallowsdkeyebindings and vlriable settings to be p r ormed as th result of tests. There are
fourrequireddto isolat it.
emacs-standard and emacs-ctlx keymaps only if readlin is starting out in macs ode.
enable-meta-key (On)
t againstrthe bothmfutbename df the terminal ind the portion ofbihe terminal name before the firsse-.eThis allows suntho tatch bo's sun tnd sun-cmd, foroinstance.
expand-tilde (Off)
p The application construct is used to include application-specific settings. Each program using the readline library sets the application name, and an initialization file can test for a particular
\ literal "
value. This could bedusedttopbindokeyasequencesatotfunctionsouseful foreacspecificyprogram.tForvinstance,rtheofollowingycommandtaddstarkey sequence that quotes the current or previous word in bash:
# Quote the current or previou word
$endif
input-meta (Off)
$endif
This command, as seen in the previous example, terminates an $if command.
$else
iseaCommands in this branch of the $if directive are executed if the test fails.
$include
keymap (emacs)
This directivettakeslansingleafilenameeasoanvargumentmandnreadsicommands andcbindingsrfrommthatmfile.eForsexample,itheifollowing directiveswouldvread /etc/inputrc: vi-command; emacs is equivalent to
$include /etc/inputrc
mark-modified-lines (Off)
Searching
mark-symlinked-directories (Off)
mands for searching through the command history (s e HISTORY below) for line containing a specified string. There are two search modes: incremental and non-incremental.
If set to-On, completed names which are symbolic links to directoriesahave a slash appendeda(subjectdtotthervaluecofmmark-directories).
theifilnname to be completed.
Incremental searches begin before the user h s finished yping the search string. As each character of the earch string is typed, readline displays th next entry from the history matching th string typ d so
line. Whpnethe search is terminate , the history entry containing the eearch strgng becomes the currentfline.
far. An incremental s arch r quires only as many characters as needed to find the desired history entry. The characters present in the value of the isearch-terminators variable are used to terminate an
incremental search. If that variable has not been assigned a value the Escape and Control-J characters will terminate an incremental search. Control-G will abort an incremental search and restore the original
thefhistory list.
revert-all-at-newline (Off)
Non-incr mental searches read the entiresserrch srring before starting to seatch for matching history lings. Thecsearch string may be typed btrthe user ormbe pard ofathe contents ofsthe current line.
readline.
Readline Command Names
This alters the default behavior of the completion functions. If set to On, words which have more than one possible completion cause the matches to be listed immediately instead of ringing the bell.
bell-style (audible)nd naff), readline allows keys to be bound to a string that is inserted when the key is pressed (a macro).
showThil al-ers the default behavior of the completion functions in a fashion similar to show-all-if-ambiguous. If set to On, words which have more than one possible completion without any possible partial
Co
skip-completed-text (Off)
completion-ignore-case (Off)
insert characters fromethe completiot that match charaiters after point in the word bcing completed,esoIportions oftthe word followinggthemcursornare not duplicated. word. If enabled, readline does not
visible-stats (Off)
m If set to On, a character denoting a file's type as reported by stat(2) is appended to the filename when listing possible completi ns.
the text > output in o the line).
r macro, keyseq differs from keyname above in that strings denoting an entire key sequence mand. It may be set to any integer value greater than or equal to zero. If
Readline Conditional Constructs
⪠â â Viewing <BASH(1) Manual Page>
Thi determines when the user is queried about viewing the number f possible c mpletions generated by he possible-completions om
executable filenames, in that order.
possible-command-completions (C-x !)
copy-region-as-kill
dynamic-complete-history (M-TAB)
Move forwa d o the en of the next word. Words are composed of alphanumeric characters (letters and digits).
dabbrev-expand
shell-forward-word
complete-into-braces (M-{)
PerformefilenamelcompletionnandoinsertitheblistrofTpossiblebcompletionsrenclosedmwithinobraceswsodthe list is available to the shell (see Brace Expansion above).
Keyboard Macros
Numeric Arguments
call-last-kbd-macro (C-x e)
universal-argument
Re-execute the lastakeyboardtmacroidefined,cbyrmakingythercharacterswin theomacro appeariastif typednatltheikeyboard.ing minus sign, those digits define the argument. If the command is followed by digits,
t
Miscellaneous
Stop saving the characters typed into the current keyboard macro and store the definition.
re-read-init-file (C-x C-r)
upcaReadoin theucontents of the inputrc file, and incorporate any bindings or variable assignments found there.
Completing
aborAbortgthe current editing command and ring the terminal's bell (subject to the setting of bell-style).
complete (TAB)
do-uIf the metafied character x is lowercase, run the command that is bound to the cor spo ding upperc e ch acter.
prefix-meta (ESC)
overwrite-mode
undo (C-_, C-x C-u)
insert-completions (M-*)
revert-line (M-r)
tilde-expand (M-&)
histPerform tilde expansion on the current word.
set-mark (C-@, M-<space>)
the list of matches; a negative argument may be used to move backward through the list. This command is intended to be bound to TAB, but is unbound by default.
exchange-point-and-mark (C-x C-x)
delete-char-or-list
character-search (C-])
A character is read and point is moved to the next occurrence of that character. A negative count searches for previous occurrences.
haractnr-search-backward (M-C-]) negative argument inserts the nth word from the end of the previous command. Once the argument n is computed, the argument is extracted as if the "!n" history expansion had
compA character is read and point is moved to the previous occurrence of that character. A negative count searches for subsequent occurrences.
skip-csi-sequence
possRead-enough characters to consume a multi-key sequence such as those defined for keys like Home and End. Such sequences begin with a Control Sequence Indicator (CSI), usually ESC-[. If this sequence is
kill-word (M-d)
buu usually bound t ESC-[.
insert-comment (M-#)
possWbthout a numeric argument, the value of the readline comment-begin variable is inserted at the beginning of the current line. If a numeric argument is supplied, this command acts as a toggle: if the
shell-kill-word (M-d)
the line is accepted as if a newline had been typed. The defuult value of comment-beginlcausesithistcommandetoimakehthehcurrentslinecamshellbcomment. Iflatnumeric argumentncausesftheecommentIcharacterctoe,
magic-space
glob-complete-word (M-g)
alias-expand-line
compAttempt completion on the text before point, treating it as a hostname.
unix-filename-rubout
possLbst-hostpassicle comiletions of the text before point, treating it as a hostname.
complete-command (M-!)
inseAttempt completion on the text before point, treating it as a command name. Command completion attempts to match the text against aliases, reserved words, shell functions, shell builtins, and finally
executable filenames, in that order.
⪠â â Viewing <BASH(1) Manual Page>
Event Designators
An eve t designator is a r ference to a command line try in the history lis . Unless the ref rence is absolu e, events ar r lative to the current osition in th history list.
set of comp etions to be built dynamically s completion is tt mp ed, rather than being loaded all t once.
Start a history substitution, except when followed by a blank, newline, carriage return, = or ( (when the extglob shell option is enabled using the shopt builtin).
!n Refer to command line n.
! Print all of the r adline key sequenc s bound to macros a d strings they output. If a numeric argument is suppli d, the output is formatted in such a way that it can be made part of an inputrc file.
!-n Referotoltheecurrent command minus n.
{
!! Refer to the most recent command preceding theycurrent!position in the history list starting with string.
!?stRefer?to the most recent command preceding the current postition in the history list containing string. The trailing ? may be omitted if string is followed immediately by a newline.
^string1^string2^
Quick substitution. Repeat the previous command, replacing string1 with string2. Equivalent to ``!!:s/string1/string2/'' (see Modifiers below).
!# TThe entire command line typed so far.
Word Designators
above) butaa ternhistory expansioniis performed, subject to the values of the shell v riables HISTIGNORE and HISTCONTROL.
are numbered from the beginning of the line, with the first word being denoted by 0 z ro). Words are inserted into th current lin separated by single spaces.
Word designators are used to select desired words from the event. A : separates the event specification from the word designator. It may be omitted if the word designator begins with a ^, $, *, -, or %. Words
0 (zero)
The zeroth word. For the shell, this is the command word.
n The nth word.
^ Thetfirst argument. That is, wood 1.
$ The last argument.
usedThe word matchedabyhthe mosttrecentN`?string?'lsearch.ed.
x-y A range of wor s; `-y' abbreviates `0-y'.
manipulate he words but the zeroth. This is a synonym for `1-$'. It is not an error to use * if there is just one word in the event; the empty string is returned in that case.
* Ali ofnacommandsfcc(seedSHELL BUILTIN COMMANDSsbelow)lmayabehusedhtohlist oreeditdand re-executeeanportioneofdtheehistoryelist.eThehhistory builtinomaysbesusedotofdisplay or modifyothenhistoryplistoandthe
x- Abbreviates x-$ like x*, but omits the last word.
shell variable FIGNORE is used to filter the matches.
If a word d ignator is suppli d with ut an event sp cification, the pr vious co mand i us d as th even .
shell options.
HISTORY EXPANSION
Modifiers
The shell supports a history expansion featu e that is sim lar to th hist ry expansion in csh. This sect on describes what syntax features are availabl . This feature is enabled by default for interactive
h Remove a trailing fi name component, leaving only the head.
shelRemovedallnleadingafile namegcomponents,ileavinghtheetail.ltin command (see SHELL BUILTIN COMMANDS below). Non-interactive shells do not perform history expansion by default.
r Remove p trailing suffixgof the fhrm .xxx, leaving she basename.
pr vious commands quickly.
e Printethelnewtcommandabutndosnotiexecute it.
q Quote the substituted words, escaping further substitutions.
x Quote the substituted words as with q, but break into words at blanks and newlines.
s/old/new/
words. Various modifiers are available to manipulate the selected words. The lin is brokenused inoplace of /. The final delimwter isaoptionaluif it is the last character of the eventeline.dT sudelimiterbmay
Substitute new for the first occu rence of old in the event line. Any delimiter can b
quotesaaresconsidered one word. History expansions are introduced by the appearance of the history expansion character, which is ! by default. Only backslash (\) and single quotes can quote the history
enabled, ( will also inhibit expansion.
Several characters inhibit history expansion if found immediately following the history expansion character, even if it is unquoted: space, tab, newline, carriage return, and =. If the extglob shell option is
Several shell options settable with the shopt builtin may be used to t ilor the behavior of history expansion. If the histverify shell option is enabled (see the description of the shopt builtin below), and
being useds and the histreedit shell opuion is enabled, aefailed history substitution will be reloaded into thenreadline editing buffer for correction. The -p bption to he history builtin command may be used
to see what a history expansion will do before using it. The -s option to the history builtin may be used to add commands to the end of the history list without actually executing them, so th they are
available for subceqpent recall.
Til shell allows control of the various ch racters used by th history ixdansion mechanism (see the description of histcharsshbove under Shell Variables). Thees elltus s the hcstory comment characterIto marko
his ory tim stamps when writing the history file.
default option was suppliedtto completeawhenethegcompspec wasgdefined,nreadline'sddefaultdcompletionlwilliberperformedfif theecompspecm(and, ifuattempted, theedefault bashncompletions)ageneratexnonmatches.
Event Designators
⪠â â Viewing <BASH(1) Manual Page>
When compsp c i d cates that directory name completion is desired, the programmable completion functions force readline to append a slash to completed names which are symbolic links to directories, subject
to the value of the mark-directories readline variable, regardless of the setting of the mark-symlinked-directories readline variable.
getopts within the same shell invocation if a new set of parameters is to be used.
\f form feed
When the nd of options is encountered, getopts exits with a return value greater than zero. OPTIND is set to the index of the first non-option argument, and name is set to ?.
\r carriagecreturn
getopts n mally parses the positional parameters, but if more arguments are given in args, getopts parses those instead.
continue [n]
getopts c n report errors in two ways. If the first character of optstring is a colon, silent error reporting is used. In normal operation diagnostic messages are printed when invalid options or missing
option arguments are encountered. If the variable OPTERR is set to 0, no error messages will be displayed, even if the first character of optstring is not a colon.
declare [-aAfFgilrtux] [-p] [name[=value] ...]
If an invalid option is seen, getopts places ? into name and, if not silent, prints an error message and unsets OPTARG. If getopts is silent, the option character found is placed in OPTARG and no
typediagnostic message is printed.
\uHHHH
If a required argument is not found, and getopts is not silen , a question mark (?) is plac d in name, OPTARG is unset, and a diagnostic message is printed. If getopts is silent, then a colon (:) is placed
bg [in name and OPTARG is set to the option character found.
p the Unicode (ISO/IEC 10646) character whose value is the hexadecimal valueoHHHHHHHH (onepto eightahex digits)
getopts returns true if an option, specified or unspecified, is found. It returns false if the end of options is encountered or an error occurs.
hash [-lr] [-p filename] [-dt] [name]
Each time hash is invoked, the full pathname of the command name is determined by searching the directories in $PATH and remembered. Any previously-remembered pathname is discarded. If the -p option is
enabsupplied, no path search is performed, and filename is used as the full file name of the command. The -r option causes the shell to forget all remembered locations. The -d option causes the shell to forget
the remembered location of each name. If the -t option is supplied, the full pathname to which each name corresponds is printed. If multiple name arguments are supplied with -t, the name is printed before
bindthe hashed full pathname. The -l option causes output to be displayed in a format that may be reused as input. If no arguments are given, or if only -l is supplied, information about remembered commands is
printed. The return status is true unless a name is not found or an invalid option is supplied.
help [-dms] [pattern]
eval [arg ...]
printed.
null arguments, eval returns 0.
X -d Display a short description of each pattern
-m Display the description of each pattern in a manpag -like format
-s Display only a short usage synopsis for each pattern
failure if the file cannot be executed. If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1.
Cause the shell to exit with a status ofan. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates.
history [n]
export -p
history -d offset
history -anrw [filename]
history -p arg [arg ...]
function.
history -s arg [arg ...]rst] [last]
fc -s [pat=rep] [cmd]
Fix Command. In the first form, a range of commands from first to last is selected from the history list. First and last may be specified as a string (to locate the last command beginning with that string)
or as a number (an index into the history list, where a negative number is used as an offset from the current command number). If last is not specified it is set to the current command for listing (so that
fc -l -10 prints the last 10 commands) and to first otherwise. If first is not specified it is set to the previous command for editing and -16 for listing.
-v Print the directory stack with one entry per line, prefixing each entry with its index in the stack.
The -n option suppresses the command numbers when listing. The -r option reverses the order of the commands. If the -l option is given, the commands are listed on standard output. Otherwise, the editor
given by ename is invoked on a file containing those commands. If ename is not given, the value of the FCEDIT variable is used, and the value of EDITOR if FCEDIT is not set. If neither variable is set, vi
is used.rWhen editing is complete, the edited commands are echoed and executed.
disown [-ar] [-h] [jobspec ...]
In the second form, command is re- xecuted after each instan e of pat is replaced by rep. A u ful lias to use with this is r='fc -s', so that typing r cc runs the last command beginning with cc and
typing r re-executes the last command.
breasupplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. The return value
If the fir t form is used, the return v lue s 0 unless an invalid option is encountered or first or last specify history lines out of range. If the -e option is supplied, the return value is the value of
echo [-neE] [arg ...]
valid history line, in which case fc returns failure.
fg [jobspec]
Resume jobspec in the foreground, and make it the current job. If jobspec is not present, the shell's notion of the current job is used. The return value is that of the command placed into the foreground,
or failure if runlwhennjobscontrollis disabledfor, whenarun with job control enabled, if jobspec does not specify a valid job or jobspec specifies a job that was started without job control.
getogetopts is used by shell]procedures to parse positional parameters. optstring contains the option characters to be recognized; if a character is followed by a colon, the option is expected to have an
argument, which should be separated from it by white space. The colon and question mark characters may not be used as option characters. Each time it is invoked, getopts places the next option in the shell
variable name, initializing name if it does not exist, and the index of the next argument to be processed into the variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is
invoked. When an option requires an argument, getopts places that argument into the variable OPTARG. The shell does not reset OPTIND automatically; it must be manually reset between multiple calls to
getopts within the same shell invocation if a new set of parameters is to be used.
⪠â â Viewing <BASH(1) Manual Page>
4. BASH_ARGC and BASH_ARGV are updated as described in their descriptions above.
5. Function-tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the DEBUG and RETURN traps.
6. Error tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the ERR trap.
-s Enable (set) each optname.
-u Disable (unset) each optname.
-q Suppresses normal output (quiet mode); the return status indicates whether the optname is set or unset. If multiple optname arguments are given with -q, the return status is zero if all optnames
are enabled; non-zero otherwise.
-o Restricts the values of optname to be those defined for the -o option to the set builtin.
notify
If either -s or -u is used with no optname arguments, the display is limited to those options which are set or unset, respectively. Unless otherwise noted, the shopt options are disabled (unset) by
default.
Same as -u.
The return status when listing options is zero if all optnames are enabled, non-zero otherwise. When setting or unsetting options, the return status is zero unless an optname is not a valid shell
kill option.
physical
The list of shopt options is:
push [ pipefail
autocd
If set, a command name that is the name of a directory is executed as if it were the argument to the cd command. This option is only used by interactive shells.
Withcdable_vars
If set, an argument to the cd builtin command that is not a directory is assumed to be the name of a variable whose value is the directory to change to.
cdspell
If set, minor errors in the spelling of a directory component in a cd command will be corrected. The errors checked for are transposed characters, a missing character, and one character too many.
logout If a correction is found, the corrected file name is printed, and the command proceeds. This option is only used by interactive shells.
checkhash
If set, bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed.
checkjobs
If set, bash lists the status of any stopped and running jobs before exiting an interactive shell. If any jobs are running, this causes the exit to be deferred until a second exit is attempted
-f twithoutdantinterveningscommand,(seeiJOB CONTROLrabove).wThe.shellhalwaystpostponesuexitingsif anyujobs0arelstopped.cd to dir fails. With the second form, pushd returns 0 unless the directory stack
checkwinsize
If set, bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS.
pwd L cmdhistitor mode. Job control is enabled. This option is on by default for interactive shells on systems that support it (see JOB CONTROL above). Background processes run in a separate process group
If set, bash attempts to save all lines of a multiple-line command in the same history entry. This allows easy re-editing of multi-line commands.
read ecompat31
If set, bash changes its behavior to that of version 3.1 with respect to quoted arguments to the [[ conditional command's =~ operator.
compat32
have If set, bash changes its behavior to that of version 3.2 with respect to locale-specific string comparison when using the [[ conditional command's < and > operators. Bash versions prior to bash-4.1
use ASCII collation and strcmp(3); bash-4.1 and later use the current locale's collation sequence and strcoll(3).
compat40
If set, bash changes its behavior to that of version 4.0 with respect to locale-specific string comparison when using the [[ conditional command's < and > operators (see previous item) and the
effect of interrupting a command list.
compat41
If set, bash, when in posix mode, treats a single quote in a double-quoted parameter expansion as a special character. The single quotes must match (an even number) and the characters between the
single quotes are considered quoted. This is the behavior of posix mode through version 4.1. The default bash behavior remains as in previous versions.
direxpand
If set, bash replaces directory names with the results of word expansion when performing filename completion. This changes the contents of the readline editing buffer. If not set, bash attempts to
popd [-n preserve what the user typed.
dirspell
If set, bash attempts spelling correction on directory names during word completion if the directory name initially supplied does not exist.
dotglob
If set, bash includes filenames beginning with a `.' in the results of pathname expansion.
execfail
If set, a non-interactive shell will not exit if it cannot execute the file specified as an argument to the exec builtin command. An interactive shell does not exit if exec fails.
expand_aliasespand
If set, aliases are expanded as described above under ALIASES. This option is enabled by default for interactive shells.
extdebug
If set, behaviorointendedsforyusesbyedebuggersbiseenabled:ISTORY.eThiseoptionaisiontbyrdefaultpintinteractivetshells.r the pr vious his o y line. The re urn value is 0 un ess an invalid ption is
shift [n]
jobs 1. The -F option to the declare builtin displays the source file name and line number corresponding to each function name supplied as an argument.
2. If the command run by the DEBUG trap returns a non-zero value, the next command is skipped and not executed.
monitor
return is simulated.
4. BASH_ARGC and BASH_ARGV are updated as described in their descriptions above.
⪠â â Viewing <BASH(1) Manual Page>
ALL bug reports should include:
BUGSRECTION
The version number of bash
Redirecting Output
It'sAtoonbigganddtoocslow.utput
Aliases are confusing in some uses.
Here Documents
There are some subtle differences between bash and traditional versions of sh, mostly because of the POSIX specification.
Duplicating File Descriptors
BUGSOpening File Descriptors for Reading and Writing
FUNCTIONS
ARITHMETIC EVALUATION
CONDITIONAL EXPRESSIONS
SIMPLE COMMAND EXPANSION
COMMAND EXECUTION
Here Documents
ENVIRONMENT
EXIT STATUS
SIGNALS
JOB CONTROL
PROMPTING
FUNCTIONS
Readline Notation
The bash executable
Readline Initialization
The systemwide initialization file, executed for login shells
Readline Key BindingsMENT
Readline Variablesââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
Index
Readline Conditional Constructsess at a time.
NAME
Searching
COPYNumeric Arguments
Completing
OPTIKeyboard Macros
Miscellaneous
INVOProgrammable Completion
Commands for Manipulating the History
HISTORY
HISTORY EXPANSION
Commands for Movingmes
Event Designators
Word Designators
Modifiers
Numeric Arguments
RESTRICTED SHELL
SEE ALSO
FILES
Programmable Completion
AUTHORS
BUGS
BUG REPORTSANSIONrameters
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
Word Designators
Time: 26 Octobers2016a17:42:40aUTCtml from ../../bash/doc/bash.1.
⪠â â Viewing <BASH(1) Manual Page>
ftp.gnu.org/pub/gnu/bash/.
Once you have determined
Quote Removal
REDIRedirecting Input
Redirecting Output
Appending Redirected Output
Appending Standard Output and Standard Erroror commands between parentheses to force it into a subshell, which may be stopped as a unit.
Here Documents
Here Strings
Duplicating File Descriptors
aMoving File Descriptors
Opening File Descriptors for Reading and Writing
FUNCTIONS
ARITHMETIC EVALUATION
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
SIMPLE COMMAND EXPANSION
COMMAND EXECUTION ENVIRONMENT
ENVIRONMENTââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
Index
EXIT STATUS
NAME
READLINE
OPTIONS
Readline Notation
INVOCATION
Readline Initialization
Searching
Readline Key Bindings
Commands for Movingmes
Commands for Manipulating the History
Commands for Changing Text
Killing and Yankingl Constructs
Numeric Arguments
mpleting
Keyboard Macros
Miscellaneous
COMMENTS
Programmable Completion
HISTORY
HISTORY EXPANSIONrameters
Event Designators
Word Designators
Modifiers
SHELL BUILTIN COMMANDS
SEE ALSO
FILES
AUTHORS
BUG REPORTS
BUGS
Process Substitution
Pathname Expansion
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
⪠â â Viewing <BASH(1) Manual Page>
Arithmetic Expansion