Upload
leo-valentine
View
238
Download
0
Embed Size (px)
DESCRIPTION
Bash Reference Manual
Citation preview
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 1/158
BashReferenceManualTableofContents
1Introduction1.1WhatisBash?1.2Whatisashell?
2Definitions3BasicShellFeatures
3.1ShellSyntax3.1.1ShellOperation3.1.2Quoting
3.1.2.1EscapeCharacter3.1.2.2SingleQuotes3.1.2.3DoubleQuotes3.1.2.4ANSICQuoting3.1.2.5LocaleSpecificTranslation
3.1.3Comments3.2ShellCommands
3.2.1SimpleCommands3.2.2Pipelines3.2.3ListsofCommands3.2.4CompoundCommands
3.2.4.1LoopingConstructs3.2.4.2ConditionalConstructs3.2.4.3GroupingCommands
3.2.5Coprocesses3.2.6GNUParallel
3.3ShellFunctions3.4ShellParameters
3.4.1PositionalParameters3.4.2SpecialParameters
3.5ShellExpansions3.5.1BraceExpansion3.5.2TildeExpansion3.5.3ShellParameterExpansion3.5.4CommandSubstitution3.5.5ArithmeticExpansion3.5.6ProcessSubstitution3.5.7WordSplitting3.5.8FilenameExpansion
3.5.8.1PatternMatching3.5.9QuoteRemoval
3.6Redirections3.6.1RedirectingInput3.6.2RedirectingOutput3.6.3AppendingRedirectedOutput3.6.4RedirectingStandardOutputandStandardError3.6.5AppendingStandardOutputandStandardError3.6.6HereDocuments3.6.7HereStrings3.6.8DuplicatingFileDescriptors3.6.9MovingFileDescriptors3.6.10OpeningFileDescriptorsforReadingandWriting
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 2/158
3.7ExecutingCommands3.7.1SimpleCommandExpansion3.7.2CommandSearchandExecution3.7.3CommandExecutionEnvironment3.7.4Environment3.7.5ExitStatus3.7.6Signals
3.8ShellScripts4ShellBuiltinCommands
4.1BourneShellBuiltins4.2BashBuiltinCommands4.3ModifyingShellBehavior
4.3.1TheSetBuiltin4.3.2TheShoptBuiltin
4.4SpecialBuiltins5ShellVariables
5.1BourneShellVariables5.2BashVariables
6BashFeatures6.1InvokingBash6.2BashStartupFiles6.3InteractiveShells
6.3.1WhatisanInteractiveShell?6.3.2IsthisShellInteractive?6.3.3InteractiveShellBehavior
6.4BashConditionalExpressions6.5ShellArithmetic6.6Aliases6.7Arrays6.8TheDirectoryStack
6.8.1DirectoryStackBuiltins6.9ControllingthePrompt6.10TheRestrictedShell6.11BashPOSIXMode
7JobControl7.1JobControlBasics7.2JobControlBuiltins7.3JobControlVariables
8CommandLineEditing8.1IntroductiontoLineEditing8.2ReadlineInteraction
8.2.1ReadlineBareEssentials8.2.2ReadlineMovementCommands8.2.3ReadlineKillingCommands8.2.4ReadlineArguments8.2.5SearchingforCommandsintheHistory
8.3ReadlineInitFile8.3.1ReadlineInitFileSyntax8.3.2ConditionalInitConstructs8.3.3SampleInitFile
8.4BindableReadlineCommands8.4.1CommandsForMoving8.4.2CommandsForManipulatingTheHistory8.4.3CommandsForChangingText8.4.4KillingAndYanking8.4.5SpecifyingNumericArguments8.4.6LettingReadlineTypeForYou
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 3/158
8.4.7KeyboardMacros8.4.8SomeMiscellaneousCommands
8.5ReadlineviMode8.6ProgrammableCompletion8.7ProgrammableCompletionBuiltins8.8AProgrammableCompletionExample
9UsingHistoryInteractively9.1BashHistoryFacilities9.2BashHistoryBuiltins9.3HistoryExpansion
9.3.1EventDesignators9.3.2WordDesignators9.3.3Modifiers
10InstallingBash10.1BasicInstallation10.2CompilersandOptions10.3CompilingForMultipleArchitectures10.4InstallationNames10.5SpecifyingtheSystemType10.6SharingDefaults10.7OperationControls10.8OptionalFeatures
AppendixAReportingBugsAppendixBMajorDifferencesFromTheBourneShell
B.1ImplementationDifferencesFromTheSVR4.2ShellAppendixCGNUFreeDocumentationLicenseAppendixDIndexes
D.1IndexofShellBuiltinCommandsD.2IndexofShellReservedWordsD.3ParameterandVariableIndexD.4FunctionIndexD.5ConceptIndex
Next:Introduction,Previous:(dir),Up:(dir)[Contents][Index]
BashFeaturesThistextisabriefdescriptionofthefeaturesthatarepresentintheBashshell(version4.3,2February2014).TheBashhomepageishttp://www.gnu.org/software/bash/.
ThisisEdition4.3,lastupdated2February2014,ofTheGNUBashReferenceManual,forBash,Version4.3.
Bashcontainsfeaturesthatappearinotherpopularshells,andsomefeaturesthatonlyappearinBash.SomeoftheshellsthatBashhasborrowedconceptsfromaretheBourneShell(sh),theKornShell(ksh),andtheCshell(cshanditssuccessor,tcsh).Thefollowingmenubreaksthefeaturesupintocategories,notingwhichfeatureswereinspiredbyothershellsandwhicharespecifictoBash.
ThismanualismeantasabriefintroductiontofeaturesfoundinBash.TheBashmanualpageshouldbeusedasthedefinitivereferenceonshellbehavior.
Introduction: Anintroductiontotheshell.Definitions: Somedefinitionsusedintherestofthismanual.BasicShellFeatures: Theshell"buildingblocks".ShellBuiltinCommands: Commandsthatareapartoftheshell.ShellVariables: VariablesusedorsetbyBash.BashFeatures: FeaturesfoundonlyinBash.
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 4/158
JobControl: WhatjobcontrolisandhowBashallowsyoutouseit.CommandLineEditing: Chapterdescribingthecommandlineeditingfeatures.UsingHistoryInteractively: CommandHistoryExpansionInstallingBash: HowtobuildandinstallBashonyoursystem.ReportingBugs: HowtoreportbugsinBash.MajorDifferencesFromTheBourneShell:AterselistofthedifferencesbetweenBashandhistoricalversionsof/bin/sh.GNUFreeDocumentationLicense: Copyingandsharingthisdocumentation.Indexes: Variousindexesforthismanual.
Next:Definitions,Up:Top[Contents][Index]
1Introduction
WhatisBash?: AshortdescriptionofBash.Whatisashell?:Abriefintroductiontoshells.
Next:Whatisashell?,Up:Introduction[Contents][Index]
1.1WhatisBash?
Bashistheshell,orcommandlanguageinterpreter,fortheGNUoperatingsystem.ThenameisanacronymfortheBourne-Again SHell,apunonStephenBourne,theauthorofthedirectancestorofthecurrentUnixshellsh,whichappearedintheSeventhEditionBellLabsResearchversionofUnix.
BashislargelycompatiblewithshandincorporatesusefulfeaturesfromtheKornshellkshandtheCshellcsh.ItisintendedtobeaconformantimplementationoftheIEEEPOSIXShellandToolsportionoftheIEEEPOSIXspecification(IEEEStandard1003.1).Itoffersfunctionalimprovementsovershforbothinteractiveandprogramminguse.
WhiletheGNUoperatingsystemprovidesothershells,includingaversionofcsh,Bashisthedefaultshell.LikeotherGNUsoftware,Bashisquiteportable.ItcurrentlyrunsonnearlyeveryversionofUnixandafewotheroperatingsystemsindependentlysupportedportsexistforMSDOS,OS/2,andWindowsplatforms.
Previous:WhatisBash?,Up:Introduction[Contents][Index]
1.2Whatisashell?
Atitsbase,ashellissimplyamacroprocessorthatexecutescommands.Thetermmacroprocessormeansfunctionalitywheretextandsymbolsareexpandedtocreatelargerexpressions.
AUnixshellisbothacommandinterpreterandaprogramminglanguage.Asacommandinterpreter,theshellprovidestheuserinterfacetotherichsetofGNUutilities.Theprogramminglanguagefeaturesallowtheseutilitiestobecombined.Filescontainingcommandscanbecreated,andbecomecommandsthemselves.Thesenewcommandshavethesamestatusassystemcommandsindirectoriessuchas/bin,allowingusersorgroupstoestablishcustomenvironmentstoautomatetheircommontasks.
Shellsmaybeusedinteractivelyornoninteractively.Ininteractivemode,theyacceptinputtypedfromthekeyboard.Whenexecutingnoninteractively,shellsexecutecommandsreadfromafile.
AshellallowsexecutionofGNUcommands,bothsynchronouslyandasynchronously.Theshellwaitsforsynchronouscommandstocompletebeforeacceptingmoreinputasynchronouscommandscontinuetoexecuteinparallelwiththeshellwhileitreadsandexecutesadditionalcommands.Theredirectionconstructspermitfinegrainedcontroloftheinputandoutputofthosecommands.Moreover,theshellallowscontroloverthecontentsofcommandsenvironments.
Shellsalsoprovideasmallsetofbuiltincommands(builtins)implementingfunctionalityimpossibleorinconvenienttoobtainvia
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 5/158
separateutilities.Forexample,cd,break,continue,andexeccannotbeimplementedoutsideoftheshellbecausetheydirectlymanipulatetheshellitself.Thehistory,getopts,kill,orpwdbuiltins,amongothers,couldbeimplementedinseparateutilities,buttheyaremoreconvenienttouseasbuiltincommands.Alloftheshellbuiltinsaredescribedinsubsequentsections.
Whileexecutingcommandsisessential,mostofthepower(andcomplexity)ofshellsisduetotheirembeddedprogramminglanguages.Likeanyhighlevellanguage,theshellprovidesvariables,flowcontrolconstructs,quoting,andfunctions.
Shellsofferfeaturesgearedspecificallyforinteractiveuseratherthantoaugmenttheprogramminglanguage.Theseinteractivefeaturesincludejobcontrol,commandlineediting,commandhistoryandaliases.Eachofthesefeaturesisdescribedinthismanual.
Next:BasicShellFeatures,Previous:Introduction,Up:Top[Contents][Index]
2Definitions
Thesedefinitionsareusedthroughouttheremainderofthismanual.
POSIX
AfamilyofopensystemstandardsbasedonUnix.BashisprimarilyconcernedwiththeShellandUtilitiesportionofthePOSIX1003.1standard.
blank
Aspaceortabcharacter.
builtin
Acommandthatisimplementedinternallybytheshellitself,ratherthanbyanexecutableprogramsomewhereinthefilesystem.
control operator
Atokenthatperformsacontrolfunction.Itisanewlineoroneofthefollowing:||,&&,&,;,;;,|,|&,(,or).
exit status
Thevaluereturnedbyacommandtoitscaller.Thevalueisrestrictedtoeightbits,sothemaximumvalueis255.
field
Aunitoftextthatistheresultofoneoftheshellexpansions.Afterexpansion,whenexecutingacommand,theresultingfieldsareusedasthecommandnameandarguments.
filename
Astringofcharactersusedtoidentifyafile.
job
Asetofprocessescomprisingapipeline,andanyprocessesdescendedfromit,thatareallinthesameprocessgroup.
job control
Amechanismbywhichuserscanselectivelystop(suspend)andrestart(resume)executionofprocesses.
metacharacter
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 6/158
Acharacterthat,whenunquoted,separateswords.Ametacharacterisablankoroneofthefollowingcharacters:|,&,;,(,),.
name
Awordconsistingsolelyofletters,numbers,andunderscores,andbeginningwithaletterorunderscore.Namesareusedasshellvariableandfunctionnames.Alsoreferredtoasanidentifier.
operator
Acontrol operatororaredirection operator.SeeRedirections,foralistofredirectionoperators.Operatorscontainatleastoneunquotedmetacharacter.
process group
AcollectionofrelatedprocesseseachhavingthesameprocessgroupID.
process group ID
Auniqueidentifierthatrepresentsaprocess groupduringitslifetime.
reserved word
Awordthathasaspecialmeaningtotheshell.Mostreservedwordsintroduceshellflowcontrolconstructs,suchasforandwhile.
return status
Asynonymforexit status.
signal
Amechanismbywhichaprocessmaybenotifiedbythekernelofaneventoccurringinthesystem.
special builtin
AshellbuiltincommandthathasbeenclassifiedasspecialbythePOSIXstandard.
token
Asequenceofcharactersconsideredasingleunitbytheshell.Itiseitherawordoranoperator.
word
Asequenceofcharacterstreatedasaunitbytheshell.Wordsmaynotincludeunquotedmetacharacters.
Next:ShellBuiltinCommands,Previous:Definitions,Up:Top[Contents][Index]
3BasicShellFeatures
BashisanacronymforBourne-Again SHell.TheBourneshellisthetraditionalUnixshelloriginallywrittenbyStephenBourne.AlloftheBourneshellbuiltincommandsareavailableinBash,TherulesforevaluationandquotingaretakenfromthePOSIXspecificationforthestandardUnixshell.
Thischapterbrieflysummarizestheshellsbuildingblocks:commands,controlstructures,shellfunctions,shellparameters,shellexpansions,redirections,whichareawaytodirectinputandoutputfromandtonamedfiles,andhowtheshellexecutescommands.
ShellSyntax: Whatyourinputmeanstotheshell.ShellCommands: Thetypesofcommandsyoucanuse.
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 7/158
ShellFunctions: Groupingcommandsbyname.ShellParameters: Howtheshellstoresvalues.ShellExpansions: HowBashexpandsparametersandthevariousexpansionsavailable.Redirections: Awaytocontrolwhereinputandoutputgo.ExecutingCommands:Whathappenswhenyourunacommand.ShellScripts: Executingfilesofshellcommands.
Next:ShellCommands,Up:BasicShellFeatures[Contents][Index]
3.1ShellSyntax
ShellOperation:Thebasicoperationoftheshell.Quoting: Howtoremovethespecialmeaningfromcharacters.Comments: Howtospecifycomments.
Whentheshellreadsinput,itproceedsthroughasequenceofoperations.Iftheinputindicatesthebeginningofacomment,theshellignoresthecommentsymbol(#),andtherestofthatline.
Otherwise,roughlyspeaking,theshellreadsitsinputanddividestheinputintowordsandoperators,employingthequotingrulestoselectwhichmeaningstoassignvariouswordsandcharacters.
Theshellthenparsesthesetokensintocommandsandotherconstructs,removesthespecialmeaningofcertainwordsorcharacters,expandsothers,redirectsinputandoutputasneeded,executesthespecifiedcommand,waitsforthecommandsexitstatus,andmakesthatexitstatusavailableforfurtherinspectionorprocessing.
Next:Quoting,Up:ShellSyntax[Contents][Index]
3.1.1ShellOperation
Thefollowingisabriefdescriptionoftheshellsoperationwhenitreadsandexecutesacommand.Basically,theshelldoesthefollowing:
1. Readsitsinputfromafile(seeShellScripts),fromastringsuppliedasanargumenttothe-cinvocationoption(seeInvokingBash),orfromtheusersterminal.
2. Breakstheinputintowordsandoperators,obeyingthequotingrulesdescribedinQuoting.Thesetokensareseparatedbymetacharacters.Aliasexpansionisperformedbythisstep(seeAliases).
3. Parsesthetokensintosimpleandcompoundcommands(seeShellCommands).4. Performsthevariousshellexpansions(seeShellExpansions),breakingtheexpandedtokensintolistsoffilenames(see
FilenameExpansion)andcommandsandarguments.5. Performsanynecessaryredirections(seeRedirections)andremovestheredirectionoperatorsandtheiroperandsfrom
theargumentlist.6. Executesthecommand(seeExecutingCommands).7. Optionallywaitsforthecommandtocompleteandcollectsitsexitstatus(seeExitStatus).
Next:Comments,Previous:ShellOperation,Up:ShellSyntax[Contents][Index]
3.1.2Quoting
EscapeCharacter: Howtoremovethespecialmeaningfromasinglecharacter.
SingleQuotes: Howtoinhibitallinterpretationofasequenceofcharacters.DoubleQuotes: Howtosuppressmostoftheinterpretationofasequenceofcharacters.ANSICQuoting: HowtoexpandANSICsequencesinquotedstrings.
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 8/158
LocaleTranslation:Howtotranslatestringsintodifferentlanguages.
Quotingisusedtoremovethespecialmeaningofcertaincharactersorwordstotheshell.Quotingcanbeusedtodisablespecialtreatmentforspecialcharacters,topreventreservedwordsfrombeingrecognizedassuch,andtopreventparameterexpansion.
Eachoftheshellmetacharacters(seeDefinitions)hasspecialmeaningtotheshellandmustbequotedifitistorepresentitself.Whenthecommandhistoryexpansionfacilitiesarebeingused(seeHistoryInteraction),thehistoryexpansioncharacter,usually!,mustbequotedtopreventhistoryexpansion.SeeBashHistoryFacilities,formoredetailsconcerninghistoryexpansion.
Therearethreequotingmechanisms:theescapecharacter,singlequotes,anddoublequotes.
Next:SingleQuotes,Up:Quoting[Contents][Index]
3.1.2.1EscapeCharacter
Anonquotedbackslash\istheBashescapecharacter.Itpreservestheliteralvalueofthenextcharacterthatfollows,withtheexceptionofnewline.Ifa\newlinepairappears,andthebackslashitselfisnotquoted,the\newlineistreatedasalinecontinuation(thatis,itisremovedfromtheinputstreamandeffectivelyignored).
Next:DoubleQuotes,Previous:EscapeCharacter,Up:Quoting[Contents][Index]
3.1.2.2SingleQuotes
Enclosingcharactersinsinglequotes(')preservestheliteralvalueofeachcharacterwithinthequotes.Asinglequotemaynotoccurbetweensinglequotes,evenwhenprecededbyabackslash.
Next:ANSICQuoting,Previous:SingleQuotes,Up:Quoting[Contents][Index]
3.1.2.3DoubleQuotes
Enclosingcharactersindoublequotes(")preservestheliteralvalueofallcharacterswithinthequotes,withtheexceptionof$, ,\,and,whenhistoryexpansionisenabled,!.Thecharacters$and retaintheirspecialmeaningwithindoublequotes(seeShellExpansions).Thebackslashretainsitsspecialmeaningonlywhenfollowedbyoneofthefollowingcharacters:$, ,",\,ornewline.Withindoublequotes,backslashesthatarefollowedbyoneofthesecharactersareremoved.Backslashesprecedingcharacterswithoutaspecialmeaningareleftunmodified.Adoublequotemaybequotedwithindoublequotesbyprecedingitwithabackslash.Ifenabled,historyexpansionwillbeperformedunlessan!appearingindoublequotesisescapedusingabackslash.Thebackslashprecedingthe!isnotremoved.
Thespecialparameters*and@havespecialmeaningwhenindoublequotes(seeShellParameterExpansion).
Next:LocaleTranslation,Previous:DoubleQuotes,Up:Quoting[Contents][Index]
3.1.2.4ANSICQuoting
Wordsoftheform$'string'aretreatedspecially.Thewordexpandstostring,withbackslashescapedcharactersreplacedasspecifiedbytheANSICstandard.Backslashescapesequences,ifpresent,aredecodedasfollows:
\a
alert(bell)
\b
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 9/158
backspace
\e\E
anescapecharacter(notANSIC)
\f
formfeed
\n
newline
\r
carriagereturn
\t
horizontaltab
\v
verticaltab
\\
backslash
\'
singlequote
\"
doublequote
\nnn
theeightbitcharacterwhosevalueistheoctalvaluennn(onetothreedigits)
\xHH
theeightbitcharacterwhosevalueisthehexadecimalvalueHH(oneortwohexdigits)
\uHHHH
theUnicode(ISO/IEC10646)characterwhosevalueisthehexadecimalvalueHHHH(onetofourhexdigits)
\UHHHHHHHH
theUnicode(ISO/IEC10646)characterwhosevalueisthehexadecimalvalueHHHHHHHH(onetoeighthexdigits)
\cx
acontrolxcharacter
Theexpandedresultissinglequoted,asifthedollarsignhadnotbeenpresent.
Previous:ANSICQuoting,Up:Quoting[Contents][Index]
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 10/158
3.1.2.5LocaleSpecificTranslation
Adoublequotedstringprecededbyadollarsign($)willcausethestringtobetranslatedaccordingtothecurrentlocale.IfthecurrentlocaleisCorPOSIX,thedollarsignisignored.Ifthestringistranslatedandreplaced,thereplacementisdoublequoted.
SomesystemsusethemessagecatalogselectedbytheLC_MESSAGESshellvariable.OtherscreatethenameofthemessagecatalogfromthevalueoftheTEXTDOMAINshellvariable,possiblyaddingasuffixof.mo.IfyouusetheTEXTDOMAINvariable,youmayneedtosettheTEXTDOMAINDIRvariabletothelocationofthemessagecatalogfiles.Stillothersusebothvariablesinthisfashion:TEXTDOMAINDIR/LC_MESSAGES/LC_MESSAGES/TEXTDOMAIN.mo.
Previous:Quoting,Up:ShellSyntax[Contents][Index]
3.1.3Comments
Inanoninteractiveshell,oraninteractiveshellinwhichtheinteractive_commentsoptiontotheshoptbuiltinisenabled(seeTheShoptBuiltin),awordbeginningwith#causesthatwordandallremainingcharactersonthatlinetobeignored.Aninteractiveshellwithouttheinteractive_commentsoptionenableddoesnotallowcomments.Theinteractive_commentsoptionisonbydefaultininteractiveshells.SeeInteractiveShells,foradescriptionofwhatmakesashellinteractive.
Next:ShellFunctions,Previous:ShellSyntax,Up:BasicShellFeatures[Contents][Index]
3.2ShellCommands
Asimpleshellcommandsuchasecho a b cconsistsofthecommanditselffollowedbyarguments,separatedbyspaces.
Morecomplexshellcommandsarecomposedofsimplecommandsarrangedtogetherinavarietyofways:inapipelineinwhichtheoutputofonecommandbecomestheinputofasecond,inalooporconditionalconstruct,orinsomeothergrouping.
SimpleCommands: Themostcommontypeofcommand.Pipelines: Connectingtheinputandoutputofseveralcommands.Lists: Howtoexecutecommandssequentially.CompoundCommands:Shellcommandsforcontrolflow.Coprocesses: Twowaycommunicationbetweencommands.GNUParallel: Runningcommandsinparallel.
Next:Pipelines,Up:ShellCommands[Contents][Index]
3.2.1SimpleCommands
Asimplecommandisthekindofcommandencounteredmostoften.Itsjustasequenceofwordsseparatedbyblanks,terminatedbyoneoftheshellscontroloperators(seeDefinitions).Thefirstwordgenerallyspecifiesacommandtobeexecuted,withtherestofthewordsbeingthatcommandsarguments.
Thereturnstatus(seeExitStatus)ofasimplecommandisitsexitstatusasprovidedbythePOSIX1003.1waitpidfunction,or128+nifthecommandwasterminatedbysignaln.
Next:Lists,Previous:SimpleCommands,Up:ShellCommands[Contents][Index]
3.2.2Pipelines
Apipelineisasequenceofsimplecommandsseparatedbyoneofthecontroloperators|or|&.
Theformatforapipelineis
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 11/158
[time [-p]] [!] command1 [ | or |& command2 ]
Theoutputofeachcommandinthepipelineisconnectedviaapipetotheinputofthenextcommand.Thatis,eachcommandreadsthepreviouscommandsoutput.Thisconnectionisperformedbeforeanyredirectionsspecifiedbythecommand.
If|&isused,command1sstandarderror,inadditiontoitsstandardoutput,isconnectedtocommand2sstandardinputthroughthepipeitisshorthandfor2>&1 |.Thisimplicitredirectionofthestandarderrortothestandardoutputisperformedafteranyredirectionsspecifiedbythecommand.
Thereservedwordtimecausestimingstatisticstobeprintedforthepipelineonceitfinishes.Thestatisticscurrentlyconsistofelapsed(wallclock)timeanduserandsystemtimeconsumedbythecommandsexecution.The-poptionchangestheoutputformattothatspecifiedbyPOSIX.WhentheshellisinPOSIXmode(seeBashPOSIXMode),itdoesnotrecognizetimeasareservedwordifthenexttokenbeginswitha-.TheTIMEFORMATvariablemaybesettoaformatstringthatspecifieshowthetiminginformationshouldbedisplayed.SeeBashVariables,foradescriptionoftheavailableformats.Theuseoftimeasareservedwordpermitsthetimingofshellbuiltins,shellfunctions,andpipelines.Anexternaltimecommandcannottimetheseeasily.
WhentheshellisinPOSIXmode(seeBashPOSIXMode),timemaybefollowedbyanewline.Inthiscase,theshelldisplaysthetotaluserandsystemtimeconsumedbytheshellanditschildren.TheTIMEFORMATvariablemaybeusedtospecifytheformatofthetimeinformation.
Ifthepipelineisnotexecutedasynchronously(seeLists),theshellwaitsforallcommandsinthepipelinetocomplete.
Eachcommandinapipelineisexecutedinitsownsubshell(seeCommandExecutionEnvironment).Theexitstatusofapipelineistheexitstatusofthelastcommandinthepipeline,unlessthepipefailoptionisenabled(seeTheSetBuiltin).Ifpipefailisenabled,thepipelinesreturnstatusisthevalueofthelast(rightmost)commandtoexitwithanonzerostatus,orzeroifallcommandsexitsuccessfully.Ifthereservedword!precedesthepipeline,theexitstatusisthelogicalnegationoftheexitstatusasdescribedabove.Theshellwaitsforallcommandsinthepipelinetoterminatebeforereturningavalue.
Next:CompoundCommands,Previous:Pipelines,Up:ShellCommands[Contents][Index]
3.2.3ListsofCommands
Alistisasequenceofoneormorepipelinesseparatedbyoneoftheoperators;,&,&&,or||,andoptionallyterminatedbyoneof;,&,oranewline.
Oftheselistoperators,&&and||haveequalprecedence,followedby;and&,whichhaveequalprecedence.
Asequenceofoneormorenewlinesmayappearinalisttodelimitcommands,equivalenttoasemicolon.
Ifacommandisterminatedbythecontroloperator&,theshellexecutesthecommandasynchronouslyinasubshell.Thisisknownasexecutingthecommandinthebackground.Theshelldoesnotwaitforthecommandtofinish,andthereturnstatusis0(true).Whenjobcontrolisnotactive(seeJobControl),thestandardinputforasynchronouscommands,intheabsenceofanyexplicitredirections,isredirectedfrom/dev/null.
Commandsseparatedbya;areexecutedsequentiallytheshellwaitsforeachcommandtoterminateinturn.Thereturnstatusistheexitstatusofthelastcommandexecuted.
ANDandORlistsaresequencesofoneormorepipelinesseparatedbythecontroloperators&&and||,respectively.ANDandORlistsareexecutedwithleftassociativity.
AnANDlisthastheform
command1 && command2
command2isexecutedif,andonlyif,command1returnsanexitstatusofzero.
AnORlisthastheform
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 12/158
command1 || command2
command2isexecutedif,andonlyif,command1returnsanonzeroexitstatus.
ThereturnstatusofANDandORlistsistheexitstatusofthelastcommandexecutedinthelist.
Next:Coprocesses,Previous:Lists,Up:ShellCommands[Contents][Index]
3.2.4CompoundCommands
LoopingConstructs: Shellcommandsforiterativeaction.ConditionalConstructs: Shellcommandsforconditionalexecution.CommandGrouping: Waystogroupcommands.
Compoundcommandsaretheshellprogrammingconstructs.Eachconstructbeginswithareservedwordorcontroloperatorandisterminatedbyacorrespondingreservedwordoroperator.Anyredirections(seeRedirections)associatedwithacompoundcommandapplytoallcommandswithinthatcompoundcommandunlessexplicitlyoverridden.
Inmostcasesalistofcommandsinacompoundcommandsdescriptionmaybeseparatedfromtherestofthecommandbyoneormorenewlines,andmaybefollowedbyanewlineinplaceofasemicolon.
Bashprovidesloopingconstructs,conditionalcommands,andmechanismstogroupcommandsandexecutethemasaunit.
Next:ConditionalConstructs,Up:CompoundCommands[Contents][Index]
3.2.4.1LoopingConstructs
Bashsupportsthefollowingloopingconstructs.
Notethatwherevera;appearsinthedescriptionofacommandssyntax,itmaybereplacedwithoneormorenewlines.
until
Thesyntaxoftheuntilcommandis:
until test-commands; do consequent-commands; done
Executeconsequentcommandsaslongastestcommandshasanexitstatuswhichisnotzero.Thereturnstatusistheexitstatusofthelastcommandexecutedinconsequentcommands,orzeroifnonewasexecuted.
while
Thesyntaxofthewhilecommandis:
while test-commands; do consequent-commands; done
Executeconsequentcommandsaslongastestcommandshasanexitstatusofzero.Thereturnstatusistheexitstatusofthelastcommandexecutedinconsequentcommands,orzeroifnonewasexecuted.
for
Thesyntaxoftheforcommandis:
for name [ [in [words ] ] ; ] do commands; done
Expandwords,andexecutecommandsonceforeachmemberintheresultantlist,withnameboundtothecurrentmember.Ifin wordsisnotpresent,theforcommandexecutesthecommandsonceforeachpositionalparameterthatisset,asifin "$@"hadbeenspecified(seeSpecialParameters).Thereturnstatusistheexitstatusofthelast
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 13/158
commandthatexecutes.Iftherearenoitemsintheexpansionofwords,nocommandsareexecuted,andthereturnstatusiszero.
Analternateformoftheforcommandisalsosupported:
for (( expr1 ; expr2 ; expr3 )) ; do commands ; done
First,thearithmeticexpressionexpr1isevaluatedaccordingtotherulesdescribedbelow(seeShellArithmetic).Thearithmeticexpressionexpr2isthenevaluatedrepeatedlyuntilitevaluatestozero.Eachtimeexpr2evaluatestoanonzerovalue,commandsareexecutedandthearithmeticexpressionexpr3isevaluated.Ifanyexpressionisomitted,itbehavesasifitevaluatesto1.Thereturnvalueistheexitstatusofthelastcommandincommandsthatisexecuted,orfalseifanyoftheexpressionsisinvalid.
Thebreakandcontinuebuiltins(seeBourneShellBuiltins)maybeusedtocontrolloopexecution.
Next:CommandGrouping,Previous:LoopingConstructs,Up:CompoundCommands[Contents][Index]
3.2.4.2ConditionalConstructs
if
Thesyntaxoftheifcommandis:
if test-commands; then consequent-commands;[elif more-test-commands; then more-consequents;][else alternate-consequents;]fi
Thetestcommandslistisexecuted,andifitsreturnstatusiszero,theconsequentcommandslistisexecuted.Iftestcommandsreturnsanonzerostatus,eacheliflistisexecutedinturn,andifitsexitstatusiszero,thecorrespondingmoreconsequentsisexecutedandthecommandcompletes.Ifelse alternate-consequentsispresent,andthefinalcommandinthefinaliforelifclausehasanonzeroexitstatus,thenalternateconsequentsisexecuted.Thereturnstatusistheexitstatusofthelastcommandexecuted,orzeroifnoconditiontestedtrue.
case
Thesyntaxofthecasecommandis:
case word in [ [(] pattern [| pattern]) command-list ;;] esac
casewillselectivelyexecutethecommandlistcorrespondingtothefirstpatternthatmatchesword.Iftheshelloptionnocasematch(seethedescriptionofshoptinTheShoptBuiltin)isenabled,thematchisperformedwithoutregardtothecaseofalphabeticcharacters.The|isusedtoseparatemultiplepatterns,andthe)operatorterminatesapatternlist.Alistofpatternsandanassociatedcommandlistisknownasaclause.
Eachclausemustbeterminatedwith;;,;&,or;;&.Thewordundergoestildeexpansion,parameterexpansion,commandsubstitution,arithmeticexpansion,andquoteremovalbeforematchingisattempted.Eachpatternundergoestildeexpansion,parameterexpansion,commandsubstitution,andarithmeticexpansion.
Theremaybeanarbitrarynumberofcaseclauses,eachterminatedbya;;,;&,or;;&.Thefirstpatternthatmatchesdeterminesthecommandlistthatisexecuted.Itsacommonidiomtouse*asthefinalpatterntodefinethedefaultcase,sincethatpatternwillalwaysmatch.
Hereisanexampleusingcaseinascriptthatcouldbeusedtodescribeoneinterestingfeatureofananimal:
echo -n "Enter the name of an animal: "read ANIMALecho -n "The $ANIMAL has "
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 14/158
case $ANIMAL in horse | dog | cat) echo -n "four";; man | kangaroo ) echo -n "two";; *) echo -n "an unknown number of";;esacecho " legs."
Ifthe;;operatorisused,nosubsequentmatchesareattemptedafterthefirstpatternmatch.Using;&inplaceof;;causesexecutiontocontinuewiththecommandlistassociatedwiththenextclause,ifany.Using;;&inplaceof;;causestheshelltotestthepatternsinthenextclause,ifany,andexecuteanyassociatedcommandlistonasuccessfulmatch.
Thereturnstatusiszeroifnopatternismatched.Otherwise,thereturnstatusistheexitstatusofthecommandlistexecuted.
select
Theselectconstructallowstheeasygenerationofmenus.Ithasalmostthesamesyntaxastheforcommand:
select name [in words ]; do commands; done
Thelistofwordsfollowinginisexpanded,generatingalistofitems.Thesetofexpandedwordsisprintedonthestandarderroroutputstream,eachprecededbyanumber.Ifthein wordsisomitted,thepositionalparametersareprinted,asifin "$@"hadbeenspecified.ThePS3promptisthendisplayedandalineisreadfromthestandardinput.Ifthelineconsistsofanumbercorrespondingtooneofthedisplayedwords,thenthevalueofnameissettothatword.Ifthelineisempty,thewordsandpromptaredisplayedagain.IfEOFisread,theselectcommandcompletes.Anyothervaluereadcausesnametobesettonull.ThelinereadissavedinthevariableREPLY.
Thecommandsareexecutedaftereachselectionuntilabreakcommandisexecuted,atwhichpointtheselectcommandcompletes.
Hereisanexamplethatallowstheusertopickafilenamefromthecurrentdirectory,anddisplaysthenameandindexofthefileselected.
select fname in *;do echo you picked $fname \($REPLY\) break;done
(())
(( expression ))
Thearithmeticexpressionisevaluatedaccordingtotherulesdescribedbelow(seeShellArithmetic).Ifthevalueoftheexpressionisnonzero,thereturnstatusis0otherwisethereturnstatusis1.Thisisexactlyequivalentto
let "expression"
SeeBashBuiltins,forafulldescriptionoftheletbuiltin.
[[]]
[[ expression ]]
Returnastatusof0or1dependingontheevaluationoftheconditionalexpressionexpression.ExpressionsarecomposedoftheprimariesdescribedbelowinBashConditionalExpressions.Wordsplittingandfilenameexpansionarenotperformedonthewordsbetweenthe[[and]]tildeexpansion,parameterandvariableexpansion,arithmeticexpansion,commandsubstitution,processsubstitution,andquoteremovalareperformed.Conditionaloperatorssuchas-fmustbeunquotedtoberecognizedasprimaries.
Whenusedwith[[,theoperatorssortlexicographicallyusingthecurrentlocale.
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 15/158
Whenthe==and!=operatorsareused,thestringtotherightoftheoperatorisconsideredapatternandmatchedaccordingtotherulesdescribedbelowinPatternMatching,asiftheextglobshelloptionwereenabled.The=operatorisidenticalto==.Iftheshelloptionnocasematch(seethedescriptionofshoptinTheShoptBuiltin)isenabled,thematchisperformedwithoutregardtothecaseofalphabeticcharacters.Thereturnvalueis0ifthestringmatches(==)ordoesnotmatch(!=)thepattern,and1otherwise.Anypartofthepatternmaybequotedtoforcethequotedportiontobematchedasastring.
Anadditionalbinaryoperator,=~,isavailable,withthesameprecedenceas==and!=.Whenitisused,thestringtotherightoftheoperatorisconsideredanextendedregularexpressionandmatchedaccordingly(asinregex3)).Thereturnvalueis0ifthestringmatchesthepattern,and1otherwise.Iftheregularexpressionissyntacticallyincorrect,theconditionalexpressionsreturnvalueis2.Iftheshelloptionnocasematch(seethedescriptionofshoptinTheShoptBuiltin)isenabled,thematchisperformedwithoutregardtothecaseofalphabeticcharacters.Anypartofthepatternmaybequotedtoforcethequotedportiontobematchedasastring.Bracketexpressionsinregularexpressionsmustbetreatedcarefully,sincenormalquotingcharacterslosetheirmeaningsbetweenbrackets.Ifthepatternisstoredinashellvariable,quotingthevariableexpansionforcestheentirepatterntobematchedasastring.SubstringsmatchedbyparenthesizedsubexpressionswithintheregularexpressionaresavedinthearrayvariableBASH_REMATCH.TheelementofBASH_REMATCHwithindex0istheportionofthestringmatchingtheentireregularexpression.TheelementofBASH_REMATCHwithindexnistheportionofthestringmatchingthenthparenthesizedsubexpression.
Forexample,thefollowingwillmatchaline(storedintheshellvariableline)ifthereisasequenceofcharactersinthevalueconsistingofanynumber,includingzero,ofspacecharacters,zerooroneinstancesofa,thenab:
[[ $line =~ [[:space:]]*(a)?b ]]
Thatmeansvalueslikeaaband aaaaaabwillmatch,aswillalinecontainingabanywhereinitsvalue.
Storingtheregularexpressioninashellvariableisoftenausefulwaytoavoidproblemswithquotingcharactersthatarespecialtotheshell.Itissometimesdifficulttospecifyaregularexpressionliterallywithoutusingquotes,ortokeeptrackofthequotingusedbyregularexpressionswhilepayingattentiontotheshellsquoteremoval.Usingashellvariabletostorethepatterndecreasestheseproblems.Forexample,thefollowingisequivalenttotheabove:
pattern='[[:space:]]*(a)?b'[[ $line =~ $pattern ]]
Ifyouwanttomatchacharacterthatsspecialtotheregularexpressiongrammar,ithastobequotedtoremoveitsspecialmeaning.Thismeansthatinthepatternxxx.txt,the.matchesanycharacterinthestring(itsusualregularexpressionmeaning),butinthepattern"xxx.txt"itcanonlymatchaliteral..Shellprogrammersshouldtakespecialcarewithbackslashes,sincebackslashesareusedbothbytheshellandregularexpressionstoremovethespecialmeaningfromthefollowingcharacter.Thefollowingtwosetsofcommandsarenotequivalent:
pattern='\.'
[[ . =~ $pattern ]][[ . =~ \. ]]
[[ . =~ "$pattern" ]][[ . =~ '\.' ]]
Thefirsttwomatcheswillsucceed,butthesecondtwowillnot,becauseinthesecondtwothebackslashwillbepartofthepatterntobematched.Inthefirsttwoexamples,thebackslashremovesthespecialmeaningfrom.,sotheliteral.matches.Ifthestringinthefirstexampleswereanythingotherthan.,saya,thepatternwouldnotmatch,becausethequoted.inthepatternlosesitsspecialmeaningofmatchinganysinglecharacter.
Expressionsmaybecombinedusingthefollowingoperators,listedindecreasingorderofprecedence:
( expression )
Returnsthevalueofexpression.Thismaybeusedtooverridethenormalprecedenceofoperators.
! expression
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 16/158
Trueifexpressionisfalse.
expression1 && expression2
Trueifbothexpression1andexpression2aretrue.
expression1 || expression2
Trueifeitherexpression1orexpression2istrue.
The&&and||operatorsdonotevaluateexpression2ifthevalueofexpression1issufficienttodeterminethereturnvalueoftheentireconditionalexpression.
Previous:ConditionalConstructs,Up:CompoundCommands[Contents][Index]
3.2.4.3GroupingCommands
Bashprovidestwowaystogroupalistofcommandstobeexecutedasaunit.Whencommandsaregrouped,redirectionsmaybeappliedtotheentirecommandlist.Forexample,theoutputofallthecommandsinthelistmayberedirectedtoasinglestream.
()
( list )
Placingalistofcommandsbetweenparenthesescausesasubshellenvironmenttobecreated(seeCommandExecutionEnvironment),andeachofthecommandsinlisttobeexecutedinthatsubshell.Sincethelistisexecutedinasubshell,variableassignmentsdonotremainineffectafterthesubshellcompletes.
{}
{ list; }
Placingalistofcommandsbetweencurlybracescausesthelisttobeexecutedinthecurrentshellcontext.Nosubshelliscreated.Thesemicolon(ornewline)followinglistisrequired.
Inadditiontothecreationofasubshell,thereisasubtledifferencebetweenthesetwoconstructsduetohistoricalreasons.Thebracesarereserved words,sotheymustbeseparatedfromthelistbyblanksorothershellmetacharacters.Theparenthesesareoperators,andarerecognizedasseparatetokensbytheshelleveniftheyarenotseparatedfromthelistbywhitespace.
Theexitstatusofbothoftheseconstructsistheexitstatusoflist.
Next:GNUParallel,Previous:CompoundCommands,Up:ShellCommands[Contents][Index]
3.2.5Coprocesses
Acoprocessisashellcommandprecededbythecoprocreservedword.Acoprocessisexecutedasynchronouslyinasubshell,asifthecommandhadbeenterminatedwiththe&controloperator,withatwowaypipeestablishedbetweentheexecutingshellandthecoprocess.
Theformatforacoprocessis:
coproc [NAME] command [redirections]
ThiscreatesacoprocessnamedNAME.IfNAMEisnotsupplied,thedefaultnameisCOPROC.NAMEmustnotbesuppliedifcommandisasimplecommand(seeSimpleCommands)otherwise,itisinterpretedasthefirstwordofthesimplecommand.
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 17/158
Whenthecoprocessisexecuted,theshellcreatesanarrayvariable(seeArrays)namedNAMEinthecontextoftheexecutingshell.Thestandardoutputofcommandisconnectedviaapipetoafiledescriptorintheexecutingshell,andthatfiledescriptorisassignedtoNAME[0].Thestandardinputofcommandisconnectedviaapipetoafiledescriptorintheexecutingshell,andthatfiledescriptorisassignedtoNAME[1].Thispipeisestablishedbeforeanyredirectionsspecifiedbythecommand(seeRedirections).Thefiledescriptorscanbeutilizedasargumentstoshellcommandsandredirectionsusingstandardwordexpansions.Thefiledescriptorsarenotavailableinsubshells.
TheprocessIDoftheshellspawnedtoexecutethecoprocessisavailableasthevalueofthevariableNAME_PID.Thewaitbuiltincommandmaybeusedtowaitforthecoprocesstoterminate.
Sincethecoprocessiscreatedasanasynchronouscommand,thecoproccommandalwaysreturnssuccess.Thereturnstatusofacoprocessistheexitstatusofcommand.
Previous:Coprocesses,Up:ShellCommands[Contents][Index]
3.2.6GNUParallel
TherearewaystoruncommandsinparallelthatarenotbuiltintoBash.GNUParallelisatooltodojustthat.
GNUParallel,asitsnamesuggests,canbeusedtobuildandruncommandsinparallel.Youmayrunthesamecommandwithdifferentarguments,whethertheyarefilenames,usernames,hostnames,orlinesreadfromfiles.GNUParallelprovidesshorthandreferencestomanyofthemostcommonoperations(inputlines,variousportionsoftheinputline,differentwaystospecifytheinputsource,andsoon).ParallelcanreplacexargsorfeedcommandsfromitsinputsourcestoseveraldifferentinstancesofBash.
Foracompletedescription,refertotheGNUParalleldocumentation.Afewexamplesshouldprovideabriefintroductiontoitsuse.
Forexample,itiseasytoreplacexargstogzipallhtmlfilesinthecurrentdirectoryanditssubdirectories:
find . -type f -name '*.html' -print | parallel gzip
Ifyouneedtoprotectspecialcharacterssuchasnewlinesinfilenames,usefinds-print0optionandparallels-0option.
YoucanuseParalleltomovefilesfromthecurrentdirectorywhenthenumberoffilesistoolargetoprocesswithonemvinvocation:
ls | parallel mv {} destdir
Asyoucansee,the{}isreplacedwitheachlinereadfromstandardinput.Whileusinglswillworkinmostinstances,itisnotsufficienttodealwithallfilenames.Ifyouneedtoaccommodatespecialcharactersinfilenames,youcanuse
find . -depth 1 \! -name '.*' -print0 | parallel -0 mv {} destdir
asalludedtoabove.
Thiswillrunasmanymvcommandsastherearefilesinthecurrentdirectory.Youcanemulateaparallelxargsbyaddingthe-Xoption:
find . -depth 1 \! -name '.*' -print0 | parallel -0 -X mv {} destdir
GNUParallelcanreplacecertaincommonidiomsthatoperateonlinesreadfromafile(inthiscase,filenameslistedoneperline):
while IFS= read -r x; do do-something1 "$x" "config-$x" do-something2 < "$x" done < file | process-output
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 18/158
withamorecompactsyntaxreminiscentoflambdas:
cat list | parallel "do-something1 {} config-{} ; do-something2 < {}" | process-output
Parallelprovidesabuiltinmechanismtoremovefilenameextensions,whichlendsitselftobatchfiletransformationsorrenaming:
ls *.gz | parallel -j+0 "zcat {} | bzip2 >{.}.bz2 && rm {}"
Thiswillrecompressallfilesinthecurrentdirectorywithnamesendingin.gzusingbzip2,runningonejobperCPU(j+0)inparallel.(Weuselsforbrevityhereusingfindasaboveismorerobustinthefaceoffilenamescontainingunexpectedcharacters.)Parallelcantakeargumentsfromthecommandlinetheabovecanalsobewrittenas
parallel "zcat {} | bzip2 >{.}.bz2 && rm {}" ::: *.gz
Ifacommandgeneratesoutput,youmaywanttopreservetheinputorderintheoutput.Forinstance,thefollowingcommand
{ echo foss.org.my ; echo debian.org; echo freenetproject.org; } | parallel traceroute
willdisplayasoutputthetracerouteinvocationthatfinishesfirst.Addingthe-koption
{ echo foss.org.my ; echo debian.org; echo freenetproject.org; } | parallel -k traceroute
willensurethattheoutputoftraceroute foss.org.myisdisplayedfirst.
Finally,Parallelcanbeusedtorunasequenceofshellcommandsinparallel,similartocat file | bash.Itisnotuncommontotakealistoffilenames,createaseriesofshellcommandstooperateonthem,andfeedthatlistofcommndstoashell.Parallelcanspeedthisup.Assumingthatfilecontainsalistofshellcommands,oneperline,
parallel -j 10 < file
willevaluatethecommandsusingtheshell(sincenoexplicitcommandissuppliedasanargument),inblocksoftenshelljobsatatime.
Next:ShellParameters,Previous:ShellCommands,Up:BasicShellFeatures[Contents][Index]
3.3ShellFunctions
Shellfunctionsareawaytogroupcommandsforlaterexecutionusingasinglenameforthegroup.Theyareexecutedjustlikea"regular"command.Whenthenameofashellfunctionisusedasasimplecommandname,thelistofcommandsassociatedwiththatfunctionnameisexecuted.Shellfunctionsareexecutedinthecurrentshellcontextnonewprocessiscreatedtointerpretthem.
Functionsaredeclaredusingthissyntax:
name () compound-command [ redirections ]
or
function name [()] compound-command [ redirections ]
Thisdefinesashellfunctionnamedname.Thereservedwordfunctionisoptional.Ifthefunctionreservedwordissupplied,theparenthesesareoptional.Thebodyofthefunctionisthecompoundcommandcompoundcommand(seeCompoundCommands).Thatcommandisusuallyalistenclosedbetween{and},butmaybeanycompoundcommandlistedabove.compoundcommandisexecutedwhenevernameisspecifiedasthenameofacommand.WhentheshellisinPOSIXmode(seeBashPOSIXMode),namemaynotbethesameasoneofthespecialbuiltins(seeSpecialBuiltins).Anyredirections(seeRedirections)associatedwiththeshellfunctionareperformedwhenthefunctionisexecuted.
Afunctiondefinitionmaybedeletedusingthe-foptiontotheunsetbuiltin(seeBourneShellBuiltins).
Theexitstatusofafunctiondefinitioniszerounlessasyntaxerroroccursorareadonlyfunctionwiththesamenamealready
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 19/158
exists.Whenexecuted,theexitstatusofafunctionistheexitstatusofthelastcommandexecutedinthebody.
Notethatforhistoricalreasons,inthemostcommonusagethecurlybracesthatsurroundthebodyofthefunctionmustbeseparatedfromthebodybyblanksornewlines.Thisisbecausethebracesarereservedwordsandareonlyrecognizedassuchwhentheyareseparatedfromthecommandlistbywhitespaceoranothershellmetacharacter.Also,whenusingthebraces,thelistmustbeterminatedbyasemicolon,a&,oranewline.
Whenafunctionisexecuted,theargumentstothefunctionbecomethepositionalparametersduringitsexecution(seePositionalParameters).Thespecialparameter#thatexpandstothenumberofpositionalparametersisupdatedtoreflectthechange.Specialparameter0isunchanged.ThefirstelementoftheFUNCNAMEvariableissettothenameofthefunctionwhilethefunctionisexecuting.
Allotheraspectsoftheshellexecutionenvironmentareidenticalbetweenafunctionanditscallerwiththeseexceptions:theDEBUGandRETURNtrapsarenotinheritedunlessthefunctionhasbeengiventhetraceattributeusingthedeclarebuiltinorthe-o functraceoptionhasbeenenabledwiththesetbuiltin,(inwhichcaseallfunctionsinherittheDEBUGandRETURNtraps),andtheERRtrapisnotinheritedunlessthe-o errtraceshelloptionhasbeenenabled.SeeBourneShellBuiltins,forthedescriptionofthetrapbuiltin.
TheFUNCNESTvariable,ifsettoanumericvaluegreaterthan0,definesamaximumfunctionnestinglevel.Functioninvocationsthatexceedthelimitcausetheentirecommandtoabort.
Ifthebuiltincommandreturnisexecutedinafunction,thefunctioncompletesandexecutionresumeswiththenextcommandafterthefunctioncall.AnycommandassociatedwiththeRETURNtrapisexecutedbeforeexecutionresumes.Whenafunctioncompletes,thevaluesofthepositionalparametersandthespecialparameter#arerestoredtothevaluestheyhadpriortothefunctionsexecution.Ifanumericargumentisgiventoreturn,thatisthefunctionsreturnstatusotherwisethefunctionsreturnstatusistheexitstatusofthelastcommandexecutedbeforethereturn.
Variableslocaltothefunctionmaybedeclaredwiththelocalbuiltin.Thesevariablesarevisibleonlytothefunctionandthecommandsitinvokes.
Functionnamesanddefinitionsmaybelistedwiththe-foptiontothedeclare(typeset)builtincommand(seeBashBuiltins).The-Foptiontodeclareortypesetwilllistthefunctionnamesonly(andoptionallythesourcefileandlinenumber,iftheextdebugshelloptionisenabled).Functionsmaybeexportedsothatsubshellsautomaticallyhavethemdefinedwiththe-foptiontotheexportbuiltin(seeBourneShellBuiltins).Notethatshellfunctionsandvariableswiththesamenamemayresultinmultipleidenticallynamedentriesintheenvironmentpassedtotheshellschildren.Careshouldbetakenincaseswherethismaycauseaproblem.
Functionsmayberecursive.TheFUNCNESTvariablemaybeusedtolimitthedepthofthefunctioncallstackandrestrictthenumberoffunctioninvocations.Bydefault,nolimitisplacedonthenumberofrecursivecalls.
Next:ShellExpansions,Previous:ShellFunctions,Up:BasicShellFeatures[Contents][Index]
3.4ShellParameters
PositionalParameters:Theshellscommandlinearguments.SpecialParameters: Parametersdenotedbyspecialcharacters.
Aparameterisanentitythatstoresvalues.Itcanbeaname,anumber,oroneofthespecialcharacterslistedbelow.Avariableisaparameterdenotedbyaname.Avariablehasavalueandzeroormoreattributes.Attributesareassignedusingthedeclarebuiltincommand(seethedescriptionofthedeclarebuiltininBashBuiltins).
Aparameterissetifithasbeenassignedavalue.Thenullstringisavalidvalue.Onceavariableisset,itmaybeunsetonlybyusingtheunsetbuiltincommand.
Avariablemaybeassignedtobyastatementoftheform
name=[value]
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 20/158
Ifvalueisnotgiven,thevariableisassignedthenullstring.Allvaluesundergotildeexpansion,parameterandvariableexpansion,commandsubstitution,arithmeticexpansion,andquoteremoval(detailedbelow).Ifthevariablehasitsintegerattributeset,thenvalueisevaluatedasanarithmeticexpressionevenifthe$(())expansionisnotused(seeArithmeticExpansion).Wordsplittingisnotperformed,withtheexceptionof"$@"asexplainedbelow.Filenameexpansionisnotperformed.Assignmentstatementsmayalsoappearasargumentstothealias,declare,typeset,export,readonly,andlocalbuiltincommands.WheninPOSIXmode(seeBashPOSIXMode),thesebuiltinsmayappearinacommandafteroneormoreinstancesofthecommandbuiltinandretaintheseassignmentstatementproperties.
Inthecontextwhereanassignmentstatementisassigningavaluetoashellvariableorarrayindex(seeArrays),the+=operatorcanbeusedtoappendtooraddtothevariablespreviousvalue.When+=isappliedtoavariableforwhichtheintegerattributehasbeenset,valueisevaluatedasanarithmeticexpressionandaddedtothevariablescurrentvalue,whichisalsoevaluated.When+=isappliedtoanarrayvariableusingcompoundassignment(seeArrays),thevariablesvalueisnotunset(asitiswhenusing=),andnewvaluesareappendedtothearraybeginningatonegreaterthanthearraysmaximumindex(forindexedarrays),oraddedasadditionalkeyvaluepairsinanassociativearray.Whenappliedtoastringvaluedvariable,valueisexpandedandappendedtothevariablesvalue.
Avariablecanbeassignedthenamerefattributeusingthe-noptiontothe\fBdeclare\fPor\fBlocal\fPbuiltincommands(seeBashBuiltins)tocreateanameref,orareferencetoanothervariable.Thisallowsvariablestobemanipulatedindirectly.Wheneverthenamerefvariableisreferencedorassignedto,theoperationisactuallyperformedonthevariablespecifiedbythenamerefvariablesvalue.Anamerefiscommonlyusedwithinshellfunctionstorefertoavariablewhosenameispassedasanargumenttothefunction.Forinstance,ifavariablenameispassedtoashellfunctionasitsfirstargument,running
declare -n ref=$1
insidethefunctioncreatesanamerefvariablerefwhosevalueisthevariablenamepassedasthefirstargument.Referencesandassignmentstorefaretreatedasreferencesandassignmentstothevariablewhosenamewaspassedas$1.
Ifthecontrolvariableinaforloophasthenamerefattribute,thelistofwordscanbealistofshellvariables,andanamereferencewillbeestablishedforeachwordinthelist,inturn,whentheloopisexecuted.Arrayvariablescannotbegiventhe-nattribute.However,namerefvariablescanreferencearrayvariablesandsubscriptedarrayvariables.Namerefscanbeunsetusingthe-noptiontotheunsetbuiltin(seeBourneShellBuiltins).Otherwise,ifunsetisexecutedwiththenameofanamerefvariableasanargument,thevariablereferencedbythenamerefvariablewillbeunset.
Next:SpecialParameters,Up:ShellParameters[Contents][Index]
3.4.1PositionalParameters
Apositionalparameterisaparameterdenotedbyoneormoredigits,otherthanthesingledigit0.Positionalparametersareassignedfromtheshellsargumentswhenitisinvoked,andmaybereassignedusingthesetbuiltincommand.PositionalparameterNmaybereferencedas${N},oras$NwhenNconsistsofasingledigit.Positionalparametersmaynotbeassignedtowithassignmentstatements.Thesetandshiftbuiltinsareusedtosetandunsetthem(seeShellBuiltinCommands).Thepositionalparametersaretemporarilyreplacedwhenashellfunctionisexecuted(seeShellFunctions).
Whenapositionalparameterconsistingofmorethanasingledigitisexpanded,itmustbeenclosedinbraces.
Previous:PositionalParameters,Up:ShellParameters[Contents][Index]
3.4.2SpecialParameters
Theshelltreatsseveralparametersspecially.Theseparametersmayonlybereferencedassignmenttothemisnotallowed.
*
($*)Expandstothepositionalparameters,startingfromone.Whentheexpansionisnotwithindoublequotes,eachpositionalparameterexpandstoaseparateword.Incontextswhereitisperformed,thosewordsaresubjecttofurtherwordsplittingandpathnameexpansion.Whentheexpansionoccurswithindoublequotes,itexpandstoasingleword
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 21/158
withthevalueofeachparameterseparatedbythefirstcharacteroftheIFSspecialvariable.Thatis,"$*"isequivalentto"$1c$2c",wherecisthefirstcharacterofthevalueoftheIFSvariable.IfIFSisunset,theparametersareseparatedbyspaces.IfIFSisnull,theparametersarejoinedwithoutinterveningseparators.
@
($@)Expandstothepositionalparameters,startingfromone.Whentheexpansionoccurswithindoublequotes,eachparameterexpandstoaseparateword.Thatis,"$@"isequivalentto"$1" "$2" .Ifthedoublequotedexpansionoccurswithinaword,theexpansionofthefirstparameterisjoinedwiththebeginningpartoftheoriginalword,andtheexpansionofthelastparameterisjoinedwiththelastpartoftheoriginalword.Whentherearenopositionalparameters,"$@"and$@expandtonothing(i.e.,theyareremoved).
#
($#)Expandstothenumberofpositionalparametersindecimal.
?
($?)Expandstotheexitstatusofthemostrecentlyexecutedforegroundpipeline.
-
($,ahyphen.)Expandstothecurrentoptionflagsasspecifieduponinvocation,bythesetbuiltincommand,orthosesetbytheshellitself(suchasthe-ioption).
$
($$)ExpandstotheprocessIDoftheshell.Ina()subshell,itexpandstotheprocessIDoftheinvokingshell,notthesubshell.
!
($!)ExpandstotheprocessIDofthejobmostrecentlyplacedintothebackground,whetherexecutedasanasynchronouscommandorusingthebgbuiltin(seeJobControlBuiltins).
0
($0)Expandstothenameoftheshellorshellscript.Thisissetatshellinitialization.IfBashisinvokedwithafileofcommands(seeShellScripts),$0issettothenameofthatfile.IfBashisstartedwiththe-coption(seeInvokingBash),then$0issettothefirstargumentafterthestringtobeexecuted,ifoneispresent.Otherwise,itissettothefilenameusedtoinvokeBash,asgivenbyargumentzero.
_
($_,anunderscore.)Atshellstartup,settotheabsolutepathnameusedtoinvoketheshellorshellscriptbeingexecutedaspassedintheenvironmentorargumentlist.Subsequently,expandstothelastargumenttothepreviouscommand,afterexpansion.Alsosettothefullpathnameusedtoinvokeeachcommandexecutedandplacedintheenvironmentexportedtothatcommand.Whencheckingmail,thisparameterholdsthenameofthemailfile.
Next:Redirections,Previous:ShellParameters,Up:BasicShellFeatures[Contents][Index]
3.5ShellExpansions
Expansionisperformedonthecommandlineafterithasbeensplitintotokens.Therearesevenkindsofexpansionperformed:
braceexpansiontildeexpansionparameterandvariableexpansioncommandsubstitution
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 22/158
arithmeticexpansionwordsplittingfilenameexpansion
BraceExpansion: Expansionofexpressionswithinbraces.TildeExpansion: Expansionofthe~character.ShellParameterExpansion:HowBashexpandsvariablestotheirvalues.CommandSubstitution: Usingtheoutputofacommandasanargument.ArithmeticExpansion: Howtousearithmeticinshellexpansions.ProcessSubstitution: Awaytowriteandreadtoandfromacommand.WordSplitting: Howtheresultsofexpansionaresplitintoseparatearguments.FilenameExpansion: Ashorthandforspecifyingfilenamesmatchingpatterns.QuoteRemoval: Howandwhenquotecharactersareremovedfromwords.
Theorderofexpansionsis:braceexpansiontildeexpansion,parameterandvariableexpansion,arithmeticexpansion,andcommandsubstitution(doneinalefttorightfashion)wordsplittingandfilenameexpansion.
Onsystemsthatcansupportit,thereisanadditionalexpansionavailable:processsubstitution.Thisisperformedatthesametimeastilde,parameter,variable,andarithmeticexpansionandcommandsubstitution.
Onlybraceexpansion,wordsplitting,andfilenameexpansioncanchangethenumberofwordsoftheexpansionotherexpansionsexpandasinglewordtoasingleword.Theonlyexceptionstothisaretheexpansionsof"$@"(seeSpecialParameters)and"${name[@]}"(seeArrays).
Afterallexpansions,quote removal(seeQuoteRemoval)isperformed.
Next:TildeExpansion,Up:ShellExpansions[Contents][Index]
3.5.1BraceExpansion
Braceexpansionisamechanismbywhicharbitrarystringsmaybegenerated.Thismechanismissimilartofilenameexpansion(seeFilenameExpansion),butthefilenamesgeneratedneednotexist.Patternstobebraceexpandedtaketheformofanoptionalpreamble,followedbyeitheraseriesofcommaseparatedstringsorasequenceexpressionbetweenapairofbraces,followedbyanoptionalpostscript.Thepreambleisprefixedtoeachstringcontainedwithinthebraces,andthepostscriptisthenappendedtoeachresultingstring,expandinglefttoright.
Braceexpansionsmaybenested.Theresultsofeachexpandedstringarenotsortedlefttorightorderispreserved.Forexample,
bash$ echo a{d,c,b}eade ace abe
Asequenceexpressiontakestheform{x..y[..incr]},wherexandyareeitherintegersorsinglecharacters,andincr,anoptionalincrement,isaninteger.Whenintegersaresupplied,theexpressionexpandstoeachnumberbetweenxandy,inclusive.Suppliedintegersmaybeprefixedwith0toforceeachtermtohavethesamewidth.Wheneitherxorybeginswithazero,theshellattemptstoforceallgeneratedtermstocontainthesamenumberofdigits,zeropaddingwherenecessary.Whencharactersaresupplied,theexpressionexpandstoeachcharacterlexicographicallybetweenxandy,inclusive,usingthedefaultClocale.Notethatbothxandymustbeofthesametype.Whentheincrementissupplied,itisusedasthedifferencebetweeneachterm.Thedefaultincrementis1or1asappropriate.
Braceexpansionisperformedbeforeanyotherexpansions,andanycharactersspecialtootherexpansionsarepreservedintheresult.Itisstrictlytextual.Bashdoesnotapplyanysyntacticinterpretationtothecontextoftheexpansionorthetextbetweenthebraces.Toavoidconflictswithparameterexpansion,thestring${isnotconsideredeligibleforbraceexpansion.
Acorrectlyformedbraceexpansionmustcontainunquotedopeningandclosingbraces,andatleastoneunquotedcommaoravalidsequenceexpression.Anyincorrectlyformedbraceexpansionisleftunchanged.
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 23/158
A{or,maybequotedwithabackslashtopreventitsbeingconsideredpartofabraceexpression.Toavoidconflictswithparameterexpansion,thestring${isnotconsideredeligibleforbraceexpansion.
Thisconstructistypicallyusedasshorthandwhenthecommonprefixofthestringstobegeneratedislongerthanintheaboveexample:
mkdir /usr/local/src/bash/{old,new,dist,bugs}
or
chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
Next:ShellParameterExpansion,Previous:BraceExpansion,Up:ShellExpansions[Contents][Index]
3.5.2TildeExpansion
Ifawordbeginswithanunquotedtildecharacter(~),allofthecharactersuptothefirstunquotedslash(orallcharacters,ifthereisnounquotedslash)areconsideredatildeprefix.Ifnoneofthecharactersinthetildeprefixarequoted,thecharactersinthetildeprefixfollowingthetildearetreatedasapossibleloginname.Ifthisloginnameisthenullstring,thetildeisreplacedwiththevalueoftheHOMEshellvariable.IfHOMEisunset,thehomedirectoryoftheuserexecutingtheshellissubstitutedinstead.Otherwise,thetildeprefixisreplacedwiththehomedirectoryassociatedwiththespecifiedloginname.
Ifthetildeprefixis~+,thevalueoftheshellvariablePWDreplacesthetildeprefix.Ifthetildeprefixis~-,thevalueoftheshellvariableOLDPWD,ifitisset,issubstituted.
IfthecharactersfollowingthetildeinthetildeprefixconsistofanumberN,optionallyprefixedbya+ora-,thetildeprefixisreplacedwiththecorrespondingelementfromthedirectorystack,asitwouldbedisplayedbythedirsbuiltininvokedwiththecharactersfollowingtildeinthetildeprefixasanargument(seeTheDirectoryStack).Ifthetildeprefix,sansthetilde,consistsofanumberwithoutaleading+or-,+isassumed.
Iftheloginnameisinvalid,orthetildeexpansionfails,thewordisleftunchanged.
Eachvariableassignmentischeckedforunquotedtildeprefixesimmediatelyfollowinga:orthefirst=.Inthesecases,tildeexpansionisalsoperformed.Consequently,onemayusefilenameswithtildesinassignmentstoPATH,MAILPATH,andCDPATH,andtheshellassignstheexpandedvalue.
ThefollowingtableshowshowBashtreatsunquotedtildeprefixes:
~
Thevalueof$HOME
~/foo
$HOME/foo
~fred/foo
Thesubdirectoryfooofthehomedirectoryoftheuserfred
~+/foo
$PWD/foo
~-/foo
${OLDPWD-'~-'}/foo
~N
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 24/158
Thestringthatwouldbedisplayedbydirs +N
~+N
Thestringthatwouldbedisplayedbydirs +N
~-N
Thestringthatwouldbedisplayedbydirs -N
Next:CommandSubstitution,Previous:TildeExpansion,Up:ShellExpansions[Contents][Index]
3.5.3ShellParameterExpansion
The$characterintroducesparameterexpansion,commandsubstitution,orarithmeticexpansion.Theparameternameorsymboltobeexpandedmaybeenclosedinbraces,whichareoptionalbutservetoprotectthevariabletobeexpandedfromcharactersimmediatelyfollowingitwhichcouldbeinterpretedaspartofthename.
Whenbracesareused,thematchingendingbraceisthefirst}notescapedbyabackslashorwithinaquotedstring,andnotwithinanembeddedarithmeticexpansion,commandsubstitution,orparameterexpansion.
Thebasicformofparameterexpansionis${parameter}.Thevalueofparameterissubstituted.Theparameterisashellparameterasdescribedabove(seeShellParameters)oranarrayreference(seeArrays).Thebracesarerequiredwhenparameterisapositionalparameterwithmorethanonedigit,orwhenparameterisfollowedbyacharacterthatisnottobeinterpretedaspartofitsname.
Ifthefirstcharacterofparameterisanexclamationpoint(!),itintroducesalevelofvariableindirection.Bashusesthevalueofthevariableformedfromtherestofparameterasthenameofthevariablethisvariableisthenexpandedandthatvalueisusedintherestofthesubstitution,ratherthanthevalueofparameteritself.Thisisknownasindirect expansion.Theexceptionstothisaretheexpansionsof${!prefix*}and${!name[@]}describedbelow.Theexclamationpointmustimmediatelyfollowtheleftbraceinordertointroduceindirection.
Ineachofthecasesbelow,wordissubjecttotildeexpansion,parameterexpansion,commandsubstitution,andarithmeticexpansion.
Whennotperformingsubstringexpansion,usingtheformdescribedbelow(e.g.,:-),Bashtestsforaparameterthatisunsetornull.Omittingthecolonresultsinatestonlyforaparameterthatisunset.Putanotherway,ifthecolonisincluded,theoperatortestsforbothparametersexistenceandthatitsvalueisnotnullifthecolonisomitted,theoperatortestsonlyforexistence.
${parameter:-word}
Ifparameterisunsetornull,theexpansionofwordissubstituted.Otherwise,thevalueofparameterissubstituted.
${parameter:=word}
Ifparameterisunsetornull,theexpansionofwordisassignedtoparameter.Thevalueofparameteristhensubstituted.Positionalparametersandspecialparametersmaynotbeassignedtointhisway.
${parameter:?word}
Ifparameterisnullorunset,theexpansionofword(oramessagetothateffectifwordisnotpresent)iswrittentothestandarderrorandtheshell,ifitisnotinteractive,exits.Otherwise,thevalueofparameterissubstituted.
${parameter:+word}
Ifparameterisnullorunset,nothingissubstituted,otherwisetheexpansionofwordissubstituted.
${parameter:offset}
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 25/158
${parameter:offset:length}
ThisisreferredtoasSubstringExpansion.Itexpandstouptolengthcharactersofthevalueofparameterstartingatthecharacterspecifiedbyoffset.Ifparameteris@,anindexedarraysubscriptedby@or*,oranassociativearrayname,theresultsdifferasdescribedbelow.Iflengthisomitted,itexpandstothesubstringofthevalueofparameterstartingatthecharacterspecifiedbyoffsetandextendingtotheendofthevalue.lengthandoffsetarearithmeticexpressions(seeShellArithmetic).
Ifoffsetevaluatestoanumberlessthanzero,thevalueisusedasanoffsetincharactersfromtheendofthevalueofparameter.Iflengthevaluatestoanumberlessthanzero,itisinterpretedasanoffsetincharactersfromtheendofthevalueofparameterratherthananumberofcharacters,andtheexpansionisthecharactersbetweenoffsetandthatresult.Notethatanegativeoffsetmustbeseparatedfromthecolonbyatleastonespacetoavoidbeingconfusedwiththe:-expansion.
Herearesomeexamplesillustratingsubstringexpansiononparametersandsubscriptedarrays:
$ string=01234567890abcdefgh$ echo ${string:7}7890abcdefgh$ echo ${string:7:0}
$ echo ${string:7:2}78$ echo ${string:7:-2}7890abcdef$ echo ${string: -7}bcdefgh$ echo ${string: -7:0}
$ echo ${string: -7:2}bc$ echo ${string: -7:-2}bcdef$ set -- 01234567890abcdefgh$ echo ${1:7}7890abcdefgh$ echo ${1:7:0}
$ echo ${1:7:2}78$ echo ${1:7:-2}7890abcdef$ echo ${1: -7}bcdefgh$ echo ${1: -7:0}
$ echo ${1: -7:2}bc$ echo ${1: -7:-2}bcdef$ array[0]=01234567890abcdefgh$ echo ${array[0]:7}7890abcdefgh$ echo ${array[0]:7:0}
$ echo ${array[0]:7:2}78$ echo ${array[0]:7:-2}7890abcdef$ echo ${array[0]: -7}bcdefgh$ echo ${array[0]: -7:0}
$ echo ${array[0]: -7:2}bc$ echo ${array[0]: -7:-2}bcdef
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 26/158
Ifparameteris@,theresultislengthpositionalparametersbeginningatoffset.Anegativeoffsetistakenrelativetoonegreaterthanthegreatestpositionalparameter,soanoffsetof1evaluatestothelastpositionalparameter.Itisanexpansionerroriflengthevaluatestoanumberlessthanzero.
Thefollowingexamplesillustratesubstringexpansionusingpositionalparameters:
$ set -- 1 2 3 4 5 6 7 8 9 0 a b c d e f g h$ echo ${@:7}7 8 9 0 a b c d e f g h$ echo ${@:7:0}
$ echo ${@:7:2}7 8$ echo ${@:7:-2}bash: -2: substring expression < 0$ echo ${@: -7:2}b c$ echo ${@:0}./bash 1 2 3 4 5 6 7 8 9 0 a b c d e f g h$ echo ${@:0:2}./bash 1$ echo ${@: -7:0}
Ifparameterisanindexedarraynamesubscriptedby@or*,theresultisthelengthmembersofthearraybeginningwith${parameter[offset]}.Anegativeoffsetistakenrelativetoonegreaterthanthemaximumindexofthespecifiedarray.Itisanexpansionerroriflengthevaluatestoanumberlessthanzero.
Theseexamplesshowhowyoucanusesubstringexpansionwithindexedarrays:
$ array=(0 1 2 3 4 5 6 7 8 9 0 a b c d e f g h)$ echo ${array[@]:7}7 8 9 0 a b c d e f g h$ echo ${array[@]:7:2}7 8$ echo ${array[@]: -7:2}b c$ echo ${array[@]: -7:-2}bash: -2: substring expression < 0$ echo ${array[@]:0}0 1 2 3 4 5 6 7 8 9 0 a b c d e f g h$ echo ${array[@]:0:2}0 1$ echo ${array[@]: -7:0}
Substringexpansionappliedtoanassociativearrayproducesundefinedresults.
Substringindexingiszerobasedunlessthepositionalparametersareused,inwhichcasetheindexingstartsat1bydefault.Ifoffsetis0,andthepositionalparametersareused,$@isprefixedtothelist.
${!prefix*}${!prefix@}
Expandstothenamesofvariableswhosenamesbeginwithprefix,separatedbythefirstcharacteroftheIFSspecialvariable.When@isusedandtheexpansionappearswithindoublequotes,eachvariablenameexpandstoaseparateword.
${!name[@]}${!name[*]}
Ifnameisanarrayvariable,expandstothelistofarrayindices(keys)assignedinname.Ifnameisnotanarray,expandsto0ifnameissetandnullotherwise.When@isusedandtheexpansionappearswithindoublequotes,eachkeyexpandstoaseparateword.
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 27/158
${#parameter}
Thelengthincharactersoftheexpandedvalueofparameterissubstituted.Ifparameteris*or@,thevaluesubstitutedisthenumberofpositionalparameters.Ifparameterisanarraynamesubscriptedby*or@,thevaluesubstitutedisthenumberofelementsinthearray.Ifparameterisanindexedarraynamesubscriptedbyanegativenumber,thatnumberisinterpretedasrelativetoonegreaterthanthemaximumindexofparameter,sonegativeindicescountbackfromtheendofthearray,andanindexof1referencesthelastelement.
${parameter#word}${parameter##word}
Thewordisexpandedtoproduceapatternjustasinfilenameexpansion(seeFilenameExpansion).Ifthepatternmatchesthebeginningoftheexpandedvalueofparameter,thentheresultoftheexpansionistheexpandedvalueofparameterwiththeshortestmatchingpattern(the#case)orthelongestmatchingpattern(the##case)deleted.Ifparameteris@or*,thepatternremovaloperationisappliedtoeachpositionalparameterinturn,andtheexpansionistheresultantlist.Ifparameterisanarrayvariablesubscriptedwith@or*,thepatternremovaloperationisappliedtoeachmemberofthearrayinturn,andtheexpansionistheresultantlist.
${parameter%word}${parameter%%word}
Thewordisexpandedtoproduceapatternjustasinfilenameexpansion.Ifthepatternmatchesatrailingportionoftheexpandedvalueofparameter,thentheresultoftheexpansionisthevalueofparameterwiththeshortestmatchingpattern(the%case)orthelongestmatchingpattern(the%%case)deleted.Ifparameteris@or*,thepatternremovaloperationisappliedtoeachpositionalparameterinturn,andtheexpansionistheresultantlist.Ifparameterisanarrayvariablesubscriptedwith@or*,thepatternremovaloperationisappliedtoeachmemberofthearrayinturn,andtheexpansionistheresultantlist.
${parameter/pattern/string}
Thepatternisexpandedtoproduceapatternjustasinfilenameexpansion.Parameterisexpandedandthelongestmatchofpatternagainstitsvalueisreplacedwithstring.Ifpatternbeginswith/,allmatchesofpatternarereplacedwithstring.Normallyonlythefirstmatchisreplaced.Ifpatternbeginswith#,itmustmatchatthebeginningoftheexpandedvalueofparameter.Ifpatternbeginswith%,itmustmatchattheendoftheexpandedvalueofparameter.Ifstringisnull,matchesofpatternaredeletedandthe/followingpatternmaybeomitted.Ifparameteris@or*,thesubstitutionoperationisappliedtoeachpositionalparameterinturn,andtheexpansionistheresultantlist.Ifparameterisanarrayvariablesubscriptedwith@or*,thesubstitutionoperationisappliedtoeachmemberofthearrayinturn,andtheexpansionistheresultantlist.
${parameterpattern}${parameter pattern}${parameter,pattern}${parameter,,pattern}
Thisexpansionmodifiesthecaseofalphabeticcharactersinparameter.Thepatternisexpandedtoproduceapatternjustasinfilenameexpansion.Eachcharacterintheexpandedvalueofparameteristestedagainstpattern,and,ifitmatchesthepattern,itscaseisconverted.Thepatternshouldnotattempttomatchmorethanonecharacter.The operatorconvertslowercaselettersmatchingpatterntouppercasethe,operatorconvertsmatchinguppercaseletterstolowercase.The^ and,,expansionsconverteachmatchedcharacterintheexpandedvaluethe and,expansionsmatchandconvertonlythefirstcharacterintheexpandedvalue.Ifpatternisomitted,itistreatedlikea?,whichmatcheseverycharacter.Ifparameteris@or*,thecasemodificationoperationisappliedtoeachpositionalparameterinturn,andtheexpansionistheresultantlist.Ifparameterisanarrayvariablesubscriptedwith@or*,thecasemodificationoperationisappliedtoeachmemberofthearrayinturn,andtheexpansionistheresultantlist.
Next:ArithmeticExpansion,Previous:ShellParameterExpansion,Up:ShellExpansions[Contents][Index]
3.5.4CommandSubstitution
Commandsubstitutionallowstheoutputofacommandtoreplacethecommanditself.Commandsubstitutionoccurswhena
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 28/158
commandisenclosedasfollows:
$(command)
or
command
Bashperformstheexpansionbyexecutingcommandandreplacingthecommandsubstitutionwiththestandardoutputofthecommand,withanytrailingnewlinesdeleted.Embeddednewlinesarenotdeleted,buttheymayberemovedduringwordsplitting.Thecommandsubstitution$(cat file)canbereplacedbytheequivalentbutfaster$(< file).
Whentheoldstylebackquoteformofsubstitutionisused,backslashretainsitsliteralmeaningexceptwhenfollowedby$, ,or\.Thefirstbackquotenotprecededbyabackslashterminatesthecommandsubstitution.Whenusingthe$(command)form,allcharactersbetweentheparenthesesmakeupthecommandnonearetreatedspecially.
Commandsubstitutionsmaybenested.Tonestwhenusingthebackquotedform,escapetheinnerbackquoteswithbackslashes.
Ifthesubstitutionappearswithindoublequotes,wordsplittingandfilenameexpansionarenotperformedontheresults.
Next:ProcessSubstitution,Previous:CommandSubstitution,Up:ShellExpansions[Contents][Index]
3.5.5ArithmeticExpansion
Arithmeticexpansionallowstheevaluationofanarithmeticexpressionandthesubstitutionoftheresult.Theformatforarithmeticexpansionis:
$(( expression ))
Theexpressionistreatedasifitwerewithindoublequotes,butadoublequoteinsidetheparenthesesisnottreatedspecially.Alltokensintheexpressionundergoparameterandvariableexpansion,commandsubstitution,andquoteremoval.Theresultistreatedasthearithmeticexpressiontobeevaluated.Arithmeticexpansionsmaybenested.
Theevaluationisperformedaccordingtotheruleslistedbelow(seeShellArithmetic).Iftheexpressionisinvalid,Bashprintsamessageindicatingfailuretothestandarderrorandnosubstitutionoccurs.
Next:WordSplitting,Previous:ArithmeticExpansion,Up:ShellExpansions[Contents][Index]
3.5.6ProcessSubstitution
Processsubstitutionissupportedonsystemsthatsupportnamedpipes(FIFOs)orthe/dev/fdmethodofnamingopenfiles.Ittakestheformof
(list)
TheprocesslistisrunwithitsinputoroutputconnectedtoaFIFOorsomefilein/dev/fd.Thenameofthisfileispassedasanargumenttothecurrentcommandastheresultoftheexpansion.Ifthe>(list)formisused,writingtothefilewillprovideinputforlist.Ifthe
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 29/158
Next:FilenameExpansion,Previous:ProcessSubstitution,Up:ShellExpansions[Contents][Index]
3.5.7WordSplitting
Theshellscanstheresultsofparameterexpansion,commandsubstitution,andarithmeticexpansionthatdidnotoccurwithindoublequotesforwordsplitting.
Theshelltreatseachcharacterof$IFSasadelimiter,andsplitstheresultsoftheotherexpansionsintowordsusingthesecharactersasfieldterminators.IfIFSisunset,oritsvalueisexactly,thedefault,thensequencesof,,andatthebeginningandendoftheresultsofthepreviousexpansionsareignored,andanysequenceofIFScharactersnotatthebeginningorendservestodelimitwords.IfIFShasavalueotherthanthedefault,thensequencesofthewhitespacecharactersspaceandtabareignoredatthebeginningandendoftheword,aslongasthewhitespacecharacterisinthevalueofIFS(anIFSwhitespacecharacter).AnycharacterinIFSthatisnotIFSwhitespace,alongwithanyadjacentIFSwhitespacecharacters,delimitsafield.AsequenceofIFSwhitespacecharactersisalsotreatedasadelimiter.IfthevalueofIFSisnull,nowordsplittingoccurs.
Explicitnullarguments(""or'')areretained.Unquotedimplicitnullarguments,resultingfromtheexpansionofparametersthathavenovalues,areremoved.Ifaparameterwithnovalueisexpandedwithindoublequotes,anullargumentresultsandisretained.
Notethatifnoexpansionoccurs,nosplittingisperformed.
Next:QuoteRemoval,Previous:WordSplitting,Up:ShellExpansions[Contents][Index]
3.5.8FilenameExpansion
PatternMatching:Howtheshellmatchespatterns.
Afterwordsplitting,unlessthe-foptionhasbeenset(seeTheSetBuiltin),Bashscanseachwordforthecharacters*,?,and[.Ifoneofthesecharactersappears,thenthewordisregardedasapattern,andreplacedwithanalphabeticallysortedlistoffilenamesmatchingthepattern(seePatternMatching).Ifnomatchingfilenamesarefound,andtheshelloptionnullglobisdisabled,thewordisleftunchanged.Ifthenullgloboptionisset,andnomatchesarefound,thewordisremoved.Ifthefailglobshelloptionisset,andnomatchesarefound,anerrormessageisprintedandthecommandisnotexecuted.Iftheshelloptionnocaseglobisenabled,thematchisperformedwithoutregardtothecaseofalphabeticcharacters.
Whenapatternisusedforfilenameexpansion,thecharacter.atthestartofafilenameorimmediatelyfollowingaslashmustbematchedexplicitly,unlesstheshelloptiondotglobisset.Whenmatchingafilename,theslashcharactermustalwaysbematchedexplicitly.Inothercases,the.characterisnottreatedspecially.
SeethedescriptionofshoptinTheShoptBuiltin,foradescriptionofthenocaseglob,nullglob,failglob,anddotgloboptions.
TheGLOBIGNOREshellvariablemaybeusedtorestrictthesetoffilenamesmatchingapattern.IfGLOBIGNOREisset,eachmatchingfilenamethatalsomatchesoneofthepatternsinGLOBIGNOREisremovedfromthelistofmatches.Thefilenames.and..arealwaysignoredwhenGLOBIGNOREissetandnotnull.However,settingGLOBIGNOREtoanonnullvaluehastheeffectofenablingthedotglobshelloption,soallotherfilenamesbeginningwitha.willmatch.Togettheoldbehaviorofignoringfilenamesbeginningwitha.,make.*oneofthepatternsinGLOBIGNORE.ThedotgloboptionisdisabledwhenGLOBIGNOREisunset.
Up:FilenameExpansion[Contents][Index]
3.5.8.1PatternMatching
Anycharacterthatappearsinapattern,otherthanthespecialpatterncharactersdescribedbelow,matchesitself.TheNUL
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 30/158
charactermaynotoccurinapattern.Abackslashescapesthefollowingcharactertheescapingbackslashisdiscardedwhenmatching.Thespecialpatterncharactersmustbequotediftheyaretobematchedliterally.
Thespecialpatterncharactershavethefollowingmeanings:
*
Matchesanystring,includingthenullstring.Whentheglobstarshelloptionisenabled,and*isusedinafilenameexpansioncontext,twoadjacent*susedasasinglepatternwillmatchallfilesandzeroormoredirectoriesandsubdirectories.Iffollowedbya/,twoadjacent*swillmatchonlydirectoriesandsubdirectories.
?
Matchesanysinglecharacter.
[]
Matchesanyoneoftheenclosedcharacters.Apairofcharactersseparatedbyahyphendenotesarangeexpressionanycharacterthatfallsbetweenthosetwocharacters,inclusive,usingthecurrentlocalescollatingsequenceandcharacterset,ismatched.Ifthefirstcharacterfollowingthe[isa!ora thenanycharacternotenclosedismatched.A-maybematchedbyincludingitasthefirstorlastcharacterintheset.A]maybematchedbyincludingitasthefirstcharacterintheset.ThesortingorderofcharactersinrangeexpressionsisdeterminedbythecurrentlocaleandthevaluesoftheLC_COLLATEandLC_ALLshellvariables,ifset.
Forexample,inthedefaultClocale,[a-dx-z]isequivalentto[abcdxyz].Manylocalessortcharactersindictionaryorder,andintheselocales[a-dx-z]istypicallynotequivalentto[abcdxyz]itmightbeequivalentto[aBbCcDdxXyYz],forexample.Toobtainthetraditionalinterpretationofrangesinbracketexpressions,youcanforcetheuseoftheClocalebysettingtheLC_COLLATEorLC_ALLenvironmentvariabletothevalueC,orenabletheglobasciirangesshelloption.
Within[and],characterclassescanbespecifiedusingthesyntax[:class:],whereclassisoneofthefollowingclassesdefinedinthePOSIXstandard:
alnum alpha ascii blank cntrl digit graph lowerprint punct space upper word xdigit
Acharacterclassmatchesanycharacterbelongingtothatclass.Thewordcharacterclassmatchesletters,digits,andthecharacter_.
Within[and],anequivalenceclasscanbespecifiedusingthesyntax[=c=],whichmatchesallcharacterswiththesamecollationweight(asdefinedbythecurrentlocale)asthecharacterc.
Within[and],thesyntax[.symbol.]matchesthecollatingsymbolsymbol.
Iftheextglobshelloptionisenabledusingtheshoptbuiltin,severalextendedpatternmatchingoperatorsarerecognized.Inthefollowingdescription,apatternlistisalistofoneormorepatternsseparatedbya|.Compositepatternsmaybeformedusingoneormoreofthefollowingsubpatterns:
?(pattern-list)
Matcheszerooroneoccurrenceofthegivenpatterns.
*(pattern-list)
Matcheszeroormoreoccurrencesofthegivenpatterns.
+(pattern-list)
Matchesoneormoreoccurrencesofthegivenpatterns.
@(pattern-list)
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 31/158
Matchesoneofthegivenpatterns.
!(pattern-list)
Matchesanythingexceptoneofthegivenpatterns.
Previous:FilenameExpansion,Up:ShellExpansions[Contents][Index]
3.5.9QuoteRemoval
Aftertheprecedingexpansions,allunquotedoccurrencesofthecharacters\,',and"thatdidnotresultfromoneoftheaboveexpansionsareremoved.
Next:ExecutingCommands,Previous:ShellExpansions,Up:BasicShellFeatures[Contents][Index]
3.6Redirections
Beforeacommandisexecuted,itsinputandoutputmayberedirectedusingaspecialnotationinterpretedbytheshell.Redirectionallowscommandsfilehandlestobeduplicated,opened,closed,madetorefertodifferentfiles,andcanchangethefilesthecommandreadsfromandwritesto.Redirectionmayalsobeusedtomodifyfilehandlesinthecurrentshellexecutionenvironment.Thefollowingredirectionoperatorsmayprecedeorappearanywherewithinasimplecommandormayfollowacommand.Redirectionsareprocessedintheordertheyappear,fromlefttoright.
Eachredirectionthatmaybeprecededbyafiledescriptornumbermayinsteadbeprecededbyawordoftheform{varname}.Inthiscase,foreachredirectionoperatorexcept>&and&or dirlist 2>&1
directsbothstandardoutput(filedescriptor1)andstandarderror(filedescriptor2)tothefiledirlist,whilethecommand
ls 2>&1 > dirlist
directsonlythestandardoutputtofiledirlist,becausethestandarderrorwasmadeacopyofthestandardoutputbeforethestandardoutputwasredirectedtodirlist.
Bashhandlesseveralfilenamesspeciallywhentheyareusedinredirections,asdescribedinthefollowingtable:
/dev/fd/fd
Iffdisavalidinteger,filedescriptorfdisduplicated.
/dev/stdin
Filedescriptor0isduplicated.
/dev/stdout
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 32/158
Filedescriptor1isduplicated.
/dev/stderr
Filedescriptor2isduplicated.
/dev/tcp/host/port
IfhostisavalidhostnameorInternetaddress,andportisanintegerportnumberorservicename,BashattemptstoopenthecorrespondingTCPsocket.
/dev/udp/host/port
IfhostisavalidhostnameorInternetaddress,andportisanintegerportnumberorservicename,BashattemptstoopenthecorrespondingUDPsocket.
Afailuretoopenorcreateafilecausestheredirectiontofail.
Redirectionsusingfiledescriptorsgreaterthan9shouldbeusedwithcare,astheymayconflictwithfiledescriptorstheshellusesinternally.
3.6.1RedirectingInput
Redirectionofinputcausesthefilewhosenameresultsfromtheexpansionofwordtobeopenedforreadingonfiledescriptorn,orthestandardinput(filedescriptor0)ifnisnotspecified.
Thegeneralformatforredirectinginputis:
[n][|]word
Iftheredirectionoperatoris>,andthenoclobberoptiontothesetbuiltinhasbeenenabled,theredirectionwillfailifthefilewhosenameresultsfromtheexpansionofwordexistsandisaregularfile.Iftheredirectionoperatoris>|,ortheredirectionoperatoris>andthenoclobberoptionisnotenabled,theredirectionisattemptedevenifthefilenamedbywordexists.
3.6.3AppendingRedirectedOutput
Redirectionofoutputinthisfashioncausesthefilewhosenameresultsfromtheexpansionofwordtobeopenedforappendingonfiledescriptorn,orthestandardoutput(filedescriptor1)ifnisnotspecified.Ifthefiledoesnotexistitiscreated.
Thegeneralformatforappendingoutputis:
[n]>>word
3.6.4RedirectingStandardOutputandStandardError
Thisconstructallowsboththestandardoutput(filedescriptor1)andthestandarderroroutput(filedescriptor2)toberedirectedtothefilewhosenameistheexpansionofword.
Therearetwoformatsforredirectingstandardoutputandstandarderror:
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 33/158
&>word
and
>&word
Ofthetwoforms,thefirstispreferred.Thisissemanticallyequivalentto
>word 2>&1
Whenusingthesecondform,wordmaynotexpandtoanumberor-.Ifitdoes,otherredirectionoperatorsapply(seeDuplicatingFileDescriptorsbelow)forcompatibilityreasons.
3.6.5AppendingStandardOutputandStandardError
Thisconstructallowsboththestandardoutput(filedescriptor1)andthestandarderroroutput(filedescriptor2)tobeappendedtothefilewhosenameistheexpansionofword.
Theformatforappendingstandardoutputandstandarderroris:
&>>word
Thisissemanticallyequivalentto
>>word 2>&1
(seeDuplicatingFileDescriptorsbelow).
3.6.6HereDocuments
Thistypeofredirectioninstructstheshelltoreadinputfromthecurrentsourceuntilalinecontainingonlyword(withnotrailingblanks)isseen.Allofthelinesreaduptothatpointarethenusedasthestandardinputforacommand.
Theformatofheredocumentsis:
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 34/158
Theredirectionoperator
[n]&word
isusedsimilarlytoduplicateoutputfiledescriptors.Ifnisnotspecified,thestandardoutput(filedescriptor1)isused.Ifthedigitsinworddonotspecifyafiledescriptoropenforoutput,aredirectionerroroccurs.Ifwordevaluatesto-,filedescriptornisclosed.Asaspecialcase,ifnisomitted,andworddoesnotexpandtooneormoredigitsor-,thestandardoutputandstandarderrorareredirectedasdescribedpreviously.
3.6.9MovingFileDescriptors
Theredirectionoperator
[n]&digit-
movesthefiledescriptordigittofiledescriptorn,orthestandardoutput(filedescriptor1)ifnisnotspecified.
3.6.10OpeningFileDescriptorsforReadingandWriting
Theredirectionoperator
[n]word
causesthefilewhosenameistheexpansionofwordtobeopenedforbothreadingandwritingonfiledescriptorn,oronfiledescriptor0ifnisnotspecified.Ifthefiledoesnotexist,itiscreated.
Next:ShellScripts,Previous:Redirections,Up:BasicShellFeatures[Contents][Index]
3.7ExecutingCommands
SimpleCommandExpansion: HowBashexpandssimplecommandsbeforeexecutingthem.CommandSearchandExecution: HowBashfindscommandsandrunsthem.CommandExecutionEnvironment:TheenvironmentinwhichBashexecutescommandsthatarenotshellbuiltins.Environment: Theenvironmentgiventoacommand.ExitStatus: ThestatusreturnedbycommandsandhowBashinterpretsit.Signals: WhathappenswhenBashoracommanditrunsreceivesasignal.
Next:CommandSearchandExecution,Up:ExecutingCommands[Contents][Index]
3.7.1SimpleCommandExpansion
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 35/158
Whenasimplecommandisexecuted,theshellperformsthefollowingexpansions,assignments,andredirections,fromlefttoright.
1. Thewordsthattheparserhasmarkedasvariableassignments(thoseprecedingthecommandname)andredirectionsaresavedforlaterprocessing.
2. Thewordsthatarenotvariableassignmentsorredirectionsareexpanded(seeShellExpansions).Ifanywordsremainafterexpansion,thefirstwordistakentobethenameofthecommandandtheremainingwordsarethearguments.
3. Redirectionsareperformedasdescribedabove(seeRedirections).4. Thetextafterthe=ineachvariableassignmentundergoestildeexpansion,parameterexpansion,commandsubstitution,
arithmeticexpansion,andquoteremovalbeforebeingassignedtothevariable.
Ifnocommandnameresults,thevariableassignmentsaffectthecurrentshellenvironment.Otherwise,thevariablesareaddedtotheenvironmentoftheexecutedcommandanddonotaffectthecurrentshellenvironment.Ifanyoftheassignmentsattemptstoassignavaluetoareadonlyvariable,anerroroccurs,andthecommandexitswithanonzerostatus.
Ifnocommandnameresults,redirectionsareperformed,butdonotaffectthecurrentshellenvironment.Aredirectionerrorcausesthecommandtoexitwithanonzerostatus.
Ifthereisacommandnameleftafterexpansion,executionproceedsasdescribedbelow.Otherwise,thecommandexits.Ifoneoftheexpansionscontainedacommandsubstitution,theexitstatusofthecommandistheexitstatusofthelastcommandsubstitutionperformed.Iftherewerenocommandsubstitutions,thecommandexitswithastatusofzero.
Next:CommandExecutionEnvironment,Previous:SimpleCommandExpansion,Up:ExecutingCommands[Contents][Index]
3.7.2CommandSearchandExecution
Afteracommandhasbeensplitintowords,ifitresultsinasimplecommandandanoptionallistofarguments,thefollowingactionsaretaken.
1. Ifthecommandnamecontainsnoslashes,theshellattemptstolocateit.Ifthereexistsashellfunctionbythatname,thatfunctionisinvokedasdescribedinShellFunctions.
2. Ifthenamedoesnotmatchafunction,theshellsearchesforitinthelistofshellbuiltins.Ifamatchisfound,thatbuiltinisinvoked.
3. Ifthenameisneitherashellfunctionnorabuiltin,andcontainsnoslashes,Bashsearcheseachelementof$PATHforadirectorycontaininganexecutablefilebythatname.BashusesahashtabletorememberthefullpathnamesofexecutablefilestoavoidmultiplePATHsearches(seethedescriptionofhashinBourneShellBuiltins).Afullsearchofthedirectoriesin$PATHisperformedonlyifthecommandisnotfoundinthehashtable.Ifthesearchisunsuccessful,theshellsearchesforadefinedshellfunctionnamedcommand_not_found_handle.Ifthatfunctionexists,itisinvokedwiththeoriginalcommandandtheoriginalcommandsargumentsasitsarguments,andthefunctionsexitstatusbecomestheexitstatusoftheshell.Ifthatfunctionisnotdefined,theshellprintsanerrormessageandreturnsanexitstatusof127.
4. Ifthesearchissuccessful,orifthecommandnamecontainsoneormoreslashes,theshellexecutesthenamedprograminaseparateexecutionenvironment.Argument0issettothenamegiven,andtheremainingargumentstothecommandaresettotheargumentssupplied,ifany.
5. Ifthisexecutionfailsbecausethefileisnotinexecutableformat,andthefileisnotadirectory,itisassumedtobeashellscriptandtheshellexecutesitasdescribedinShellScripts.
6. Ifthecommandwasnotbegunasynchronously,theshellwaitsforthecommandtocompleteandcollectsitsexitstatus.
Next:Environment,Previous:CommandSearchandExecution,Up:ExecutingCommands[Contents][Index]
3.7.3CommandExecutionEnvironment
Theshellhasanexecutionenvironment,whichconsistsofthefollowing:
openfilesinheritedbytheshellatinvocation,asmodifiedbyredirectionssuppliedtotheexecbuiltinthecurrentworkingdirectoryassetbycd,pushd,orpopd,orinheritedbytheshellatinvocationthefilecreationmodemaskassetbyumaskorinheritedfromtheshellsparent
2/25/2015 Bash Reference Manual
http://www.gnu.org/software/bash/manual/bash.html#Commands-For-History 36/158