Sie sind auf Seite 1von 7

BA SH REFERENCE

 

CONTENTS

Aliasing ArithmeticEvaluation Arrays BraceExpansion Built-In Commands CommandLineA rguments CommandSubs titution

6

8

13

6

16

3

8

ConditionalExpress ions ControlCommands Definitions ExecutionOrder FieldSplitting Functions H istorySubstitution Input/Output Invocation andStartup JobIds and JobControl

15

14

2

13

8

12

5

13

3

24

Options

Tos et

22

Options

Tos hopt

23

Options Totest Patterns Pre-DefinedVariables Process Substitution Prompting Quoting Readline ReadlineDirectives ReadlineKeyBindings ReadlineVariables Restrictedbash Signals and Traps S pecialCharacters TildeSubstitution VariableAss ignment VariableNames VariableSubstitution

21

9

10

8

4

6

25

25

25

26

2

13

24

6

9

9

7

This referencecard w as w ritten byA rnold Robbins .W e thankChet Ramey(bashís m aintainer)forhis help.

OTHER SS C PRODUCTS:

SpecializedSystemsConsultants,Inc. (206)FOR-UN IX/(206)782-7733

FAX:(206)782-7191

E-mail:sales@ssc.com URL:http://w w w .ssc.com

LinuxJournaló ThePremierLinuxMagazine TechnicalBooks andCDs SA MBA :IntegratingUNIX andW indow s ShellTutorials,KSHReference VI&EmacsReferences,VITutorial

© Copyright1999SpecializedSystems Consultants,Inc., P.O.Box55549,Seattle,W A 98155-0549. A llRights Reserved.

1

 

DEFINITIONS

This carddes cribes vers ion 2.02.0ofbash.

Severaltypefacesareusedtoclarifythemeaning:

SerifaBoldis us edforcomputerinput.

Serifa Italic is us ed to indicate us er input and for s yntacticplaceholders ,s uchas variableorcmd.

SerifaRom an is us edforexplanatorytext.

blank

blank

ormorespaces and/ortabcharacters.Inaddition,

w

ords are term inated by any of the follow ing

characters:

;&()|<>s pacetabnew line

 

command

w ords.

list

list pipelines .Can beseparatedby ; , & ,

pipelines.Can beseparatedby;,&,

&&,||and optionallybeterm

inatedby;,&.

n name bash language. Keyw ords are s pecial only after a ; or new

n

name

bash language.

Keyw ords are s pecial only after a ;or new line,after anotherkeyw ord,andincertainothercontexts.

keyw ord

pat bashpattern.SeePatterns.

pat bash pattern.See Patterns . pipeline

pipeline

byapipe(|).

string

substitution

string substitution

command line w ith different text,e.g.,replacing a variable w ith its value.bash performs many s ubs titutions.This cardlists them in theordertheyare performed.

word

word

necessaryifit contains s pecialcharacters.

RESTRIC TED bash

If bash is invokedas rbash ,orw iththe option,itis restricted .Thefollowingactionsarenotallowedina restrictedshell:
If bash is invokedas rbash ,orw iththe option,itis restricted .Thefollowingactionsarenotallowedina restrictedshell:

Ifbashis invokedas rbash,orw iththe option,itis restricted.Thefollowingactionsarenotallowedina restrictedshell:

changingdirectoryw ithcd settingoruns etting$S H ELL or$PA TH us ingpathnames forcommands thatcontain / us ingapathnamethatcontains /forthe.command importingfunctionsfromtheenvironment pars ing$S H ELLOPTS ats tartup redirectingoutputwithanyof>,>|,<>,>&,&>,or>> us ingexectorun adifferent command addingordeletingbuilt-incommands w ithenable us ing to bypass ares tricted$PA TH us ingset+rorset+o res tricted

addingordeletingbuilt-incommands w ith enable us ing to bypass ares tricted $PA TH us ing set+r or
addingordeletingbuilt-incommands w ith enable us ing to bypass ares tricted $PA TH us ing set+r or
addingordeletingbuilt-incommands w ith enable us ing to bypass ares tricted $PA TH us ing set+r or
Theserestrictions areineffect after executingall startupfiles,allow ingtheauthorofthestartupfiles full controlin settingup
Theserestrictions areineffect after executingall startupfiles,allow ingtheauthorofthestartupfiles full controlin settingup

Theserestrictions areineffectafterexecutingall startupfiles,allow ingtheauthorofthestartupfiles full controlin settingup therestrictedenvironment.(In practice,restrictedshellsarenotusedmuch,asthey aredifficulttosetupcorrectly.)

ErrorReporting

Ifyoufindanerrorinthisreferenceandarethefirstto reportit,w ew illsend youafreecopyofanyofour
Ifyoufindanerrorinthisreferenceandarethefirstto reportit,w ew illsend youafreecopyofanyofour

Ifyoufindanerrorinthisreferenceandarethefirstto reportit,w ew illsend youafreecopyofanyofour references.Pleasewrite,orsendelectronicmailto bugs@ssc.com.

2

COMMAND LINEARGUMENTS

bashaccepts theoneletteroptions to set,and the additionaloneletterandGNU -stylelongoptions s how n below.

$bash[options][args]

 

cmdends ends option process ing option process ing

ends

ends

option process ing option process ing

execute cmd (default reads command from file named in

 

firstentryofargsandfoundvia

pathsearch)

printalldoublequotedstringsnamed in   firstentryof args andfoundvia pathsearch)   thatareprecededbya $ to stdout . This implies ,

 

thatareprecededbya$to

stdout. This implies

, no

commands areexecuted setinteractivemode setrestrictedmode read commands from stdin (default) sameas ,butoutputin GNU gettext format sameas displayahelpmessageandexit successfully actlikealoginshell stdin (default) sameas ,butoutputin GNU gettextformat sameas displayahelpmessageandexit successfully actlikealoginshellareexecuted setinteractivemode setrestrictedmode read commands from stdin (default) sameas ,butoutputin GNU gettext

do not us ethereadlinelibrary to read commands w hen interactive

successfully actlikealoginshell do not us ethe readline library to read commands w hen interactive
successfully actlikealoginshell do not us ethe readline library to read commands w hen interactive
successfully actlikealoginshell do not us ethe readline library to read commands w hen interactive
successfully actlikealoginshell do not us ethe readline library to read commands w hen interactive

do not read any of theus ethe readline library to read commands w hen interactive   initialization files. See InvocationAndStartup

 

initialization

files.

See

InvocationAndStartup,below do not read ò/.bashrc if

interactive.SeeInvocationAnd Startup,below

follow theIEEEPOSIX 1003.2ò/.bashrc if interactive.See InvocationAnd Startup ,below   s tandard file use file instead of ò/.bashrc

 

s

tandard

fileuse file instead of ò/.bashrc if interactive

use fileinstead ofò/.bashrc if interactive

sameas sameas print version information on stdout andexitsuccessfully
sameas sameas print version information on stdout andexitsuccessfully

sameas sameas print version information on stdoutandexitsuccessfully

 

INV OCATION AN D S TARTUP

Therearefivew ays thatbashruns:normalinteractive, normal non-interactive,as sh,in POSIX mode,or invokedviarshd.

1.Normal interactive: Login s hells run commands in /etc/profile.Thefirstofò/.bash_profile,ò/.bash_login, and ò/.profilethat is found is executed.This s tageis skippedif is used.

ò/.bash_profile , ò/.bash_login , and ò/.profile that is found is executed.This s tageis skippedif is used.

Upon logout,bashruns ò/.bas h_logoutifitexists.

Interactivenon-loginshells executeò/.bashrc,ifit

exists.The

ifile optionchangesthefilethatis

ifileoptionchangesthefilethatis

used.

2.Normal non-interactive:Non-interactive shells do variable,command,and arithmetics ubstitution on the value of $BA S H _ENV ,and if the res ult nam es an existingfile,thatfileis executed.

3

INV OCATION AN D S TARTUP(continued)

3.Invoked as sh: Interactive login s hells read and execute/etc/profileandò/.profileiftheyexist.These files are skipped if is used.Interactive

login s hells read and execute /etc/profile and ò/.profile iftheyexist.These files are skipped if is used.Interactive

hells expand $EN V and executethat file ifit exis ts. Non-interactive s hells do not read anystartup files.

s

A

fterthestartupfiles areexecuted,bashenters POSIX

mode.

4.POSIX mode:W hen startedw ith

4.POSIX mode:W hen startedw ith

,interactive

hells expand $EN V and execute the given file.No otherstartupfilesareread.

s

5.Invokedviarshd:Ifrunfromrshdandnotinvokedas

sh,bashreads ò/.bashrc.The

optionskips this

step,andthe optionchangesthefile,but rshd usuallydoes notpass theseoptions on totheshellit invokes.

step,andthe optionchangesthefile,butrshd usuallydoes notpass theseoptions on totheshellit invokes.

If$SHELLOPTSexistsintheenvironmentatstartup,

bashenables thegivenoptions.

 

PROMPTING

W hen interactive, bash displays the primary and

s

econdary prompt s trings, $PS1 and $PS2. bash

expands thefollow inges cape sequences in thevalues ofthes es trings.

\a an A SC IIBEL character(octal07) \d thedateinëëWeekdayMonthDayííformat \e anASCIIescapecharacter(octal033) \h thehostnam eup tothefirs t dot(.) \H thefullhostname \n anew line

\r acarriagereturn \s thenam eofthes hell(bas enam eof$0)

\t

thetim ein 24-hourH H :MM:SS form at

\T thetim ein 12-hourH H :MM:SS form at \u theuserís username \v theversionofbash(e.g.,2.02) \V theversionandpatchlevelofbash(e.g.,2.02.0) \w thecurrentworkingdirectory \W thebasenam eofthecurrentw orkingdirectory \! thehistorynumberofthis command \# thecommandnumberofthis command \$ a#iftheeffectiveUIDis0,otherwisea$ \@ thetimein12-houram/pmformat \\ abackslash \nnn thecharactercorrespondingtooctalvaluennn \[ startasequenceofnon-printingcharacters \] endasequenceofnon-printingcharacters

The historynumberis the numberofthe comm and in thehistorylis t,w hichmayincludecommands res tored from the history file.The command number is the number of this command starting from the first commandrun bythecurrentinvocation ofthes hell.

Thedefaultvalueof PS1 is ëë íí.

ThedefaultvalueofPS1is ëë íí.

 

4

 

H ISTORY S UBSTITUTION

 

H

istoryexpansion is similarto cshís.It is enabledby

default in interactive s hells. H istory expansion happens beforetheshellbreaks theinputintow ords, althoughquotingis recognizedandquotedtextis

treatedas onehistoryëëw ordíí.

 

H

istory s ubs titution is performed on history events,

hichcons is t ofan eventdes ignator(w hichprevious line tostartw ith),aw orddesignator(w hichw ordfrom that

w

line to use,starting w ith zero), and one or more optionalmodifiers(whichpartsofthewordstouse). Colons separatethe three parts,although the colon

betweentheeventdesignatorandworddesignator

maybeomittedwhentheworddesignatorbeginswith

à,$,*,,or%.Eachmodifierisseparatedfromthenext onewithacolon.Thehistcharsvariablespecifiesthe start-of-historyand quicksubstitution characters,and als othecomment characterthatindicates thattherest ofalineis acomment.Theprevious commandis the defaulteventifnoeventdesignatorissupplied.

Theeventdesignatorsare:

 

!

startahistorys ubs titution

!n

commandlinen

n
n

currentlineminus n(nprevious)

!!

theprevious command

 

!str

mos t recent command linestartingw ith str

!?str[?]

mos

trecentcommandlinecontainingstr

!#

theentirecommandlinetypeds ofar

àoldànew à quicks ubstitution:repeat las t command changingoldto new

Theworddesignatorsare:

 

0

thezeroíthw ord(command name)

n

wordn

 

à

thefirs targum ent,i.e.,w ordone

$

thelastargument

 

%

thewordmatchedbythemostrecent !?str?search

xy

wordsxthroughy. isshortfor

words x through y . isshortfor words1throughthelast(like )
words x through y . isshortfor words1throughthelast(like )

words1throughthelast(like )

*

n*

wordsnthroughthelast(liken )

n

w

ords nthroughthenexttolast

Themodifiersare:

e

rem oveallbutthesuffixofafilename

g

makechanges globally,usewiths modifier,below

h

rem ove the las t part of a filenam e, leavingtheëëheadíí

p

printthecommandbutdonotexecuteit

q

quotethegeneratedtext

 

r

rem ovethelas t s uffixofafilename

s/old/new / s ubs titute new for old in the text.A ny delimiter may be used.A n & in the replacementmeansthevalueofold.With emptyold,uselastold,orthemostrecent !?str?searchiftherewasnopreviousold

t

rem oveallbut thelas t partofafilenam e,

leavingtheëëtailíí

 

x

quotethegeneratedtext,butbreakinto

w

ords atblanks andnew line

&

repeatthelastsubstitution

 

5

 

QUOTING

 

\c

 

quotes inglecharacterc

 

`

`

"

"

olds tylecommands ubs titution text treatedas as ingleargument,double quotes removed;variable,commandand arithmeticsubstitutions performed; use\to quote$,\,`,and"

$"

 

"

like"

",butlocaletranslationdone

¥

¥ text treatedas as ingleargument,s ingle

¥

quotesremoved;textbetweenquotes leftalone,cannotinclude¥ text treatedas as ingleargument,$and s inglequotes removed;no s ubs titutions performed;ANSICandadditional escapesequences processed:

 

\a alert(bell) \b backspace \f formfeed \n new line

\v

verticaltab

 

\ddd octalvalueddd

\xhhh hexvaluehhh

 

\\

backs lash

\r carriagereturn \e

escape,notinANSIC

\t horizontaltab

 
 

ALIASING

 

alias name=value

 

A

lias es are expanded w hen a command is

read,not

w

hen executed.A lias nam es can contain

any non-

s

pecialcharacter,not jus t alphanumerics ,except for=.

A

lias expansion is doneon thefirstw ordofacommand.

Ifthelastcharacterofthereplacementtextisablank,

then thenextw ordin thecommandlineis checkedfor alias expans ion.A lias es can even be used to redefine

s

hellkeyw ords ,butnotin POSIX mode.

 

BRA CE EXPAN S ION

Brace expansion is similar to csh ís.A w ord must contain atleast oneunquotedleftbraceandcommato be expanded.
Brace expansion is similar to csh ís.A w ord must contain atleast oneunquotedleftbraceandcommato be expanded.

Brace expansion is similar to cshís.A w ord must contain atleast oneunquotedleftbraceandcommato be expanded.bash expands the comma-separated items in order,the result is not sorted. Brace expans ions maybenested.Forexam ple:

$ m kdir/us r/{gnu,local}/{src,bin,lib}

$m kdir/us r/{gnu,local}/{src,bin,lib}

in order,the result is not sorted. Brace expans ions maybenested.Forexam ple: $ m kdir/us r/{gnu,local}/{src,bin,lib}
 

TILDE SUBSTITUTION

ò

òuser

substitute$HOME substituteuseríshomedirectory substitute$PWD substitute$OLDPWD

ò+

íshomedirectory substitute $PWD substitute $OLDPWD ò+ ò n s ubs titute ${D IRSTA C K[ n

òn

s ubs titute ${D IRSTA C K[n]}.A leading + or is allow ed:negative values count from theendofthestack

Tildesubstitutionhappensafteraliasexpansion.Itis doneforwords thatbeginwithòandforvariable assignment.

Invariableassignments,itis alsodoneaftera:in the value.Tildesubstitutionis doneas partofword

expans ion.This means for${nameopw ord},w ord w illbe

checkedfortildesubstitution,butonlyiftheoperation

requiresthevalueoftheright-handside.

 

6

 

VA RIA BLESUBSTITUTION

 

$name

referencetos hellvariablename

${name}

us ebraces todelimits hellvariablename

${name w ord} us evariablenameifset,els eusew ord

${name=w ord} as abovebutals os etnametow ord

${name?w ord}

 

usenameifset,otherw is eprintw ordand exit(interactiveshellsdonotexit) ${name+w ord} usew ordifnameis s et,otherw is euse nothing ${name[n]} elementn in arrayname

${#name}

lengthofshellvariablename

${#name[*]} numberofelements ${#name[@]} numberofelements

in arrayname

in arrayname

${name#pat} removes hortes tleadings ubs tring ofnamethatmatches pat ${name##pat} removelonges tleadings ubs tring ofnamethatmatches pat ${name% pat} removes hortes ttrailings ubs tring ofnamethatmatches pat

${name%%pat}

 

removelongesttrailings ubs tring ofnamethatmatches pat

${name:start} ${name:start:length} lengthcharacters ofnamestartingat

 

start(countingfrom0);userestof

valueifnolength.N egativestart counts from theend.Ifnameis *or@ oran arrayindexedby*or@,start andlengthindicatethearrayindexand countofelements.startandlengthcan bearithmeticexpressions ${name/pattern/string} valueofnamew ithfirstmatchofpattern replacedwithstring ${name/pattern} valueofnamew ithfirstmatchofpattern deleted ${name//pattern/string} valueofnamew itheverym atchof patternreplacedwithstring ${name/#pattern/string} valueofnamew ithmatchofpattern replacedwithstring;matchmustoccur atbeginning ${name/%pattern/string} valueofnamew ithmatchofpattern replacedwithstring;matchoccursatend

Note:for ,=,?,and +,us ing name:ins tead ofname tes ts w hethernameis s et and non-NU LL;us ing name tes ts onlyw hethernameis s et.

For#,##,% ,%%,/,//,/#,and /%,w hen nameis *or@ or an array indexed by * or @,the s ubs tring or substitutionoperationisappliedtoeachelement.

7

 

ARITHMETIC EVA LUATION

 

Arithmeticevaluationis donewiththeletbuilt-in

command, the ((

))

command and the $((

))

expans ion forproducingtheres ultofan express ion.

A

llarithm eticus es longintegers .Use

to get

to get

integervariables.Integerconstants looklike[base#]n

w

herebaseis adecimalnumberbetw een tw o and 64,

andnis in thatbase.Thedigits are0-9,a-z,A -Z,_and @.A leading0or0xdenoteoctalorhexadecimal.

The follow ing operators bas ed on C ,w ith the same precedenceandassociativity,areavailable.

 

unaryplusandminus

logicalandbitw is enegation exponentiation(notin C) multiply,divide,modulus addition,subtraction leftshift,rightshift

 

**

*/%

<< >>

< <= > >= comparisons

 

==!=

equals,notequals

&

bitw iseAND

à

bitw is eXOR

|

bitw is eOR logicalAND,shortcircuit logicalOR,s hortcircuit in-lineconditional

 

&&

||

?:

hortcircuit in-lineconditional   && || ?:   assignmentoperators Inside let , (( )), and $(( )),
 

assignmentoperators

Insidelet,(( )),and$(( )),variablenamesdonotneed a$togettheirvalues.

COMMAN D SU BSTITUTION

$(command) new form `command` oldform

 

Run command,s ubs titute the res ults as arguments. Trailing new lines are rem oved.Characters in $IFS separatew ords (s ee Field Splitting).The new form is preferredforsimplerquotingrules.

$((expression))arithmeticsubstitution

 

Theexpression is evaluated,andtheresultis us edas an argumenttothecurrent command.

PROCESS SUBSTITUTION

cmd<(list1)>(list2)

cmd <( list1 )>( list2 )
cmd <( list1 )>( list2 ) Runs list1 and list2 asynchronous ly,w ith stdin and stdout
Runs list1 and list2 asynchronous ly,w ith stdin and stdout respectivelyconnectedviapipes us ingfifos or files
Runs list1 and list2 asynchronous ly,w ith stdin and stdout respectivelyconnectedviapipes us ingfifos or files

Runs list1and list2 asynchronous ly,w ith stdin and stdout respectivelyconnectedviapipes us ingfifos or files in /dev/fd.Thes efilenam es becom eargum ents to cmd,w hichexpects toreadits first argument and w rite its s econd.This onlyw orks ifyouhave/dev/fd orfifos.

FIELD S PLITTING

Quoted text becomes one w ord. Otherw is e,

occurrences ofanycharacterin $IFS separatew ords.

Multiplewhitespacecharactersthatarein$IFSdonot

delimitemptywords,whilemultiplenon-whitespace

charactersdo.When$IFSis notthedefaultvalue,

sequences

of leading and trailing $IFS w hites pace

characters areremoved,andprintablecharacters in $IFS surrounded by adjacent $IFS w hitespace characters delim it fields .If$IFS is N ULL,bash does

notdofieldsplitting.

 

8

 

PATTERNS

?

m atchs inglecharacterin filename

*

[chars]

m atch0orm orecharacters in filename matchanyofchars (pairseparatedbya matches arange) matchanyexceptchars matchanyexceptchars

[!chars]

chars]

If

the extglob option to s hopt is s et,the follow ing

extendedmatchingfacilities maybeused.

 

?(pat-list) optionallym atchanyofthepatterns *(pat-list) match0ormoreofanyofthepatterns +(pat-list) match1ormoreofanyofthepatterns @(pat-list) matchexactly1ofanyofthepatterns !(pat-list) matchanythingbutanyofthepatterns

pat-listis alistofoneormorepatterns separatedby|.

ThePOSIX [[=c=]]and[[.c.]]notations forsame-w eight characters andcollatingelementsareaccepted.The notation [[:class :]]defines characterclass es:

 

alnum

alphanumeric low er low er-case

alpha alphabetic

print printable

 

blank s paceortab

punct punctuation

cntrl

control

space whitespace

digit

decimal

upper upper-case

graph non-spaces

xdigit hexadecimal

Threes hoptoptions affectpattern matching.

 

dotglob

includefiles w hos enam es begin w ith.

nocaseglob ignorecas ew hen matching

 

nullglob

removepatterns thatdonítmatch

W

hen expanding filenam es, .and

are

ignored,

filenam es m atchingthepatterns in $G LOBIGNO RE are

als o ignored and a leading .mus t be s upplied in the pattern to m atch filenam es that begin w ith

H

ow ever,setting G LOBIGNORE enables the dotglob

option.Include.*in GLOBIGNOREtogetthedefault behavior.

VARIABLENAMES

Variable nam es are m ade up of letters , digits and unders cores .Theymaynot
Variable nam es are m ade up of letters , digits and unders cores .Theymaynot

Variable nam es are m ade up of letters , digits and unders cores .Theymaynot startw ithadigit.Thereis no limiton thelengthofavariablename,and thecase oflettersissignificant.

VARIA BLEASSIGNMENT

A

ss ignments to integer variables undergo arithmetic

evaluation.Variable assignments have one of the follow ingforms.

name=w ord s etnametow ord name[index]=w ord

 

name=(w ord

setelementindexofarraynametow ord ) setindexedarraynametow ords

name=([num]=w ord

)

 
 

setgiven indices ofarraynametow ords

9

PRE-DEFINED VARIA BLES

$n us epos itionalparam etern,n 9 ${n} us epos itionalparam etern $* allpositionalparameters $@ allpositionalparameters "

"$*" equivalentto"$1$2

itionalparam eter n $* allpositionalparameters $@ allpositionalparameters " "$*" equivalentto "$1$2

"$@" equivalentto "$1""$2" $# numberofpos itionalparameters optionstoshellorbyset $? valuereturnedbylas tcommand $$ process numberofcurrent s hell $! process numberoflast background cmd $_ nam e of program in environm ent at startup. Value of las t pos itional argumentin las t command.Name of changedmailfilein$MAILPATH $auto_res ume enables us e of single-w ord commands to matchs toppedjobs for foregrounding.W ithavalueofexact, thewordmustexactlymatchthe command used tos tartthejob.W ith avalueofs ubs tring,thetypedw ord can beas ubs tringofthecommand, like%?string $BA SH fullfilenam eusedtoinvokebash $BA SH _ENV in normalnon-interactive s hells only, value is variable, command and arithmetic substituted for path of startup file (See Invocation And Startup) $BA SH _VERSION thevers ion ofbash $BA SH _V ERS IN FO[0] the major vers ion number (release) $BA SH _V ERS IN FO[1] the minor vers ion number (version) $BA S H _V ERS IN FO[2] thepatchlevel $BA S H _V ERS IN FO[3] thebuildvers ion $BA SH _V ERS IN FO[4] thereleas es tatus $BA SH _V ERS IN FO[5] sameas $MA C H TYPE $C D PA TH s earchpathforcdcommand $D IRSTA C K[*] array variable containing the pus hd andpopddirectorystack $ENV ininteractivePOSIXmodeshells,or w heninvokedas sh,valueis variable, commandandarithmetics ubstituted forpathofstartupfile $EUID theeffectiveuserid(readonly) $FCED IT defaulteditorforthefccommand(no defaultvalue) $FIGNO RE colon-separatedlis t ofsuffixes giving the set offilenam es to ignore w hen doing filenam e com pletion us ing readline $G LOBIGNO RE colon-separatedlis tofpatterns giving the set offilenam es to ignore w hen doingpattern matching $G ROUPS[*] readonlyarrayvariablew iththelist ofgroups theus erbelongs to $histchars characters that control csh-style history (default: !à#). See H istory Substitution

theus erbelongs to $histchars characters that control csh -style history (default: !à# ). See H istory

10

PRE-DEFINED VARIA BLES (continued)

$H ISTC MD history number of the current command $H ISTCONTROL w ithavalueofignorespace,do not enterlines thatbeginwithspaces intothehistoryfile.W ithavalueof ignoredups,donotenteralinethat m atches the previous line. Use ignorebothtocombinebothoptions $H ISTFILE w herecommandhistoryis s tored

$H ISTFILES IZE

maximum numberoflines to keep in

$H ISTFILE $H ISTIGNORE colon-separatedlistofpatterns;ifthe currentlinematchesanyofthem,the lineis notenteredin thehistoryfile. & represents the last history line. Patterns mus tmatchthew holeline $H IS TSIZE number of previous commands to keepavailablew hilebashis running $H OME homedirectoryforcd command and valueusedfortildeexpansion $H OSTFILE filein format of/etc/hosts to us efor hostnam ecompletion $H OS TNA ME nam eofthecurrenthost $H OSTTYPE stringdescribingthecurrenthost $IFS fields eparators (s pace,tab,new line) $IGNO REEOF for interactive s hells,the number of consecutive EOFs that must be enteredbeforebashactuallyexits $IN PUT RC nam e of readline startup file, overridesò/.inputrc $LANG nam eofcurrentlocale $LC_A LL current locale; overrides $LANG and other$LC_variables

$LC_COLLA TE current locale for character collation, includes sorting results of filename expansion $LC_CTYPE current locale for character class functions(seePatterns)

$LC_MESSA G ES

current locale for trans lating $"

"

strings $LIN ENO linenumberofline beingexecutedin scriptorfunction $MA C H TYPE a string in GNU cpu-company-sys tem format des cribing the machine runningbash $MA IL nam eofamailfile,ifany $MA ILCH ECK checkfor mail every n s econds (60 default) $MA ILPA TH filenam es to checkfor new m ail;us es :separator;filenamemaybe follow ed by ?message; $_ in message is m atched m ail file nam e.Overrides $MAIL $OLDPWD previousworkingdirectory $OPTA RG valueoflastargumentprocessedby getopts $OPTERR if set to 1,display error messages

 

fromgetopts(default:1)

$OPTIND indexoflas t argument processed by getopts

11

 

PRE-DEFINED VARIA BLES (continued)

 

$OS TYPE

$PA TH

string describing the operating s ystem running bash commands earchpath arrayvariablecontainingexit status values from processes inthemostrecentlyexecuted foregroundpipeline process idofshellís parent

$PIPESTATUS[*]

$PPID

$PROMPT_CO MMAND comm and to run before each primaryprompt

$PS1

primary prompt string ( s econdaryprompts tring(>) select command prompt string(#?) tracingpromptstring(+) currentworkingdirectory set eachtimeitís referenced,

)
)

$PS2

$PS3

$PS4

$PWD $RA N DOM

eachtimeitís referenced, ) $PS2 $PS3 $PS4 $PWD $RA N DOM $REPLY set by the select and

$REPLY

set by the select and read commands numberofs econds s inces hell invocation nam eofthis s hell colon-separated list of the enabledshelloptionsforset

incremented byoneforeach sub-bash format string for output of time keyw ord. Special constructsintroducedby%.

%[p][l]R elapsedsecs %[p][l]U userCPUsecs

$S ECO NDS

$S H ELL $SH ELLOPTS

$SH LVL

$TIMEFORMA T

%[p][l]S

system C PU secs CPU percentage literal%

%P

%%

Optionalp gives theprecis ion, thenumberofdigits afterthe decimalpoint;itmustbe betw een 0and 3.Optional l produces alongerformat,in theform MMmSS.FFs

$TMOUT number of s econds to w ait during prompt before terminating

$UID

therealuserid(readonly)

FUNCTIONS

Functions run in thesameprocess as thecallingscript, andsharetheopenfilesandcurrentdirectory.They access theirparameters
Functions run in thesameprocess as thecallingscript, andsharetheopenfilesandcurrentdirectory.They access theirparameters

Functions run in thesameprocess as thecallingscript, andsharetheopenfilesandcurrentdirectory.They access theirparameters likeascript,via$1,$2 andso on.$0does not change.return maybe used ins ide a function or.script.Functions sharetraps w iththe parent script,except forDEBUG .Functions maybe recurs ive,and mayhavelocalvariables ,declaredus ing declare,local,ortypeset.Functionsmaybeexported intotheenvironmentwith .

12

 

IN PU T/OU TPUT

Redirectionsaredonelefttoright,afterpipesareset up.Defaultfiledescriptors arestdin and stdout.File descriptors above2aremarkedclose-on-exec.

&>w ord

sendstdoutandstderrtow ord sendstdoutandstderrtow ord

>&w ord

[n]<file

usefileforinput

 

[n]>file

usefileforoutput

[n]>|file

like>,butoverridesnoclobber

[n]>>file

like>butappendtofileifitexists

[n]<>file

openfileforread/write(default:fd0)

[n]<&m

duplicateinputfiledescriptorfrom m

[n]>&m

duplicateoutputfiledescriptorfromm

[n]

closeinputfiledescriptor[ n ]

[n]

closeoutputfiledescriptor[ n ]

[n]<<word

inputcomes from theshellscript;treatalinew ith w ord as EOF on input.Ifanyofw ord is quoted,no additionalprocess ingis done on input bythes hell. Otherwise:

dovariable,command,arithmetics ubstitutions ignoreescapednewlines use\toquote\,$,`,andfirstcharacterofw ord [n] word asabove,butwithleadingtabsignored

Of&> and >&,thefirst is preferred.It is equivalent to >w ord2>&1.

EX ECU TION ORD ER

Allsubstitutions andI/Oredirections areperformed beforeacommandis actuallyexecuted.

bash m aintains an internal has h table for caching external commands .Initially,this table is em pty.A s commands arefound bys earchingthedirectories listed in$PATH,theyareaddedtothehashtable.

Thecommands earchorderis shellfunctions first,built- in commands s econd,and external commands (firs t in theinternalhas htable,andthen via$PA TH )third.

SIGNALS AND TRAPS

Signalhandlingis donew iththetrapbuilt-in command. Thew ord argument describingcodeto executeupon receiptofthesignalis scanned tw icebybash;once w hen thetrap commandis executed,and again w hen thesignaliscaught.Thereforeitisbesttousesingle quotes for the trap command.Traps are executed in orderofs ignalnumber.You cannot changethestatus ofasignalthatw as ignoredw hen thes hellstartedup.

Traps on D EBUG happen aftercommands areexecuted.

Backgrounded comm ands (thos e follow ed by &)w ill ignoretheSIG INT and SIG QU IT s ignals ifthemonitor option is turnedoff.Otherw ise,theyinheritthevalues oftheparentbash.

A RRA YS

A rrays in bash have no limits on the number of elements.A rray indices s
A rrays in bash have no limits on the number of elements.A rray indices s

A rrays in bash have no limits on the number of elements.A rray indices s tart at 0.A rray s ubscripts can bearithmeticexpressions.A rrayelements need not be contiguous.bash does not have associative arrays.

13

CONTROL COMMA N DS

!pipeline executepipeline.Ifexitstatus w as non-zero,exit zero.Ifexitstatus w as zero,exit1 casew ordin [[(]pat1[|pat2] )list;;] esac executelistassociatedw ithpatthatmatches w ord. Fieldsplittingis notdoneforw ord.patis abash pattern (s eePatterns ).|is us ed to indicate an OR condition.Us eleading(ifcaseis ins ide$()

forname[in w ords];dolist;done sequentiallyass ign eachw ord to nameandexecute list.If in w ords is missing use the positional parameters [function]func(){list;} definefunction func,bodyis list(seeFunctions) iflist1;then list2 [;eliflist3 ;then list4] [;elselist5];fi if executing list1returns s uccess ful exit status,

executelist2else

 

selectname[in w ords];dolist;done printamenuofw ords,promptw ith$PS3 andreada linefrom stdin,s avingitin $REPLY .Ifthelineis the number of one of the w ords ,s et name to it, otherw is e s et name to NU LL.Execute list.Ifin w ords is missing use the positional parameters. bashautomaticallyreprints themenuattheendof theloop time[ ]pipeline execute pipeline;print elapsed,system and user times on stderr. printtimes in POSIX format The$TIMEFORMA T variablecontrols theformatof theoutputif is notused.bashuses thevalue $í\nreal\t% 3lR\nuser\t% 3lU \ns ys\t% 3lSíifthereis novaluefor$TIMEFORMA T

untillist1;dolist2;done

uses thevalue $í\nreal\t% 3lR\nuser\t% 3lU \ns ys\t% 3lSí ifthereis novaluefor $TIMEFORMA T until list1 ;do list2
uses thevalue $í\nreal\t% 3lR\nuser\t% 3lU \ns ys\t% 3lSí ifthereis novaluefor $TIMEFORMA T until list1 ;do list2
uses thevalue $í\nreal\t% 3lR\nuser\t% 3lU \ns ys\t% 3lSí ifthereis novaluefor $TIMEFORMA T until list1 ;do list2

likew hilebutnegatetheterm ination test

whilelist1;dolist2;done

 

execute list1.If las t command in list1had a successful exit status,execute list2 follow ed by list1.Repeatuntillas t commandin list1returns an unsuccessfulexitstatus

((

))

arithmeticevaluation,likelet" [[expression]] evaluateexpression,return s uccess fulexitstatus if true, uns uccess ful if fals e (s ee Conditional Expressions fordetails) (list)

"

executelistin as ub-shell {list;} executelistin thecurrentshell

 

14

 

CONDITIONA L EXPRESSIONS

 

Us edw iththe[[

]]compoundcommand,w

hichdoes

notdopatternexpansionorw ordsplitting.

string

trueifstringis notNULL trueiffileexists( ispreferred) trueiffileisablockdevice trueiffileisacharacterdevice trueiffileisadirectory trueiffileexists trueiffileisaregularfile trueiffilehassetgidbitset trueiffilegroupiseffectivegid trueiffileis as ym boliclink trueiffilehasstickybitset trueiffileis as ym boliclink

 

file

file

file

file

file

file

file

file

file

file

file

string trueifstringhas non-zerolength

file

trueiffileexistsandwasmodifiedsince lastread trueifoptionison trueiffileow neris effectiveuid trueiffileis afifo(namedpipe) trueiffileisreadable trueiffilehasnon-zerosize trueiffileisasocket trueiffiledesisaterminal trueiffilehassetuidbitset trueiffileiswritable trueiffileisexecutable

option file file file file file filedes file file file
option
file
file
file
file
file
filedes
file
file
file
file file file file file filedes file file file string trueif string has zerolength file1 file2
file file file file file filedes file file file string trueif string has zerolength file1 file2

string trueifstringhas zerolength file1 file2 trueiffile1isnewerthanfile2orfile2 does notexist file1 file2 trueiffile1isolderthanfile2orfile2 does notexist file1 file2 trueiffile1andfile2arethesamefile string==pattern trueifstringmatchespattern string!=pattern trueifstringdoesnotmatchpattern

string1<string2

 

trueifstring1isbeforestring2

string1>string2

 
 

trueifstring1isafterstring2

exp1 exp2trueifexp1equalsexp2 exp1 exp2trueifexp1doesnotequalexp2 exp1 exp2 trueifexp1is less thanexp2 exp1 exp2trueifexp1isgreaterthanexp2 exp1 exp2 trueifexp1is less thanorequaltoexp2 exp1 exp2trueifexp1isgreaterthanor

trueif exp1 isgreaterthan exp2 exp1 exp2 trueif exp1 is less thanorequalto exp2 exp1 exp2 trueif exp1
 

equaltoexp2

(expression) trueifexpress ion is true,forgrouping !expression trueifexpression is false exp1&&exp2 trueifexp1AND exp2aretrue exp1||exp2 trueifexp1OR exp2 is true

Iffileis/dev/fd/n,then,ifthereisno/dev/fddirectory, file descriptor n is checked.Otherw ise,the real /dev/fd/n fileis checked.Linux,FreeBSD ,BSD /OS (and maybe others ) return info for the indicated file descriptor,insteadoftheactual/dev/fddevicefile.

Both && and || are s hort circuit. Operands of com parison operators undergo arithm etic evaluation. For==and!=,quoteanypartofpatterntotreatitasa string.

15

BUILT-IN COMMA N DS

Thes e commands are executed directly by the s hell. A lmostallaccept tomarktheendofoptions.

.file sourcefile read and execute commands from file. If arguments,save and restore positional params. Search$PATH;ifnothingfound,lookinthecurrent directory

nullcommand;returns 0exitstatus [ seetest alias [ ][name[=value] createan alias.Withnoarguments,printall alias es .W ithname,printalias valueforname printaliasbeforeeachalias

:

] createan alias.Withnoarguments,printall alias es .W ith name ,printalias valuefor name print alias beforeeachalias : ]
] createan alias.Withnoarguments,printall alias es .W ith name ,printalias valuefor name print alias beforeeachalias : ]

]

bg[jobid] putjobidinthebackground bind[ map][ bind[ map][ func][ keys eq][ func] bind[ map] file bind[ map]keys eq:func display and/or modify readline function and key bindings .Thes yntaxis s ameas forò/.inputrc file readnew bindings from file lis tthenam es ofallreadlinefunctions map usethekeymapmap listreadlinefunctions and bindings forre-reading listreadlinefunctions and bindings func showwhichkeysinvokefunc keys eq removebindings forkeys eq listreadlinekeysequences andmacros forre-reading listreadlinekeysequences andmacros func removekeybindings forfunc listreadlinevariablenames andvalues forre-reading listreadlinevariablenames andvalues

]
]
removekeybindings for func list readline variablenames andvalues forre-reading list readline variablenames andvalues ]
removekeybindings for func list readline variablenames andvalues forre-reading list readline variablenames andvalues ]
removekeybindings for func list readline variablenames andvalues forre-reading list readline variablenames andvalues ]
removekeybindings for func list readline variablenames andvalues forre-reading list readline variablenames andvalues ]

break[n] exit from enclos ingfor,w hile,until orselect loop. Ifnissupplied,exitfromníthenclosingloop

builtinshell-builtin[args

]

 

executeshell-builtin withgiven args andreturn

status.Usefulforthebodyofas hellfunction that redefinesabuilt-in,e.g.,cd cd[ ][dir] changecurrentdirectorytodir($HOMEdefault). Dodirectorypathsearchusingvalueof$CDPATH uselogicalpathforcd ,$PWD(default) usephysicalpathforcd ,$PWD Ifbotharegiven,thelas t oneon thecommand line wins cd[ ] changecurrentdirectoryto$OLDPWD

comm and[ ]name[arg

[ ] changecurrentdirectoryto $OLDPWD comm and [ ] name [ arg ] w ithout or ,execute
[ ] changecurrentdirectoryto $OLDPWD comm and [ ] name [ arg ] w ithout or ,execute
[ ] changecurrentdirectoryto $OLDPWD comm and [ ] name [ arg ] w ithout or ,execute
[ ] changecurrentdirectoryto $OLDPWD comm and [ ] name [ arg ] w ithout or ,execute
[ ] changecurrentdirectoryto $OLDPWD comm and [ ] name [ arg ] w ithout or ,execute

]

w ithout or ,executenamew itharguments arg useadefaultsearchpath,not$PATH print aonew orddes criptionofname print averbos edes criptionofname

continue[n] do next iteration ofenclos ing for,w hile,until or select loop.Ifn is s upplied,iterate níth enclos ing loop

16

 

BUILT-IN COMMA N DS (continued)

 

BUILT-IN COMMA N DS (continued)

 

BUILT-IN COMMA N DS (continued)

 

BUILT-IN COMMA N DS (continued)

 

declare[afFirx][ ][name[=value]] types et[afFirx][ ][name[=value]] set attributes and values of variables.Inside functions ,createnew copies ofthevariables .Us ing +insteadof turnsattributesoff.Withnonames or attributes , print every variableís nam e and attributes

+ insteadof turnsattributesoff.Withnonames or attributes , print every variableís nam e and attributes name is an
+ insteadof turnsattributesoff.Withnonames or attributes , print every variableís nam e and attributes name is an

nameis an array

export[ ][name[=value]

export [ ][ name [ = value ] ] w ith no argum ents ,print nam

]

w

ith no argum ents ,print nam es and values of

kill[sig]jobid kill[ s igname][ s ignum]jobid send SIG TERM or given s ignal to named jobids. Signals are names listed in /usr/include/signal.h

readonly[ ][name=value

readonly [ ][ name = value ] mark names read-only;printlis tifno names

]

marknames read-only;printlis tifnonames

 

exportedvariables.Otherw ise,exportnames tothe

exportedvariables.Otherw ise,export names tothe each name mus tbean array

eachnamemus tbean array

environmentofcommands

 

eachnamemus

tbeafunction

 

names refertofunctions

 

ithorw ithout theprefixëëSIG íí.Stopped jobs get a SIG C ONT first if sig is either SIG TERM or SIG H UP [sigs

w

ithout theprefixëëSIG íí.Stopped jobs get a SIG C ONT first if sig is either SIG TERM

]

printreadonlybeforeeachvariable

stopexportingeachname

return[n] exitfunction or.scriptw ithreturn valuen.W ithno n,return s tatus oflas tcommand.Ifnotin function or.script,printanerrormessage set[options][ option][words]

setflags and options (s eeOptions To s et).w ords s et positionalparameters set[+options][+ooption][words] unsetflags andoptions shift[n]

print export beforeeachvariable fc [ editor ][ ][ first [ last ]]

printexportbeforeeachvariable

fc[ editor][ ][first[last]]

print export beforeeachvariable fc [ editor ][ ][ first [ last ]]
each name is afunction donítshow functiondefinitions (bodies) name is an integer;arithmetic evaluationis

eachnameis afunction donítshow functiondefinitions (bodies) nameis an integer;arithmetic evaluationis doneuponassignment marknames readonly marknames forexport ][+n][n]

print arangeofcommands from firsttolastfrom last $H ISTSIZEcommands

runeditorifsupplied;ifnot,usefirstof

lis

t s ignal names and/or numbers .If s ig is a

numericalexitstatus ,printthes ignalthat killedthe process letarg evaluateeachargas anarithmeticexpression;exit0 ifthelast expression w as non-zero,1otherw ise (seeArithmeticEvaluation)

   

$FCED IT,$ED ITOR,orvion

 
dirs [

dirs[

commands ;executeresult(s)

lis t on s tandardoutput ins teadofediting

lis

t on s tandardoutput ins teadofediting

donítprintlinenumbers

 

displaythedirectorystack

 

revers eorderofcommands

local[name[=value]

]

 

renamepositionalparameters;$n+1=$1

 

+n

showníthentryfromleft,n 0

 

[old=new ][command]

 

createvariables withthegivenvalueslocaltoa function.Withnooperands,printalistoflocal variables .Mus tbeusedins ideafunction logout exitaloginshell popd[ ][+n][n]

ndefaultsto1

 
n
n

showníthentryfromright,n 0

s ubs titutenew foroldin command(orlas t command ifnocommand)andexecutetheresult fg[jobid]

shopt[

shopt [ ][ option ]

][option

]

clearthedirectorystack

print or change values of shell options .W ith no arguments,printshelloptioninformation

print alongerformat listing

printthestackoneentryperline

putjobidintheforeground

   

onlychange options prints ettings forre-reading

onlychange options prints ettings forre-reading
 

printthestackoneentryperline,w ith

getopts optstringname[arg

]

printthestackoneentryperline,w ith getopts optstringname [ arg ]
 

indexnumbers

     
  indexnumbers      

disow n [ ][ ][job w ithno options ,removenamed jobs from thetable ofactivejobs

ithno options ,removenamed job s from thetable ofactivejobs ] removeormark(with )alljobs markeach job tonotreceivea SIG

]

options ,removenamed job s from thetable ofactivejobs ] removeormark(with )alljobs markeach job tonotreceivea SIG H

removeormark(with )alljobs

markeachjobtonotreceiveaSIG H UP

options ,removenamed job s from thetable ofactivejobs ] removeormark(with )alljobs markeach job tonotreceivea SIG H UP

parseparameters andoptions (seebash(1)) hash[ ][ file][name]

andoptions (see bash (1)) hash [ ][ file ][ name ] ithnoarguments,printthehashtablecontents, givinghitcount

ithnoarguments,printthehashtablecontents, givinghitcount andfilename file enterfilefornamein thehas htable cleartheinternalhas htable

w

givinghitcount andfilename file enter file for name in thehas htable cleartheinternalhas htable w

remove entries from the directory stack.W ith no arguments,removethetopentryandcdthere

+n

removeníthentryfromleft,n 0

removeníthentryfromright,n 0 donítchangedirectory

n
n

printfformat[arg

]

quiet mode;exitstatus indicates optionstatus

set(enable)given option;w ithno options,printthosethatareset unset(disable)given option;w ithno options,printthosethatareunset (SeeOptions To s hopt) s us pend[ ] s us pendthes helluntilSIG C ONT is received forcesuspension,evenforloginshell

test

Options To s hopt ) s us pend [ ] s us pendthes helluntil SIG C
Options To s hopt ) s us pend [ ] s us pendthes helluntil SIG C
 

w

hen bashterminates

A

ssignmentto$PATH alsoclears thehashtable

printoutputlikeANSICprintf,withextensions

us
us

ew ith tomarkjus trunningjobs ][words]

us ew ith tomarkjus trunningjobs ][ words ] echo [ echo words ; isnotspecial expand\-escapes(see echo

echo[

echowords; isnotspecial

expand\-escapes(seeecho(1))

help[pattern] printhelp.Withpattern,printhelpaboutallthe commands thatmatchpattern history[n]

%b

%q

expandescapesequences ins trings printquotedstringthatcanbere-read

Formatconversionsarereusedasneeded pushd[ ][dir] pushd[ ][+n][n] addanentrytothedirectorystack.Withno

neverexpand\-escapes

donítoutputtrailingnew line

 
history[ ] arg[
history[ ]
arg[

[file]

]

 

evaluate conditional express ions (s ee Options To testandConditionalExpress ions ) times printaccumulatedprocess times trap[ ][word][sigs] executewordifsignalinsigs received.sigs are num bers or s ignal nam es w ith or w ithout ëëSIG íí. W ith no w ord or s igs ,print traps .W ith no w ord, resetsigstoentrydefaults.Ifword sigs to entrydefaults .Ifw ord is the null s tring,ignore

traps .W ith no w ord , reset sigs toentrydefaults.If word sigs to entrydefaults .If w
traps .W ith no w ord , reset sigs toentrydefaults.If word sigs to entrydefaults .If w

printfismoreportable

 

arguments,exchangethetoptwoentries

 

enable[

enable [ ][ file ][ name ] enable and disable s hell built-ins ,or load and

][ file][name

]

enable and disable s hell built-ins ,or load and

w

arg[

]

ith no options,print the command history.A n

+n

rotatethestacksothattheníth entryfromleftisatthetop,n 0

unload new built-ins from shared library files. Disablingabuilt-inallow s useofadiskfilew iththe samenameas abuilt-in printallbuilt-ins ,w iththeirstatus

s useofadiskfilew iththe samenameas abuilt-in printallbuilt-ins ,w iththeirstatus deleteabuilt-inloadedwith

deleteabuilt-inloadedwith

argument ofn prints onlyn lines .Ifs upplied,use fileins teadof$H ISTFILE

n

rotatethestacksothattheníth entryfromrightisatthetop,n 0

 

append new historylines to historyfile

 

clearthehistorylist

readnew historylines in thefileinto the

dir

donítchangedirectory pushdiron thestackandcdthere

pwd[ ] printw orkingdirectoryname printlogicalpath(default) printphysicalpath Ifbotharegiven,thelas t oneon thecommand line

printphysicalpath Ifbotharegiven,thelas t oneon thecommand line wins name ][ ][ prompt ][ names ]
printphysicalpath Ifbotharegiven,thelas t oneon thecommand line wins name ][ ][ prompt ][ names ]
printphysicalpath Ifbotharegiven,thelas t oneon thecommand line wins name ][ ][ prompt ][ names ]

wins

printphysicalpath Ifbotharegiven,thelas t oneon thecommand line wins name ][ ][ prompt ][ names ]

name][ ][ prompt][names

printphysicalpath Ifbotharegiven,thelas t oneon thecommand line wins name ][ ][ prompt ][ names ]

]

file loadanew built-in namefrom file

 

internalhistorylist

 

sigs.Ifsigsis0orEXIT,executewordonexitfrom

 

disablename,orprintdisabledbuilt-ins

  disable name ,orprintdisabledbuilt-ins perform historys ubs titutionandprint shell.If sigs is DEBUG ,run w ord

perform historys ubs titutionandprint

shell.If sigs is DEBUG ,run w ord after every command.

shell.If sigs is DEBUG ,run w ord after every command. printalis tofsignalnames and num bers printtraps

printalis tofsignalnames and num bers printtraps w ithquoting type[ ]name describehow thes hellinterprets name printallpossibleinterpretations ofname printthenam eofthefileto executeif nameis an externalprogram print akeyw orddes cribingname

of name printthenam eofthefileto executeif name is an externalprogram print akeyw orddes cribing name
of name printthenam eofthefileto executeif name is an externalprogram print akeyw orddes cribing name
w printenabledbuilt-ins printonlyPOSIXspecialbuilt-ins ithno name s
w printenabledbuilt-ins printonlyPOSIXspecialbuilt-ins ithno name s

w

printenabledbuilt-ins

printonlyPOSIXspecialbuilt-ins

ithno names

theresults

replaceinternalhistoryw ithcontents of

historyfile

placetheargs intothehistorylist

eval[words] evaluatew ords andexecuteresult exec[ name][ ][w ords]

eval [ words ] evaluate w ords andexecuteresult exec [ name ][ ][ w ords ]
 

forlateruse

 

readstdin andassign to names.$IFS splits input.

w

ritetheinternalhistorytothefile

$REPLY is s et ifno namegiven.Exit0unless end- of-fileencountered readw ords intoindexedarrayname usereadlineifreadingfrom aterminal

executewordsinplaceoftheshell.Ifredirections only,changetheshellísopenfiles

usenameforargv[0]

][jobid

]

 
jobs[
jobs[

command[args

]

listinformationaboutjobs

 
cleartheenvironmentfirst   alsolistprocess id   print prompt ifreadingfromaterminal

cleartheenvironmentfirst

 

alsolistprocess id

 
cleartheenvironmentfirst   alsolistprocess id   print prompt ifreadingfromaterminal

printpromptifreadingfromaterminal

placea onargv[0](likelogin(1)) Iftheexecfails,non-interactiveshells exit,unless theshoptoptionexecfailisset

onlyliststoppedorexitedjobs

beforereading

onlylistprocess groups

onlylistprocess groups  
 

onlylistrunningjobs

 

at endoflinedoes notdoline continuation

exit[n] exitw ithreturn valuen.Use$? ifno n

 

onlyliststoppedjobs

 

replaceanyjobidin thecommandline

 
   

w

iththecorrespondingprocess groupID,

andexecutethecommand

 

17

18

19

20

BUILT-IN COMMA N DS (continued)

ulimit[type][options][limit] setorprintper-process limits type(defaultisboth):

 
 
  hardlimit

hardlimit

softlimit

options:

 
all(displayonly) corefilesize ëëkííofdatasegment maximumfilesize ëëkííofphysicalmemory maximum filedescriptor+1

all(displayonly) corefilesize ëëkííofdatasegment maximumfilesize ëëkííofphysicalmemory maximum filedescriptor+1 sizeofpipebuffers ëëkííofstacksegment cpuseconds maxprocesses foroneuser ëëkííofvirtualmemory is assumedifnooptions aregiven.Thesizefor

isin512-byteblocks;theothersareinsizesof

1024bytes

 

umask[ ][mask] setfilecreationpermissions masktocomplementof maskifoctal,orsymbolicvalueas in chmod.W ith noarguments,printcurrentmask.An octalmaskis permissions to remove,a symbolic mask is permissions tokeep printoutputforre-reading printcurrentmaskinsymbolicform unalias[][names] removealiasesnames removeallaliases unset[ ][names] unsetvariables names (sameas ) unsetfunctions names unsetvariables names Unsetting LIN ENO, MA ILCH ECK, OPTA RG , OPTIND,RA NDOM,SECON DS,TMOUT and _ removes their s pecial meaning, even if us ed afterwards

ECK , OPTA RG , OPTIND , RA NDOM , SECON DS , TMOUT and _
ECK , OPTA RG , OPTIND , RA NDOM , SECON DS , TMOUT and _
ECK , OPTA RG , OPTIND , RA NDOM , SECON DS , TMOUT and _
ECK , OPTA RG , OPTIND , RA NDOM , SECON DS , TMOUT and _
ECK , OPTA RG , OPTIND , RA NDOM , SECON DS , TMOUT and _

wait[jobid

]

 

waitforjobjobid;ifnojob,waitforallchildren

 

OPTIONS TO test

Thetest command,and its s ynonym [

],arebuilt-in

to

bash.Thecommandaccepts alloftheoptions listedin theConditionalExpress ions s ection.H ow ever,s ince itis acommand,options and arguments mus t be quotedto

getproperbehavior,andnormalpatternexpansionand field splittingaredone.Parenthes es us edfor grouping mustbequoted.Arithmeticexpansionisnotdonefor numeric operators ,and pattern matching is not done for==and!=.testcomplies w ithPOSIX.

The and

options have the follow ing meanings,

ins teadoftheones listedin ConditionalExpress ions :

 
 

logicalAND

 

logicalOR

21

 

OPTIONS TO s et

 

Thes etcommand is complicated.H ereis as ummary. Use + ins tead of to turn options off.W ith no arguments,s et prints the nam es and values of all variables.

s et[abBC efhH kmnpPtuvx][ooption

][arg

]

automaticallyexportvariablesupon assignment printjobcompletionmessages immediately,donítw aitfornextprompt enablebraceexpansion(default) force>| tooverw riteforexistingfiles exitupon non-zeroexitfrom acommand disablepatternexpansion s avecommandlocations in >| tooverw riteforexistingfiles exitupon non-zeroexitfrom acommand disablepatternexpansion s avecommandlocations in >|tooverw riteforexistingfiles exitupon non-zeroexitfrom acommand disablepatternexpansion s avecommandlocations in the internalhashtable(default) enableaitfornextprompt enablebraceexpansion(default) force >| ! -stylehistory(default) placeallvariableassignments in !-stylehistory(default) placeallvariableassignments in theenvironment(obsolete) runbackgroundjobsintheirown

process group,printamessage w hentheyexit;setautomaticallyfor interactives hells on jobcontrolsystems readcommands w ithoutexecutingthem (ignoredifinteractive) setoptions;w ithnoarguments,print currentsettings

allexport

sameas

 
braceexpand sameas

braceexpand sameas

em acs us ean emacs -styleline editor(default)

errexit

 

sameas

sameas histexpand sameas hashall

sameas histexpand sameas

hashall

 

history

 

enablehistory

ignoreeof

likeIGNOREEOF=10

keyw ord sameas

monitor

 
sameas sameas sameas sameas sameas sameas sameas sameas

sameas

sameas

sameas

sameas

sameas

sameas

sameas

sameas

noclobber

noexec

 

noglob

notify

nounset

onecmd

physical

posix

 

obeythePOSIX1003.2

s

tandard

 

privileged

sameas

sameas sameas

sameas

 

verbose

 

vi

us eavi-stylelineeditor

xtrace

 

sameas

donítread$ENV ,donottakeshell functionsfromenvironment,andignore optionsin $SHELLOPTS environment variable $ENV,donottakeshell functionsfromenvironment,andignore optionsin$SHELLOPTSenvironment variable

followthephysicaldirectorystructure forcommands that changethedirectoryoptionsin $SHELLOPTS environment variable readandexecuteonecommand, thenexit

readandexecuteonecommand, thenexit makeitanerrortosubstituteanunset variable printinputlines as theyírereadoptionsin $SHELLOPTS environment variable followthephysicaldirectorystructure forcommands that changethedirectory

22

OPTIONS TO s et(continued)

print commands as theyíreexecuted,

precededbyexpandedvalueof$PS4.

Outputis quotedforlaterreuse turnoff , ,stoplookingforflags; anyremainingargssetthe positionalparameters donotchangeflags;setpositional parametersfromargumentlist; w ithnoargs,unsetthepositional parameters

OPTIONS TO s hopt

Thes hoptcommandsets oruns ets anumberofoptions thataffecthow bashbehaves.This section describes eachoptionís effectw hen enabled.Unless noted,they arealldisabledbydefault.

cdable_vars treatanargumenttocdthatisnotadirectoryasa variablew hos evalueis thedirectoryname cdspell attempt to correct minor spellingerrors in arguments to