Professional Documents
Culture Documents
TableofContents
1Introduction 1.1WhatisBash? 1.2Whatisashell? 2Definitions 3BasicShellFeatures 3.1ShellSyntax 3.1.1ShellOperation 3.1.2Quoting 3.1.2.1EscapeCharacter 3.1.2.2SingleQuotes 3.1.2.3DoubleQuotes 3.1.2.4ANSICQuoting 3.1.2.5LocaleSpecificTranslation 3.1.3Comments 3.2ShellCommands 3.2.1SimpleCommands 3.2.2Pipelines 3.2.3ListsofCommands 3.2.4CompoundCommands 3.2.4.1LoopingConstructs 3.2.4.2ConditionalConstructs 3.2.4.3GroupingCommands 3.2.5Coprocesses 3.2.6GNUParallel 3.3ShellFunctions 3.4ShellParameters 3.4.1PositionalParameters 3.4.2SpecialParameters 3.5ShellExpansions 3.5.1BraceExpansion 3.5.2TildeExpansion 3.5.3ShellParameterExpansion 3.5.4CommandSubstitution 3.5.5ArithmeticExpansion 3.5.6ProcessSubstitution 3.5.7WordSplitting 3.5.8FilenameExpansion 3.5.8.1PatternMatching 3.5.9QuoteRemoval 3.6Redirections 3.6.1RedirectingInput 3.6.2RedirectingOutput 3.6.3AppendingRedirectedOutput 3.6.4RedirectingStandardOutputandStandardError 3.6.5AppendingStandardOutputandStandardError 3.6.6HereDocuments 3.6.7HereStrings 3.6.8DuplicatingFileDescriptors 3.6.9MovingFileDescriptors 3.6.10OpeningFileDescriptorsforReadingandWriting 3.7ExecutingCommands 3.7.1SimpleCommandExpansion 3.7.2CommandSearchandExecution 3.7.3CommandExecutionEnvironment 3.7.4Environment 3.7.5ExitStatus 3.7.6Signals 3.8ShellScripts 4ShellBuiltinCommands 4.1BourneShellBuiltins 4.2BashBuiltinCommands 4.3ModifyingShellBehavior 4.3.1TheSetBuiltin 4.3.2TheShoptBuiltin 4.4SpecialBuiltins 5ShellVariables
5.1BourneShellVariables 5.2BashVariables 6BashFeatures 6.1InvokingBash 6.2BashStartupFiles 6.3InteractiveShells 6.3.1WhatisanInteractiveShell? 6.3.2IsthisShellInteractive? 6.3.3InteractiveShellBehavior 6.4BashConditionalExpressions 6.5ShellArithmetic 6.6Aliases 6.7Arrays 6.8TheDirectoryStack 6.8.1DirectoryStackBuiltins 6.9ControllingthePrompt 6.10TheRestrictedShell 6.11BashPOSIXMode 7JobControl 7.1JobControlBasics 7.2JobControlBuiltins 7.3JobControlVariables 8CommandLineEditing 8.1IntroductiontoLineEditing 8.2ReadlineInteraction 8.2.1ReadlineBareEssentials 8.2.2ReadlineMovementCommands 8.2.3ReadlineKillingCommands 8.2.4ReadlineArguments 8.2.5SearchingforCommandsintheHistory 8.3ReadlineInitFile 8.3.1ReadlineInitFileSyntax 8.3.2ConditionalInitConstructs 8.3.3SampleInitFile 8.4BindableReadlineCommands 8.4.1CommandsForMoving 8.4.2CommandsForManipulatingTheHistory 8.4.3CommandsForChangingText 8.4.4KillingAndYanking 8.4.5SpecifyingNumericArguments 8.4.6LettingReadlineTypeForYou 8.4.7KeyboardMacros 8.4.8SomeMiscellaneousCommands 8.5ReadlineviMode 8.6ProgrammableCompletion 8.7ProgrammableCompletionBuiltins 9UsingHistoryInteractively 9.1BashHistoryFacilities 9.2BashHistoryBuiltins 9.3HistoryExpansion 9.3.1EventDesignators 9.3.2WordDesignators 9.3.3Modifiers 10InstallingBash 10.1BasicInstallation 10.2CompilersandOptions 10.3CompilingForMultipleArchitectures 10.4InstallationNames 10.5SpecifyingtheSystemType 10.6SharingDefaults 10.7OperationControls 10.8OptionalFeatures AppendixAReportingBugs AppendixBMajorDifferencesFromTheBourneShell B.1ImplementationDifferencesFromTheSVR4.2Shell AppendixCGNUFreeDocumentationLicense AppendixDIndexes D.1IndexofShellBuiltinCommands D.2IndexofShellReservedWords D.3ParameterandVariableIndex D.4FunctionIndex D.5ConceptIndex
Next:Introduction,Previous:(dir),Up:(dir)[Contents][Index]
BashFeatures
ThistextisabriefdescriptionofthefeaturesthatarepresentintheBashshell(version4.2,28December2010). ThisisEdition4.2,lastupdated28December2010,ofTheGNUBashReferenceManual,forB a s h ,Version4.2. Bashcontainsfeaturesthatappearinotherpopularshells,andsomefeaturesthatonlyappearinBash.SomeoftheshellsthatBashhasborrowed conceptsfromaretheBourneShell(s h ),theKornShell(k s h ),andtheCshell(c s h anditssuccessor,t c s h ).Thefollowingmenubreaksthefeatures upintocategoriesbaseduponwhichoneoftheseothershellsinspiredthefeature. ThismanualismeantasabriefintroductiontofeaturesfoundinBash.TheBashmanualpageshouldbeusedasthedefinitivereferenceonshell behavior. Introduction: Anintroductiontotheshell. Definitions: Somedefinitionsusedintherestofthismanual. BasicShellFeatures: Theshell"buildingblocks". ShellBuiltinCommands: Commandsthatareapartoftheshell. ShellVariables: VariablesusedorsetbyBash. BashFeatures: FeaturesfoundonlyinBash. JobControl: WhatjobcontrolisandhowBashallowsyoutouseit. CommandLineEditing: Chapterdescribingthecommandlineeditingfeatures. UsingHistoryInteractively: CommandHistoryExpansion InstallingBash: 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.ThenameisanacronymfortheB o u r n e A g a i nS H e l l ,apunon StephenBourne,theauthorofthedirectancestorofthecurrentUnixshells h ,whichappearedintheSeventhEditionBellLabsResearchversionof Unix. Bashislargelycompatiblewiths h andincorporatesusefulfeaturesfromtheKornshellk s h andtheCshellc s h .Itisintendedtobeaconformant implementationoftheIEEEPOSIXShellandToolsportionoftheIEEEPOSIXspecification(IEEEStandard1003.1).Itoffersfunctionalimprovements overs h forbothinteractiveandprogramminguse. WhiletheGNUoperatingsystemprovidesothershells,includingaversionofc s h ,Bashisthedefaultshell.LikeotherGNUsoftware,Bashisquite portable.ItcurrentlyrunsonnearlyeveryversionofUnixandafewotheroperatingsystemsindependentlysupportedportsexistforMSDOS,OS/2, andWindowsplatforms. Previous:WhatisBash?,Up:Introduction[Contents][Index]
1.2Whatisashell?
Atitsbase,ashellissimplyamacroprocessorthatexecutescommands.Thetermmacroprocessormeansfunctionalitywheretextandsymbolsare expandedtocreatelargerexpressions. AUnixshellisbothacommandinterpreterandaprogramminglanguage.Asacommandinterpreter,theshellprovidestheuserinterfacetotherichset ofGNUutilities.Theprogramminglanguagefeaturesallowtheseutilitiestobecombined.Filescontainingcommandscanbecreated,andbecome commandsthemselves.Thesenewcommandshavethesamestatusassystemcommandsindirectoriessuchas/ b i n ,allowingusersorgroupsto establishcustomenvironmentstoautomatetheircommontasks. Shellsmaybeusedinteractivelyornoninteractively.Ininteractivemode,theyacceptinputtypedfromthekeyboard.Whenexecutingnon interactively,shellsexecutecommandsreadfromafile. AshellallowsexecutionofGNUcommands,bothsynchronouslyandasynchronously.Theshellwaitsforsynchronouscommandstocompletebefore
acceptingmoreinputasynchronouscommandscontinuetoexecuteinparallelwiththeshellwhileitreadsandexecutesadditionalcommands.The redirectionconstructspermitfinegrainedcontroloftheinputandoutputofthosecommands.Moreover,theshellallowscontroloverthecontentsof commandsenvironments. Shellsalsoprovideasmallsetofbuiltincommands(builtins)implementingfunctionalityimpossibleorinconvenienttoobtainviaseparateutilities.For example,c d ,b r e a k ,c o n t i n u e ,ande x e c )cannotbeimplementedoutsideoftheshellbecausetheydirectlymanipulatetheshellitself.Theh i s t o r y , g e t o p t s ,k i l l ,orp w d builtins,amongothers,couldbeimplementedinseparateutilities,buttheyaremoreconvenienttouseasbuiltincommands.All oftheshellbuiltinsaredescribedinsubsequentsections. Whileexecutingcommandsisessential,mostofthepower(andcomplexity)ofshellsisduetotheirembeddedprogramminglanguages.Likeanyhigh levellanguage,theshellprovidesvariables,flowcontrolconstructs,quoting,andfunctions. Shellsofferfeaturesgearedspecificallyforinteractiveuseratherthantoaugmenttheprogramminglanguage.Theseinteractivefeaturesincludejob control,commandlineediting,commandhistoryandaliases.Eachofthesefeaturesisdescribedinthismanual. Next:BasicShellFeatures,Previous:Introduction,Up:Top[Contents][Index]
2Definitions
Thesedefinitionsareusedthroughouttheremainderofthismanual.
P O S I X
AfamilyofopensystemstandardsbasedonUnix.BashisprimarilyconcernedwiththeShellandUtilitiesportionofthePOSIX1003.1standard.
b l a n k
Aspaceortabcharacter.
b u i l t i n
Acommandthatisimplementedinternallybytheshellitself,ratherthanbyanexecutableprogramsomewhereinthefilesystem.
c o n t r o lo p e r a t o r
Thevaluereturnedbyacommandtoitscaller.Thevalueisrestrictedtoeightbits,sothemaximumvalueis255.
f i e l d
Aunitoftextthatistheresultofoneoftheshellexpansions.Afterexpansion,whenexecutingacommand,theresultingfieldsareusedasthe commandnameandarguments.
f i l e n a m e
Astringofcharactersusedtoidentifyafile.
j o b
Asetofprocessescomprisingapipeline,andanyprocessesdescendedfromit,thatareallinthesameprocessgroup.
j o bc o n t r o l
Amechanismbywhichuserscanselectivelystop(suspend)andrestart(resume)executionofprocesses.
m e t a c h a r a c t e r
AcollectionofrelatedprocesseseachhavingthesameprocessgroupID.
p r o c e s sg r o u pI D
Auniqueidentifierthatrepresentsap r o c e s sg r o u p duringitslifetime.
r e s e r v e dw o r d
Aw o r d thathasaspecialmeaningtotheshell.Mostreservedwordsintroduceshellflowcontrolconstructs,suchasf o r andw h i l e .
r e t u r ns t a t u s
Asynonymfore x i ts t a t u s .
s i g n a l
Amechanismbywhichaprocessmaybenotifiedbythekernelofaneventoccurringinthesystem.
s p e c i a lb u i l t i n
AshellbuiltincommandthathasbeenclassifiedasspecialbythePOSIXstandard.
t o k e n
Asequenceofcharactersconsideredasingleunitbytheshell.Itiseitheraw o r d orano p e r a t o r .
w o r d
Asequenceofcharacterstreatedasaunitbytheshell.Wordsmaynotincludeunquotedm e t a c h a r a c t e r s . Next:ShellBuiltinCommands,Previous:Definitions,Up:Top[Contents][Index]
3BasicShellFeatures
BashisanacronymforB o u r n e A g a i nS H e l l .TheBourneshellisthetraditionalUnixshelloriginallywrittenbyStephenBourne.AlloftheBourne shellbuiltincommandsareavailableinBash,TherulesforevaluationandquotingaretakenfromthePOSIXspecificationforthestandardUnixshell. Thischapterbrieflysummarizestheshellsbuildingblocks:commands,controlstructures,shellfunctions,shellparameters,shellexpansions, redirections,whichareawaytodirectinputandoutputfromandtonamedfiles,andhowtheshellexecutescommands. ShellSyntax: ShellCommands: ShellFunctions: ShellParameters: Whatyourinputmeanstotheshell. Thetypesofcommandsyoucanuse. Groupingcommandsbyname. Howtheshellstoresvalues.
3.1ShellSyntax
ShellOperation: Thebasicoperationoftheshell. Quoting: Howtoremovethespecialmeaningfromcharacters. Comments: Howtospecifycomments. Whentheshellreadsinput,itproceedsthroughasequenceofoperations.Iftheinputindicatesthebeginningofacomment,theshellignoresthe commentsymbol(# ),andtherestofthatline. Otherwise,roughlyspeaking,theshellreadsitsinputanddividestheinputintowordsandoperators,employingthequotingrulestoselectwhich meaningstoassignvariouswordsandcharacters. Theshellthenparsesthesetokensintocommandsandotherconstructs,removesthespecialmeaningofcertainwordsorcharacters,expandsothers, redirectsinputandoutputasneeded,executesthespecifiedcommand,waitsforthecommandsexitstatus,andmakesthatexitstatusavailablefor furtherinspectionorprocessing. Next:Quoting,Up:ShellSyntax[Contents][Index] 3.1.1ShellOperation Thefollowingisabriefdescriptionoftheshellsoperationwhenitreadsandexecutesacommand.Basically,theshelldoesthefollowing: 1. Readsitsinputfromafile(seeShellScripts),fromastringsuppliedasanargumenttothec invocationoption(seeInvokingBash),orfromthe usersterminal. 2. Breakstheinputintowordsandoperators,obeyingthequotingrulesdescribedinQuoting.Thesetokensareseparatedbym e t a c h a r a c t e r s . Aliasexpansionisperformedbythisstep(seeAliases). 3. Parsesthetokensintosimpleandcompoundcommands(seeShellCommands).
4. Performsthevariousshellexpansions(seeShellExpansions),breakingtheexpandedtokensintolistsoffilenames(seeFilenameExpansion)and commandsandarguments. 5. Performsanynecessaryredirections(seeRedirections)andremovestheredirectionoperatorsandtheiroperandsfromtheargumentlist. 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. LocaleTranslation: Howtotranslatestringsintodifferentlanguages. Quotingisusedtoremovethespecialmeaningofcertaincharactersorwordstotheshell.Quotingcanbeusedtodisablespecialtreatmentforspecial characters,topreventreservedwordsfrombeingrecognizedassuch,andtopreventparameterexpansion. Eachoftheshellmetacharacters(seeDefinitions)hasspecialmeaningtotheshellandmustbequotedifitistorepresentitself.Whenthecommand historyexpansionfacilitiesarebeingused(seeHistoryInteraction),thehistoryexpansioncharacter,usually! ,mustbequotedtopreventhistory expansion.SeeBashHistoryFacilities,formoredetailsconcerninghistoryexpansion. Therearethreequotingmechanisms:theescapecharacter,singlequotes,anddoublequotes. Next:SingleQuotes,Up:Quoting[Contents][Index] 3.1.2.1EscapeCharacter Anonquotedbackslash\ istheBashescapecharacter.Itpreservestheliteralvalueofthenextcharacterthatfollows,withtheexceptionofn e w l i n e . Ifa\ n e w l i n e pairappears,andthebackslashitselfisnotquoted,the\ n e w l i n e istreatedasalinecontinuation(thatis,itisremovedfromtheinput streamandeffectivelyignored). Next:DoubleQuotes,Previous:EscapeCharacter,Up:Quoting[Contents][Index] 3.1.2.2SingleQuotes Enclosingcharactersinsinglequotes(' )preservestheliteralvalueofeachcharacterwithinthequotes.Asinglequotemaynotoccurbetweensingle quotes,evenwhenprecededbyabackslash. Next:ANSICQuoting,Previous:SingleQuotes,Up:Quoting[Contents][Index] 3.1.2.3DoubleQuotes Enclosingcharactersindoublequotes(" )preservestheliteralvalueofallcharacterswithinthequotes,withtheexceptionof$ ,` ,\ ,and,when historyexpansionisenabled,! .Thecharacters$ and` retaintheirspecialmeaningwithindoublequotes(seeShellExpansions).Thebackslash retainsitsspecialmeaningonlywhenfollowedbyoneofthefollowingcharacters:$ ,` ," ,\ ,orn e w l i n e .Withindoublequotes,backslashesthat arefollowedbyoneofthesecharactersareremoved.Backslashesprecedingcharacterswithoutaspecialmeaningareleftunmodified.Adoublequote maybequotedwithindoublequotesbyprecedingitwithabackslash.Ifenabled,historyexpansionwillbeperformedunlessan! appearingindouble quotesisescapedusingabackslash.Thebackslashprecedingthe! isnotremoved. Thespecialparameters* and@ havespecialmeaningwhenindoublequotes(seeShellParameterExpansion). Next:LocaleTranslation,Previous:DoubleQuotes,Up:Quoting[Contents][Index] 3.1.2.4ANSICQuoting Wordsoftheform$ ' s t r i n g ' aretreatedspecially.Thewordexpandstostring,withbackslashescapedcharactersreplacedasspecifiedbytheANSI Cstandard.Backslashescapesequences,ifpresent,aredecodedasfollows:
\ a
alert(bell)
\ b
backspace
\ e
\ E
anescapecharacter(notANSIC)
\ f
formfeed
\ n
newline
\ r
carriagereturn
\ t
horizontaltab
\ v
verticaltab
\ \
backslash
\ '
singlequote
\ "
doublequote
\ n n n
theeightbitcharacterwhosevalueistheoctalvaluennn(onetothreedigits)
\ x H H
theeightbitcharacterwhosevalueisthehexadecimalvalueHH(oneortwohexdigits)
\ u H H H H
theUnicode(ISO/IEC10646)characterwhosevalueisthehexadecimalvalueHHHH(onetofourhexdigits)
\ U H H H H H H H H
theUnicode(ISO/IEC10646)characterwhosevalueisthehexadecimalvalueHHHHHHHH(onetoeighthexdigits)
\ c x
acontrolxcharacter Theexpandedresultissinglequoted,asifthedollarsignhadnotbeenpresent. Previous:ANSICQuoting,Up:Quoting[Contents][Index] 3.1.2.5LocaleSpecificTranslation Adoublequotedstringprecededbyadollarsign($ )willcausethestringtobetranslatedaccordingtothecurrentlocale.IfthecurrentlocaleisC or P O S I X ,thedollarsignisignored.Ifthestringistranslatedandreplaced,thereplacementisdoublequoted. SomesystemsusethemessagecatalogselectedbytheL C _ M E S S A G E S shellvariable.Otherscreatethenameofthemessagecatalogfromthevalueofthe T E X T D O M A I N shellvariable,possiblyaddingasuffixof. m o .IfyouusetheT E X T D O M A I N variable,youmayneedtosettheT E X T D O M A I N D I R variableto thelocationofthemessagecatalogfiles.Stillothersusebothvariablesinthisfashion: T E X T D O M A I N D I R /L C _ M E S S A G E S /LC_MESSAGES/T E X T D O M A I N .mo. Previous:Quoting,Up:ShellSyntax[Contents][Index] 3.1.3Comments Inanoninteractiveshell,oraninteractiveshellinwhichthei n t e r a c t i v e _ c o m m e n t s optiontothes h o p t builtinisenabled(seeTheShoptBuiltin),a wordbeginningwith# causesthatwordandallremainingcharactersonthatlinetobeignored.Aninteractiveshellwithoutthe i n t e r a c t i v e _ c o m m e n t s optionenableddoesnotallowcomments.Thei n t e r a c t i v e _ c o m m e n t s optionisonbydefaultininteractiveshells.See InteractiveShells,foradescriptionofwhatmakesashellinteractive.
Next:ShellFunctions,Previous:ShellSyntax,Up:BasicShellFeatures[Contents][Index]
3.2ShellCommands
Asimpleshellcommandsuchase c h oabc consistsofthecommanditselffollowedbyarguments,separatedbyspaces. Morecomplexshellcommandsarecomposedofsimplecommandsarrangedtogetherinavarietyofways:inapipelineinwhichtheoutputofone commandbecomestheinputofasecond,inalooporconditionalconstruct,orinsomeothergrouping. SimpleCommands: Themostcommontypeofcommand. Pipelines: Connectingtheinputandoutputofseveralcommands. Lists: Howtoexecutecommandssequentially. CompoundCommands: Shellcommandsforcontrolflow. Coprocesses: Twowaycommunicationbetweencommands. GNUParallel: Runningcommandsinparallel. Next:Pipelines,Up:ShellCommands[Contents][Index] 3.2.1SimpleCommands Asimplecommandisthekindofcommandencounteredmostoften.Itsjustasequenceofwordsseparatedbyb l a n k s,terminatedbyoneoftheshells controloperators(seeDefinitions).Thefirstwordgenerallyspecifiesacommandtobeexecuted,withtherestofthewordsbeingthatcommands arguments. Thereturnstatus(seeExitStatus)ofasimplecommandisitsexitstatusasprovidedbythePOSIX1003.1w a i t p i d function,or128+nifthecommand wasterminatedbysignaln. Next:Lists,Previous:SimpleCommands,Up:ShellCommands[Contents][Index] 3.2.2Pipelines Ap i p e l i n e isasequenceofsimplecommandsseparatedbyoneofthecontroloperators| or| & . Theformatforapipelineis
[ t i m e[ p ] ][ ! ]c o m m a n d 1[[ |o r| & ]c o m m a n d 2 ]
Theoutputofeachcommandinthepipelineisconnectedviaapipetotheinputofthenextcommand.Thatis,eachcommandreadstheprevious commandsoutput.Thisconnectionisperformedbeforeanyredirectionsspecifiedbythecommand. If| & isused,thestandarderrorofcommand1isconnectedtocommand2sstandardinputthroughthepipeitisshorthandfor2 > & 1| .Thisimplicit redirectionofthestandarderrorisperformedafteranyredirectionsspecifiedbythecommand. Thereservedwordt i m e causestimingstatisticstobeprintedforthepipelineonceitfinishes.Thestatisticscurrentlyconsistofelapsed(wallclock)time anduserandsystemtimeconsumedbythecommandsexecution.Thep optionchangestheoutputformattothatspecifiedbyPOSIX.Whentheshell isinPOSIXmode(seeBashPOSIXMode),itdoesnotrecognizet i m e asareservedwordifthenexttokenbeginswitha.TheT I M E F O R M A T variable maybesettoaformatstringthatspecifieshowthetiminginformationshouldbedisplayed.SeeBashVariables,foradescriptionoftheavailable formats.Theuseoft i m e asareservedwordpermitsthetimingofshellbuiltins,shellfunctions,andpipelines.Anexternalt i m e commandcannottime theseeasily. WhentheshellisinPOSIXmode(seeBashPOSIXMode),t i m e maybefollowedbyanewline.Inthiscase,theshelldisplaysthetotaluserandsystem timeconsumedbytheshellanditschildren.TheT I M E F O R M A T variablemaybeusedtospecifytheformatofthetimeinformation. Ifthepipelineisnotexecutedasynchronously(seeLists),theshellwaitsforallcommandsinthepipelinetocomplete. Eachcommandinapipelineisexecutedinitsownsubshell(seeCommandExecutionEnvironment).Theexitstatusofapipelineistheexitstatusof thelastcommandinthepipeline,unlessthep i p e f a i l optionisenabled(seeTheSetBuiltin).Ifp i p e f a i l isenabled,thepipelinesreturnstatusisthe valueofthelast(rightmost)commandtoexitwithanonzerostatus,orzeroifallcommandsexitsuccessfully.Ifthereservedword! precedesthe pipeline,theexitstatusisthelogicalnegationoftheexitstatusasdescribedabove.Theshellwaitsforallcommandsinthepipelinetoterminatebefore returningavalue. Next:CompoundCommands,Previous:Pipelines,Up:ShellCommands[Contents][Index] 3.2.3ListsofCommands Al i s t isasequenceofoneormorepipelinesseparatedbyoneoftheoperators; ,& ,& & ,or| | ,andoptionallyterminatedbyoneof; ,& ,ora n e w l i n e . Oftheselistoperators,& & and| | haveequalprecedence,followedby; and& ,whichhaveequalprecedence. Asequenceofoneormorenewlinesmayappearinal i s t todelimitcommands,equivalenttoasemicolon.
withleftassociativity. AnANDlisthastheform
c o m m a n d 1& &c o m m a n d 2
command2isexecutedif,andonlyif,command1returnsanexitstatusofzero. AnORlisthastheform
c o m m a n d 1| |c o m m a n d 2
command2isexecutedif,andonlyif,command1returnsanonzeroexitstatus. ThereturnstatusofANDandORlistsistheexitstatusofthelastcommandexecutedinthelist. Next:Coprocesses,Previous:Lists,Up:ShellCommands[Contents][Index] 3.2.4CompoundCommands LoopingConstructs: Shellcommandsforiterativeaction. ConditionalConstructs: Shellcommandsforconditionalexecution. CommandGrouping: Waystogroupcommands. Compoundcommandsaretheshellprogrammingconstructs.Eachconstructbeginswithareservedwordorcontroloperatorandisterminatedbya correspondingreservedwordoroperator.Anyredirections(seeRedirections)associatedwithacompoundcommandapplytoallcommandswithinthat compoundcommandunlessexplicitlyoverridden. Bashprovidesloopingconstructs,conditionalcommands,andmechanismstogroupcommandsandexecutethemasaunit. Next:ConditionalConstructs,Up:CompoundCommands[Contents][Index] 3.2.4.1LoopingConstructs Bashsupportsthefollowingloopingconstructs. Notethatwherevera; appearsinthedescriptionofacommandssyntax,itmaybereplacedwithoneormorenewlines.
u n t i l
Thesyntaxoftheu n t i l commandis:
u n t i lt e s t c o m m a n d s ;d oc o n s e q u e n t c o m m a n d s ;d o n e
Executeconsequentcommandsaslongastestcommandshasanexitstatuswhichisnotzero.Thereturnstatusistheexitstatusofthelast commandexecutedinconsequentcommands,orzeroifnonewasexecuted.
w h i l e
Thesyntaxofthew h i l e commandis:
w h i l et e s t c o m m a n d s ;d oc o n s e q u e n t c o m m a n d s ;d o n e
Executeconsequentcommandsaslongastestcommandshasanexitstatusofzero.Thereturnstatusistheexitstatusofthelastcommand executedinconsequentcommands,orzeroifnonewasexecuted.
f o r
Thesyntaxofthef o r commandis:
f o rn a m e[[ i n[ w o r d s ]];]d oc o m m a n d s ;d o n e
Expandwords,andexecutecommandsonceforeachmemberintheresultantlist,withnameboundtothecurrentmember.Ifi nw o r d s isnot present,thef o r commandexecutesthecommandsonceforeachpositionalparameterthatisset,asifi n" $ @ " hadbeenspecified(seeSpecial Parameters).Thereturnstatusistheexitstatusofthelastcommandthatexecutes.Iftherearenoitemsintheexpansionofwords,nocommands areexecuted,andthereturnstatusiszero. Analternateformofthef o r commandisalsosupported:
Thesyntaxofthei f commandis:
i ft e s t c o m m a n d s ;t h e n c o n s e q u e n t c o m m a n d s ; [ e l i fm o r e t e s t c o m m a n d s ;t h e n m o r e c o n s e q u e n t s ; ] [ e l s ea l t e r n a t e c o n s e q u e n t s ; ] f i
Thesyntaxofthec a s e commandis:
c a s ew o r di n[[ ( ]p a t t e r n[ |p a t t e r n ] )c o m m a n d l i s t; ; ] e s a c c a s e willselectivelyexecutethecommandlistcorrespondingtothefirstpatternthatmatchesword.Iftheshelloptionn o c a s e m a t c h (seethe descriptionofs h o p t inTheShoptBuiltin)isenabled,thematchisperformedwithoutregardtothecaseofalphabeticcharacters.The| isused toseparatemultiplepatterns,andthe) operatorterminatesapatternlist.Alistofpatternsandanassociatedcommandlistisknownasaclause.
Eachclausemustbeterminatedwith; ; ,; & ,or; ; & .Thewordundergoestildeexpansion,parameterexpansion,commandsubstitution, arithmeticexpansion,andquoteremovalbeforematchingisattempted.Eachpatternundergoestildeexpansion,parameterexpansion,command substitution,andarithmeticexpansion. Theremaybeanarbitrarynumberofc a s e clauses,eachterminatedbya; ; ,; & ,or; ; & .Thefirstpatternthatmatchesdeterminesthe commandlistthatisexecuted. Hereisanexampleusingc a s e inascriptthatcouldbeusedtodescribeoneinterestingfeatureofananimal:
e c h on" E n t e rt h en a m eo fa na n i m a l :" r e a dA N I M A L e c h on" T h e$ A N I M A Lh a s" c a s e$ A N I M A Li n h o r s e|d o g|c a t )e c h on" f o u r " ; ; m a n|k a n g a r o o)e c h on" t w o " ; ; * )e c h on" a nu n k n o w nn u m b e ro f " ; ; e s a c e c h o"l e g s . "
Ifthe; ; operatorisused,nosubsequentmatchesareattemptedafterthefirstpatternmatch.Using; & inplaceof; ; causesexecutionto continuewiththecommandlistassociatedwiththenextclause,ifany.Using; ; & inplaceof; ; causestheshelltotestthepatternsinthenext clause,ifany,andexecuteanyassociatedcommandlistonasuccessfulmatch. Thereturnstatusiszeroifnopatternismatched.Otherwise,thereturnstatusistheexitstatusofthecommandlistexecuted.
s e l e c t
Thelistofwordsfollowingi n isexpanded,generatingalistofitems.Thesetofexpandedwordsisprintedonthestandarderroroutputstream, eachprecededbyanumber.Ifthei nw o r d s isomitted,thepositionalparametersareprinted,asifi n" $ @ " hadbeenspecified.TheP S 3 promptisthendisplayedandalineisreadfromthestandardinput.Ifthelineconsistsofanumbercorrespondingtooneofthedisplayedwords, thenthevalueofnameissettothatword.Ifthelineisempty,thewordsandpromptaredisplayedagain.IfE O F isread,thes e l e c t command completes.Anyothervaluereadcausesnametobesettonull.ThelinereadissavedinthevariableR E P L Y . Thecommandsareexecutedaftereachselectionuntilab r e a k commandisexecuted,atwhichpointthes e l e c t commandcompletes. Hereisanexamplethatallowstheusertopickafilenamefromthecurrentdirectory,anddisplaysthenameandindexofthefileselected.
s e l e c tf n a m ei n* ; d o e c h oy o up i c k e d$ f n a m e\ ( $ R E P L Y \ ) b r e a k ; d o n e ( ( ) ) ( (e x p r e s s i o n) )
Thearithmeticexpressionisevaluatedaccordingtotherulesdescribedbelow(seeShellArithmetic).Ifthevalueoftheexpressionisnonzero, thereturnstatusis0otherwisethereturnstatusis1.Thisisexactlyequivalentto
l e t" e x p r e s s i o n "
SeeBashBuiltins,forafulldescriptionofthel e t builtin.
[ [ ] ] [ [e x p r e s s i o n] ]
Returnastatusof0or1dependingontheevaluationoftheconditionalexpressionexpression.Expressionsarecomposedoftheprimaries describedbelowinBashConditionalExpressions.Wordsplittingandfilenameexpansionarenotperformedonthewordsbetweenthe[ [ and ] ] tildeexpansion,parameterandvariableexpansion,arithmeticexpansion,commandsubstitution,processsubstitution,andquoteremovalare performed.Conditionaloperatorssuchasf mustbeunquotedtoberecognizedasprimaries. Whenusedwith[ [ ,the< and> operatorssortlexicographicallyusingthecurrentlocale. Whenthe= = and! = operatorsareused,thestringtotherightoftheoperatorisconsideredapatternandmatchedaccordingtotherules describedbelowinPatternMatching.Iftheshelloptionn o c a s e m a t c h (seethedescriptionofs h o p t inTheShoptBuiltin)isenabled,thematchis performedwithoutregardtothecaseofalphabeticcharacters.Thereturnvalueis0ifthestringmatches(= = )ordoesnotmatch(! = )the pattern,and1otherwise.Anypartofthepatternmaybequotedtoforceittobematchedasastring. Anadditionalbinaryoperator,= ~ ,isavailable,withthesameprecedenceas= = and! = .Whenitisused,thestringtotherightoftheoperator isconsideredanextendedregularexpressionandmatchedaccordingly(asinregex3)).Thereturnvalueis0ifthestringmatchesthepattern,and 1otherwise.Iftheregularexpressionissyntacticallyincorrect,theconditionalexpressionsreturnvalueis2.Iftheshelloptionn o c a s e m a t c h (see thedescriptionofs h o p t inTheShoptBuiltin)isenabled,thematchisperformedwithoutregardtothecaseofalphabeticcharacters.Anypartof thepatternmaybequotedtoforceittobematchedasastring.Substringsmatchedbyparenthesizedsubexpressionswithintheregularexpression aresavedinthearrayvariableB A S H _ R E M A T C H .TheelementofB A S H _ R E M A T C H withindex0istheportionofthestringmatchingtheentireregular expression.TheelementofB A S H _ R E M A T C H withindexnistheportionofthestringmatchingthenthparenthesizedsubexpression. Expressionsmaybecombinedusingthefollowingoperators,listedindecreasingorderofprecedence:
(e x p r e s s i o n)
Returnsthevalueofexpression.Thismaybeusedtooverridethenormalprecedenceofoperators.
!e x p r e s s i o n
Trueifexpressionisfalse.
e x p r e s s i o n 1& &e x p r e s s i o n 2
Trueifbothexpression1andexpression2aretrue.
e x p r e s s i o n 1| |e x p r e s s i o n 2
Trueifeitherexpression1orexpression2istrue. The& & and| | operatorsdonotevaluateexpression2ifthevalueofexpression1issufficienttodeterminethereturnvalueoftheentire conditionalexpression. Previous:ConditionalConstructs,Up:CompoundCommands[Contents][Index] 3.2.4.3GroupingCommands Bashprovidestwowaystogroupalistofcommandstobeexecutedasaunit.Whencommandsaregrouped,redirectionsmaybeappliedtotheentire commandlist.Forexample,theoutputofallthecommandsinthelistmayberedirectedtoasinglestream.
( ) (l i s t)
Placingalistofcommandsbetweencurlybracescausesthelisttobeexecutedinthecurrentshellcontext.Nosubshelliscreated.Thesemicolon (ornewline)followinglistisrequired. Inadditiontothecreationofasubshell,thereisasubtledifferencebetweenthesetwoconstructsduetohistoricalreasons.Thebracesarer e s e r v e d w o r d s ,sotheymustbeseparatedfromthelistbyb l a n k sorothershellmetacharacters.Theparenthesesareo p e r a t o r s ,andarerecognizedasseparate tokensbytheshelleveniftheyarenotseparatedfromthelistbywhitespace. Theexitstatusofbothoftheseconstructsistheexitstatusoflist. Next:GNUParallel,Previous:CompoundCommands,Up:ShellCommands[Contents][Index] 3.2.5Coprocesses Ac o p r o c e s s isashellcommandprecededbythec o p r o c reservedword.Acoprocessisexecutedasynchronouslyinasubshell,asifthecommand hadbeenterminatedwiththe& controloperator,withatwowaypipeestablishedbetweentheexecutingshellandthecoprocess. Theformatforacoprocessis:
c o p r o c[ N A M E ]c o m m a n d[ r e d i r e c t i o n s ]
ThiscreatesacoprocessnamedNAME.IfNAMEisnotsupplied,thedefaultnameisCOPROC.NAMEmustnotbesuppliedifcommandisasimple command(seeSimpleCommands)otherwise,itisinterpretedasthefirstwordofthesimplecommand. Whenthecoprocisexecuted,theshellcreatesanarrayvariable(seeArrays)namedNAMEinthecontextoftheexecutingshell.Thestandardoutputof commandisconnectedviaapipetoafiledescriptorintheexecutingshell,andthatfiledescriptorisassignedtoNAME[0].Thestandardinputof commandisconnectedviaapipetoafiledescriptorintheexecutingshell,andthatfiledescriptorisassignedtoNAME[1].Thispipeisestablished beforeanyredirectionsspecifiedbythecommand(seeRedirections).Thefiledescriptorscanbeutilizedasargumentstoshellcommandsand redirectionsusingstandardwordexpansions. TheprocessIDoftheshellspawnedtoexecutethecoprocessisavailableasthevalueofthevariableNAME_PID.Thew a i t builtincommandmaybe usedtowaitforthecoprocesstoterminate. Thereturnstatusofacoprocessistheexitstatusofcommand. Previous:Coprocesses,Up:ShellCommands[Contents][Index] 3.2.6GNUParallel GNUParallel,asitsnamesuggests,canbeusedtobuildandruncommandsinparallel.Youmayrunthesamecommandwithdifferentarguments, whethertheyarefilenames,usernames,hostnames,orlinesreadfromfiles. Foracompletedescription,refertotheGNUParalleldocumentation.Afewexamplesshouldprovideabriefintroductiontoitsuse. Forexample,itiseasytoprefixeachlineinatextfilewithaspecifiedstring:
c a tf i l e|p a r a l l e lke c h op r e f i x _ s t r i n g
YoucanuseParalleltomovefilesfromthecurrentdirectorywhenthenumberoffilesistoolargetoprocesswithonem v invocation:
l s|p a r a l l e lm v{ }d e s t d i r
GNUParallelcanreplacecertaincommonidiomsthatoperateonlinesreadfromafile(inthiscase,filenames):
f o rxi n$ ( c a tl i s t ) ;d o d o s o m e t h i n g 1$ xc o n f i g $ x d o s o m e t h i n g 2<$ x d o n e|p r o c e s s o u t p u t
withamorecompactsyntaxreminiscentoflambdas:
c a tl i s t|p a r a l l e l" d o s o m e t h i n g 1{ }c o n f i g { };d o s o m e t h i n g 2<{ } "|p r o c e s s o u t p u t
Parallelprovidesabuiltinmechanismtoremovefilenameextensions,whichlendsitselftobatchfiletransformationsorrenaming:
l s* . g z|p a r a l l e lj + 0" z c a t{ }|b z i p 2> { . } . b z 2& &r m{ } "
Thiswillrecompressallfilesinthecurrentdirectorywithnamesendingin.gzusingbzip2,runningonejobperCPU(j+0)inparallel. Ifacommandgeneratesoutput,youmaywanttopreservetheinputorderintheoutput.Forinstance,thefollowingcommand
{e c h of o s s . o r g . m y;e c h od e b i a n . o r g ;e c h of r e e n e t p r o j e c t . o r g ;}|p a r a l l e lt r a c e r o u t e
willdisplayasoutputthetracerouteinvocationthatfinishesfirst.Usingthek option,aswesawabove
{e c h of o s s . o r g . m y;e c h od e b i a n . o r g ;e c h of r e e n e t p r o j e c t . o r g ;}|p a r a l l e lkt r a c e r o u t e
3.3ShellFunctions
Shellfunctionsareawaytogroupcommandsforlaterexecutionusingasinglenameforthegroup.Theyareexecutedjustlikea"regular"command. Whenthenameofashellfunctionisusedasasimplecommandname,thelistofcommandsassociatedwiththatfunctionnameisexecuted.Shell functionsareexecutedinthecurrentshellcontextnonewprocessiscreatedtointerpretthem. Functionsaredeclaredusingthissyntax:
n a m e( )c o m p o u n d c o m m a n d[r e d i r e c t i o n s] o r f u n c t i o nn a m e[ ( ) ]c o m p o u n d c o m m a n d[r e d i r e c t i o n s]
Thisdefinesashellfunctionnamedname.Thereservedwordf u n c t i o n isoptional.Ifthef u n c t i o n reservedwordissupplied,theparenthesesare optional.Thebodyofthefunctionisthecompoundcommandcompoundcommand(seeCompoundCommands).Thatcommandisusuallyalist enclosedbetween{and},butmaybeanycompoundcommandlistedabove.compoundcommandisexecutedwhenevernameisspecifiedasthe nameofacommand.Anyredirections(seeRedirections)associatedwiththeshellfunctionareperformedwhenthefunctionisexecuted. Afunctiondefinitionmaybedeletedusingthef optiontotheu n s e t builtin(seeBourneShellBuiltins). Theexitstatusofafunctiondefinitioniszerounlessasyntaxerroroccursorareadonlyfunctionwiththesamenamealreadyexists.Whenexecuted, theexitstatusofafunctionistheexitstatusofthelastcommandexecutedinthebody. Notethatforhistoricalreasons,inthemostcommonusagethecurlybracesthatsurroundthebodyofthefunctionmustbeseparatedfromthebodyby b l a n k sornewlines.Thisisbecausethebracesarereservedwordsandareonlyrecognizedassuchwhentheyareseparatedfromthecommandlistby whitespaceoranothershellmetacharacter.Also,whenusingthebraces,thelistmustbeterminatedbyasemicolon,a& ,oranewline. Whenafunctionisexecuted,theargumentstothefunctionbecomethepositionalparametersduringitsexecution(seePositionalParameters).The specialparameter# thatexpandstothenumberofpositionalparametersisupdatedtoreflectthechange.Specialparameter0 isunchanged.Thefirst elementoftheF U N C N A M E variableissettothenameofthefunctionwhilethefunctionisexecuting. Allotheraspectsoftheshellexecutionenvironmentareidenticalbetweenafunctionanditscallerwiththeseexceptions:theD E B U G andR E T U R N traps arenotinheritedunlessthefunctionhasbeengiventhet r a c e attributeusingthed e c l a r e builtinortheof u n c t r a c e optionhasbeenenabledwith thes e t builtin,(inwhichcaseallfunctionsinherittheD E B U G andR E T U R N traps),andtheE R R trapisnotinheritedunlesstheoe r r t r a c e shelloption hasbeenenabled.SeeBourneShellBuiltins,forthedescriptionofthet r a p builtin. TheF U N C N E S T variable,ifsettoanumericvaluegreaterthan0,definesamaximumfunctionnestinglevel.Functioninvocationsthatexceedthelimit causetheentirecommandtoabort. Ifthebuiltincommandr e t u r n isexecutedinafunction,thefunctioncompletesandexecutionresumeswiththenextcommandafterthefunctioncall. AnycommandassociatedwiththeR E T U R N trapisexecutedbeforeexecutionresumes.Whenafunctioncompletes,thevaluesofthepositional parametersandthespecialparameter# arerestoredtothevaluestheyhadpriortothefunctionsexecution.Ifanumericargumentisgiventor e t u r n , thatisthefunctionsreturnstatusotherwisethefunctionsreturnstatusistheexitstatusofthelastcommandexecutedbeforether e t u r n . Variableslocaltothefunctionmaybedeclaredwiththel o c a l builtin.Thesevariablesarevisibleonlytothefunctionandthecommandsitinvokes. Functionnamesanddefinitionsmaybelistedwiththef optiontothed e c l a r e ort y p e s e t builtincommands(seeBashBuiltins).TheF optionto d e c l a r e ort y p e s e t willlistthefunctionnamesonly(andoptionallythesourcefileandlinenumber,ifthee x t d e b u g shelloptionisenabled). Functionsmaybeexportedsothatsubshellsautomaticallyhavethemdefinedwiththef optiontothee x p o r t builtin(seeBourneShellBuiltins).Note thatshellfunctionsandvariableswiththesamenamemayresultinmultipleidenticallynamedentriesintheenvironmentpassedtotheshellschildren. Careshouldbetakenincaseswherethismaycauseaproblem. Functionsmayberecursive.TheF U N C N E S T variablemaybeusedtolimitthedepthofthefunctioncallstackandrestrictthenumberoffunction invocations.Bydefault,nolimitisplacedonthenumberofrecursivecalls. Next:ShellExpansions,Previous:ShellFunctions,Up:BasicShellFeatures[Contents][Index]
3.4ShellParameters
PositionalParameters: Theshellscommandlinearguments. SpecialParameters: Parametersdenotedbyspecialcharacters.
Aparameterisanentitythatstoresvalues.Itcanbean a m e ,anumber,oroneofthespecialcharacterslistedbelow.Avariableisaparameterdenoted byan a m e .Avariablehasavalueandzeroormoreattributes.Attributesareassignedusingthed e c l a r e builtincommand(seethedescriptionofthe d e c l a r e builtininBashBuiltins). Aparameterissetifithasbeenassignedavalue.Thenullstringisavalidvalue.Onceavariableisset,itmaybeunsetonlybyusingtheu n s e t builtin command. Avariablemaybeassignedtobyastatementoftheform
n a m e = [ v a l u e ]
Ifvalueisnotgiven,thevariableisassignedthenullstring.Allvaluesundergotildeexpansion,parameterandvariableexpansion,command substitution,arithmeticexpansion,andquoteremoval(detailedbelow).Ifthevariablehasitsi n t e g e r attributeset,thenvalueisevaluatedasan arithmeticexpressionevenifthe$ ( ( ) ) expansionisnotused(seeArithmeticExpansion).Wordsplittingisnotperformed,withtheexceptionof" $ @ " asexplainedbelow.Filenameexpansionisnotperformed.Assignmentstatementsmayalsoappearasargumentstothea l i a s ,d e c l a r e ,t y p e s e t , e x p o r t ,r e a d o n l y ,andl o c a l builtincommands. Inthecontextwhereanassignmentstatementisassigningavaluetoashellvariableorarrayindex(seeArrays),the+ = operatorcanbeusedtoappend tooraddtothevariablespreviousvalue.When+ = isappliedtoavariableforwhichtheintegerattributehasbeenset,valueisevaluatedasan arithmeticexpressionandaddedtothevariablescurrentvalue,whichisalsoevaluated.When+ = isappliedtoanarrayvariableusingcompound assignment(seeArrays),thevariablesvalueisnotunset(asitiswhenusing= ),andnewvaluesareappendedtothearraybeginningatonegreater thanthearraysmaximumindex(forindexedarrays),oraddedasadditionalkeyvaluepairsinanassociativearray.Whenappliedtoastringvalued variable,valueisexpandedandappendedtothevariablesvalue. Next:SpecialParameters,Up:ShellParameters[Contents][Index] 3.4.1PositionalParameters Apositionalparameterisaparameterdenotedbyoneormoredigits,otherthanthesingledigit0 .Positionalparametersareassignedfromtheshells argumentswhenitisinvoked,andmaybereassignedusingthes e t builtincommand.PositionalparameterN maybereferencedas$ { N } ,oras$ N when N consistsofasingledigit.Positionalparametersmaynotbeassignedtowithassignmentstatements.Thes e t ands h i f t builtinsareusedtosetand unsetthem(seeShellBuiltinCommands).Thepositionalparametersaretemporarilyreplacedwhenashellfunctionisexecuted(seeShellFunctions). Whenapositionalparameterconsistingofmorethanasingledigitisexpanded,itmustbeenclosedinbraces. Previous:PositionalParameters,Up:ShellParameters[Contents][Index] 3.4.2SpecialParameters Theshelltreatsseveralparametersspecially.Theseparametersmayonlybereferencedassignmenttothemisnotallowed.
*
Expandstothepositionalparameters,startingfromone.Whentheexpansionoccurswithindoublequotes,itexpandstoasinglewordwiththe valueofeachparameterseparatedbythefirstcharacteroftheI F S specialvariable.Thatis," $ * " isequivalentto" $ 1 c $ 2 c " ,wherecisthefirst characterofthevalueoftheI F S variable.IfI F S isunset,theparametersareseparatedbyspaces.IfI F S isnull,theparametersarejoinedwithout interveningseparators.
@
Expandstothepositionalparameters,startingfromone.Whentheexpansionoccurswithindoublequotes,eachparameterexpandstoaseparate word.Thatis," $ @ " isequivalentto" $ 1 "" $ 2 " .Ifthedoublequotedexpansionoccurswithinaword,theexpansionofthefirstparameteris joinedwiththebeginningpartoftheoriginalword,andtheexpansionofthelastparameterisjoinedwiththelastpartoftheoriginalword.When therearenopositionalparameters," $ @ " and$ @ expandtonothing(i.e.,theyareremoved).
#
Expandstothenumberofpositionalparametersindecimal.
?
Expandstotheexitstatusofthemostrecentlyexecutedforegroundpipeline.
-
ExpandstotheprocessIDoftheshell.Ina( ) subshell,itexpandstotheprocessIDoftheinvokingshell,notthesubshell.
!
ExpandstotheprocessIDofthemostrecentlyexecutedbackground(asynchronous)command.
3.5ShellExpansions
Expansionisperformedonthecommandlineafterithasbeensplitintot o k e n s.Therearesevenkindsofexpansionperformed: braceexpansion tildeexpansion parameterandvariableexpansion commandsubstitution arithmeticexpansion wordsplitting filenameexpansion BraceExpansion: Expansionofexpressionswithinbraces. TildeExpansion: Expansionofthe~character. ShellParameterExpansion: HowBashexpandsvariablestotheirvalues. CommandSubstitution: Usingtheoutputofacommandasanargument. ArithmeticExpansion: Howtousearithmeticinshellexpansions. ProcessSubstitution: Awaytowriteandreadtoandfromacommand. WordSplitting: Howtheresultsofexpansionaresplitintoseparatearguments. FilenameExpansion: Ashorthandforspecifyingfilenamesmatchingpatterns. QuoteRemoval: Howandwhenquotecharactersareremovedfromwords. Theorderofexpansionsis:braceexpansion,tildeexpansion,parameter,variable,andarithmeticexpansionandcommandsubstitution(doneinaleftto rightfashion),wordsplitting,andfilenameexpansion. Onsystemsthatcansupportit,thereisanadditionalexpansionavailable:processsubstitution.Thisisperformedatthesametimeasparameter, variable,andarithmeticexpansionandcommandsubstitution. Onlybraceexpansion,wordsplitting,andfilenameexpansioncanchangethenumberofwordsoftheexpansionotherexpansionsexpandasingle wordtoasingleword.Theonlyexceptionstothisaretheexpansionsof" $ @ " (seeSpecialParameters)and" $ { n a m e [ @ ] } " (seeArrays). Afterallexpansions,q u o t er e m o v a l (seeQuoteRemoval)isperformed. Next:TildeExpansion,Up:ShellExpansions[Contents][Index] 3.5.1BraceExpansion Braceexpansionisamechanismbywhicharbitrarystringsmaybegenerated.Thismechanismissimilartofilenameexpansion(seeFilename Expansion),butthefilenamesgeneratedneednotexist.Patternstobebraceexpandedtaketheformofanoptionalpreamble,followedbyeithera seriesofcommaseparatedstringsoraseqeunceexpressionbetweenapairofbraces,followedbyanoptionalpostscript.Thepreambleisprefixedto eachstringcontainedwithinthebraces,andthepostscriptisthenappendedtoeachresultingstring,expandinglefttoright. Braceexpansionsmaybenested.Theresultsofeachexpandedstringarenotsortedlefttorightorderispreserved.Forexample,
b a s h $e c h oa { d , c , b } e a d ea c ea b e
Asequenceexpressiontakestheform{ x . . y [ . . i n c r ] } ,wherexandyareeitherintegersorsinglecharacters,andincr,anoptionalincrement,isan integer.Whenintegersaresupplied,theexpressionexpandstoeachnumberbetweenxandy,inclusive.Suppliedintegersmaybeprefixedwith0 to forceeachtermtohavethesamewidth.Wheneitherxorybeginswithazero,theshellattemptstoforceallgeneratedtermstocontainthesame numberofdigits,zeropaddingwherenecessary.Whencharactersaresupplied,theexpressionexpandstoeachcharacterlexicographicallybetweenx andy,inclusive.Notethatbothxandymustbeofthesametype.Whentheincrementissupplied,itisusedasthedifferencebetweeneachterm.The defaultincrementis1or1asappropriate. Braceexpansionisperformedbeforeanyotherexpansions,andanycharactersspecialtootherexpansionsarepreservedintheresult.Itisstrictly textual.Bashdoesnotapplyanysyntacticinterpretationtothecontextoftheexpansionorthetextbetweenthebraces.Toavoidconflictswith parameterexpansion,thestring$ { isnotconsideredeligibleforbraceexpansion.
or
c h o w nr o o t/ u s r / { u c b / { e x , e d i t } , l i b / { e x ? . ? * , h o w _ e x } }
Next:ShellParameterExpansion,Previous:BraceExpansion,Up:ShellExpansions[Contents][Index] 3.5.2TildeExpansion Ifawordbeginswithanunquotedtildecharacter(~ ),allofthecharactersuptothefirstunquotedslash(orallcharacters,ifthereisnounquotedslash) areconsideredatildeprefix.Ifnoneofthecharactersinthetildeprefixarequoted,thecharactersinthetildeprefixfollowingthetildearetreatedasa possibleloginname.Ifthisloginnameisthenullstring,thetildeisreplacedwiththevalueoftheH O M E shellvariable.IfH O M E isunset,thehome directoryoftheuserexecutingtheshellissubstitutedinstead.Otherwise,thetildeprefixisreplacedwiththehomedirectoryassociatedwiththe specifiedloginname. Ifthetildeprefixis~ + ,thevalueoftheshellvariableP W D replacesthetildeprefix.Ifthetildeprefixis~ ,thevalueoftheshellvariableO L D P W D ,ifit isset,issubstituted. IfthecharactersfollowingthetildeinthetildeprefixconsistofanumberN,optionallyprefixedbya+ ora,thetildeprefixisreplacedwiththe correspondingelementfromthedirectorystack,asitwouldbedisplayedbythed i r s builtininvokedwiththecharactersfollowingtildeinthetilde prefixasanargument(seeTheDirectoryStack).Ifthetildeprefix,sansthetilde,consistsofanumberwithoutaleading+ or,+ isassumed. Iftheloginnameisinvalid,orthetildeexpansionfails,thewordisleftunchanged. Eachvariableassignmentischeckedforunquotedtildeprefixesimmediatelyfollowinga: orthefirst= .Inthesecases,tildeexpansionisalso performed.Consequently,onemayusefilenameswithtildesinassignmentstoP A T H ,M A I L P A T H ,andC D P A T H ,andtheshellassignstheexpandedvalue. ThefollowingtableshowshowBashtreatsunquotedtildeprefixes:
~
Thevalueof$ H O M E
~ / f o o $ H O M E / f o o ~ f r e d / f o o
Thesubdirectoryf o o ofthehomedirectoryoftheuserf r e d
~ + / f o o $ P W D / f o o ~ / f o o $ { O L D P W D ' ~ ' } / f o o ~ N
Thestringthatwouldbedisplayedbyd i r s+ N
~ + N
Thestringthatwouldbedisplayedbyd i r s+ N
~ N
Whenbracesareused,thematchingendingbraceisthefirst} notescapedbyabackslashorwithinaquotedstring,andnotwithinanembedded arithmeticexpansion,commandsubstitution,orparameterexpansion. Thebasicformofparameterexpansionis${parameter}.Thevalueofparameterissubstituted.Thebracesarerequiredwhenparameterisapositional parameterwithmorethanonedigit,orwhenparameterisfollowedbyacharacterthatisnottobeinterpretedaspartofitsname. Ifthefirstcharacterofparameterisanexclamationpoint(!),alevelofvariableindirectionisintroduced.Bashusesthevalueofthevariableformed fromtherestofparameterasthenameofthevariablethisvariableisthenexpandedandthatvalueisusedintherestofthesubstitution,ratherthanthe valueofparameteritself.Thisisknownasi n d i r e c te x p a n s i o n .Theexceptionstothisaretheexpansionsof${!prefix }and${!name[@]}describedbelow.Theexclamationpointmustimmediatelyfollowtheleftbraceinordertointroduceindirection. Ineachofthecasesbelow,wordissubjecttotildeexpansion,parameterexpansion,commandsubstitution,andarithmeticexpansion. Whennotperformingsubstringexpansion,usingtheformdescribedbelow,Bashtestsforaparameterthatisunsetornull.Omittingthecolonresultsin atestonlyforaparameterthatisunset.Putanotherway,ifthecolonisincluded,theoperatortestsforbothparametersexistenceandthatitsvalueis notnullifthecolonisomitted,theoperatortestsonlyforexistence.
$ { p a r a m e t e r : w o r d }
Ifparameterisunsetornull,theexpansionofwordissubstituted.Otherwise,thevalueofparameterissubstituted.
$ { p a r a m e t e r : = w o r d }
Ifparameterisunsetornull,theexpansionofwordisassignedtoparameter.Thevalueofparameteristhensubstituted.Positionalparameters andspecialparametersmaynotbeassignedtointhisway.
$ { p a r a m e t e r : ? w o r d }
Ifparameterisnullorunset,theexpansionofword(oramessagetothateffectifwordisnotpresent)iswrittentothestandarderrorandthe shell,ifitisnotinteractive,exits.Otherwise,thevalueofparameterissubstituted.
$ { p a r a m e t e r : + w o r d }
Ifparameterisnullorunset,nothingissubstituted,otherwisetheexpansionofwordissubstituted.
$ { p a r a m e t e r : o f f s e t } $ { p a r a m e t e r : o f f s e t : l e n g t h }
Expandstouptolengthcharactersofparameterstartingatthecharacterspecifiedbyoffset.Iflengthisomitted,expandstothesubstringof parameterstartingatthecharacterspecifiedbyoffset.lengthandoffsetarearithmeticexpressions(seeShellArithmetic).Thisisreferredtoas SubstringExpansion. Ifoffsetevaluatestoanumberlessthanzero,thevalueisusedasanoffsetfromtheendofthevalueofparameter.Iflengthevaluatestoanumber lessthanzero,andparameterisnot@ andnotanindexedorassociativearray,itisinterpretedasanoffsetfromtheendofthevalueof parameterratherthananumberofcharacters,andtheexpansionisthecharactersbetweenthetwooffsets.Ifparameteris@ ,theresultislength positionalparametersbeginningatoffset.Ifparameterisanindexedarraynamesubscriptedby@ or* ,theresultisthelengthmembersofthe arraybeginningwith$ { p a r a m e t e r [ o f f s e t ] } .Anegativeoffsetistakenrelativetoonegreaterthanthemaximumindexofthespecifiedarray. Substringexpansionappliedtoanassociativearrayproducesundefinedresults. Notethatanegativeoffsetmustbeseparatedfromthecolonbyatleastonespacetoavoidbeingconfusedwiththe: expansion.Substring indexingiszerobasedunlessthepositionalparametersareused,inwhichcasetheindexingstartsat1bydefault.Ifoffsetis0,andthepositional parametersareused,$ @ isprefixedtothelist.
$ { ! p r e f i x * } $ { ! p r e f i x @ }
Thewordisexpandedtoproduceapatternjustasinfilenameexpansion(seeFilenameExpansion).Ifthepatternmatchesthebeginningofthe expandedvalueofparameter,thentheresultoftheexpansionistheexpandedvalueofparameterwiththeshortestmatchingpattern(the# case)orthelongestmatchingpattern(the# # case)deleted.Ifparameteris@ or* ,thepatternremovaloperationisappliedtoeachpositional parameterinturn,andtheexpansionistheresultantlist.Ifparameterisanarrayvariablesubscriptedwith@ or* ,thepatternremoval operationisappliedtoeachmemberofthearrayinturn,andtheexpansionistheresultantlist.
$ { p a r a m e t e r % w o r d }
$ { p a r a m e t e r % % w o r d }
Thewordisexpandedtoproduceapatternjustasinfilenameexpansion.Ifthepatternmatchesatrailingportionoftheexpandedvalueof parameter,thentheresultoftheexpansionisthevalueofparameterwiththeshortestmatchingpattern(the% case)orthelongestmatching pattern(the% % case)deleted.Ifparameteris@ or* ,thepatternremovaloperationisappliedtoeachpositionalparameterinturn,andthe expansionistheresultantlist.Ifparameterisanarrayvariablesubscriptedwith@ or* ,thepatternremovaloperationisappliedtoeach memberofthearrayinturn,andtheexpansionistheresultantlist.
$ { p a r a m e t e r / p a t t e r n / s t r i n g }
Thepatternisexpandedtoproduceapatternjustasinfilenameexpansion.Parameterisexpandedandthelongestmatchofpatternagainstits valueisreplacedwithstring.Ifpatternbeginswith/ ,allmatchesofpatternarereplacedwithstring.Normallyonlythefirstmatchisreplaced. Ifpatternbeginswith# ,itmustmatchatthebeginningoftheexpandedvalueofparameter.Ifpatternbeginswith% ,itmustmatchattheend oftheexpandedvalueofparameter.Ifstringisnull,matchesofpatternaredeletedandthe/ followingpatternmaybeomitted.Ifparameteris @ or* ,thesubstitutionoperationisappliedtoeachpositionalparameterinturn,andtheexpansionistheresultantlist.Ifparameterisanarray variablesubscriptedwith@ or* ,thesubstitutionoperationisappliedtoeachmemberofthearrayinturn,andtheexpansionistheresultantlist.
$ { p a r a m e t e r ^ p a t t e r n } $ { p a r a m e t e r ^ ^ p a t t e r n } $ { p a r a m e t e r , p a t t e r n } $ { p a r a m e t e r , , p a t t e r n }
Thisexpansionmodifiesthecaseofalphabeticcharactersinparameter.Thepatternisexpandedtoproduceapatternjustasinfilename expansion.The^ operatorconvertslowercaselettersmatchingpatterntouppercasethe, operatorconvertsmatchinguppercaselettersto lowercase.The^ ^ and, , expansionsconverteachmatchedcharacterintheexpandedvaluethe^ and, expansionsmatchandconvert onlythefirstcharacterintheexpandedvalue.Ifpatternisomitted,itistreatedlikea? ,whichmatcheseverycharacter.Ifparameteris@ or * ,thecasemodificationoperationisappliedtoeachpositionalparameterinturn,andtheexpansionistheresultantlist.Ifparameterisanarray variablesubscriptedwith@ or* ,thecasemodificationoperationisappliedtoeachmemberofthearrayinturn,andtheexpansionisthe resultantlist. Next:ArithmeticExpansion,Previous:ShellParameterExpansion,Up:ShellExpansions[Contents][Index] 3.5.4CommandSubstitution Commandsubstitutionallowstheoutputofacommandtoreplacethecommanditself.Commandsubstitutionoccurswhenacommandisenclosedas follows:
$ ( c o m m a n d )
or
` c o m m a n d `
Bashperformstheexpansionbyexecutingcommandandreplacingthecommandsubstitutionwiththestandardoutputofthecommand,withany trailingnewlinesdeleted.Embeddednewlinesarenotdeleted,buttheymayberemovedduringwordsplitting.Thecommandsubstitution$ ( c a t f i l e ) canbereplacedbytheequivalentbutfaster$ ( <f i l e ) . Whentheoldstylebackquoteformofsubstitutionisused,backslashretainsitsliteralmeaningexceptwhenfollowedby$ ,` ,or\ .Thefirst backquotenotprecededbyabackslashterminatesthecommandsubstitution.Whenusingthe$ ( c o m m a n d ) form,allcharactersbetweentheparentheses makeupthecommandnonearetreatedspecially. Commandsubstitutionsmaybenested.Tonestwhenusingthebackquotedform,escapetheinnerbackquoteswithbackslashes. Ifthesubstitutionappearswithindoublequotes,wordsplittingandfilenameexpansionarenotperformedontheresults. Next:ProcessSubstitution,Previous:CommandSubstitution,Up:ShellExpansions[Contents][Index] 3.5.5ArithmeticExpansion Arithmeticexpansionallowstheevaluationofanarithmeticexpressionandthesubstitutionoftheresult.Theformatforarithmeticexpansionis:
$ ( (e x p r e s s i o n) )
< ( l i s t )
or
> ( l i s t )
TheprocesslistisrunwithitsinputoroutputconnectedtoaFIFOorsomefilein/ d e v / f d .Thenameofthisfileispassedasanargumenttothecurrent commandastheresultoftheexpansion.Ifthe> ( l i s t ) formisused,writingtothefilewillprovideinputforlist.Ifthe< ( l i s t ) formisused,thefile passedasanargumentshouldbereadtoobtaintheoutputoflist.Notethatnospacemayappearbetweenthe< or> andtheleftparenthesis,otherwise theconstructwouldbeinterpretedasaredirection. Whenavailable,processsubstitutionisperformedsimultaneouslywithparameterandvariableexpansion,commandsubstitution,andarithmetic expansion. Next:FilenameExpansion,Previous:ProcessSubstitution,Up:ShellExpansions[Contents][Index] 3.5.7WordSplitting Theshellscanstheresultsofparameterexpansion,commandsubstitution,andarithmeticexpansionthatdidnotoccurwithindoublequotesforword splitting. Theshelltreatseachcharacterof$ I F S asadelimiter,andsplitstheresultsoftheotherexpansionsintowordsonthesecharacters.IfI F S isunset,orits valueisexactly< s p a c e > < t a b > < n e w l i n e > ,thedefault,thensequencesof< s p a c e > ,< t a b > ,and< n e w l i n e > atthebeginningandendoftheresultsof thepreviousexpansionsareignored,andanysequenceofI F S charactersnotatthebeginningorendservestodelimitwords.IfI F S hasavalueother thanthedefault,thensequencesofthewhitespacecharacterss p a c e andt a b areignoredatthebeginningandendoftheword,aslongasthe whitespacecharacterisinthevalueofI F S (anI F S whitespacecharacter).AnycharacterinI F S thatisnotI F S whitespace,alongwithanyadjacentI F S whitespacecharacters,delimitsafield.AsequenceofI F S whitespacecharactersisalsotreatedasadelimiter.IfthevalueofI F S isnull,noword splittingoccurs. Explicitnullarguments(" " or' ' )areretained.Unquotedimplicitnullarguments,resultingfromtheexpansionofparametersthathavenovalues,are removed.Ifaparameterwithnovalueisexpandedwithindoublequotes,anullargumentresultsandisretained. Notethatifnoexpansionoccurs,nosplittingisperformed. Next:QuoteRemoval,Previous:WordSplitting,Up:ShellExpansions[Contents][Index] 3.5.8FilenameExpansion PatternMatching: Howtheshellmatchespatterns. Afterwordsplitting,unlessthef optionhasbeenset(seeTheSetBuiltin),Bashscanseachwordforthecharacters* ,? ,and[ .Ifoneofthese charactersappears,thenthewordisregardedasapattern,andreplacedwithanalphabeticallysortedlistoffilenamesmatchingthepattern.Ifno matchingfilenamesarefound,andtheshelloptionn u l l g l o b isdisabled,thewordisleftunchanged.Ifthen u l l g l o b optionisset,andnomatchesare found,thewordisremoved.Ifthef a i l g l o b shelloptionisset,andnomatchesarefound,anerrormessageisprintedandthecommandisnot executed.Iftheshelloptionn o c a s e g l o b isenabled,thematchisperformedwithoutregardtothecaseofalphabeticcharacters. Whenapatternisusedforfilenameexpansion,thecharacter. atthestartofafilenameorimmediatelyfollowingaslashmustbematchedexplicitly, unlesstheshelloptiond o t g l o b isset.Whenmatchingafilename,theslashcharactermustalwaysbematchedexplicitly.Inothercases,the. characterisnottreatedspecially. Seethedescriptionofs h o p t inTheShoptBuiltin,foradescriptionofthen o c a s e g l o b ,n u l l g l o b ,f a i l g l o b ,andd o t g l o b options. TheG L O B I G N O R E shellvariablemaybeusedtorestrictthesetoffilenamesmatchingapattern.IfG L O B I G N O R E isset,eachmatchingfilenamethatalso matchesoneofthepatternsinG L O B I G N O R E isremovedfromthelistofmatches.Thefilenames. and. . arealwaysignoredwhenG L O B I G N O R E isset andnotnull.However,settingG L O B I G N O R E toanonnullvaluehastheeffectofenablingthed o t g l o b shelloption,soallotherfilenamesbeginning witha. willmatch.Togettheoldbehaviorofignoringfilenamesbeginningwitha. ,make. * oneofthepatternsinG L O B I G N O R E .Thed o t g l o b optionisdisabledwhenG L O B I G N O R E isunset. Up:FilenameExpansion[Contents][Index] 3.5.8.1PatternMatching Anycharacterthatappearsinapattern,otherthanthespecialpatterncharactersdescribedbelow,matchesitself.TheNULcharactermaynotoccurina pattern.Abackslashescapesthefollowingcharactertheescapingbackslashisdiscardedwhenmatching.Thespecialpatterncharactersmustbequoted iftheyaretobematchedliterally. Thespecialpatterncharactershavethefollowingmeanings:
*
willmatchonlydirectoriesandsubdirectories.
?
Matchesanysinglecharacter.
[ ]
Matchesanyoneoftheenclosedcharacters.Apairofcharactersseparatedbyahyphendenotesarangeexpressionanycharacterthatsorts betweenthosetwocharacters,inclusive,usingthecurrentlocalescollatingsequenceandcharacterset,ismatched.Ifthefirstcharacterfollowing the[ isa! ora^ thenanycharacternotenclosedismatched.Amaybematchedbyincludingitasthefirstorlastcharacterintheset.A ] maybematchedbyincludingitasthefirstcharacterintheset.Thesortingorderofcharactersinrangeexpressionsisdeterminedbythe currentlocaleandthevalueoftheL C _ C O L L A T E shellvariable,ifset. Forexample,inthedefaultClocale,[ a d x z ] isequivalentto[ a b c d x y z ] .Manylocalessortcharactersindictionaryorder,andinthese locales[ a d x z ] istypicallynotequivalentto[ a b c d x y z ] itmightbeequivalentto[ a B b C c D d x X y Y z ] ,forexample.Toobtainthe traditionalinterpretationofrangesinbracketexpressions,youcanforcetheuseoftheClocalebysettingtheL C _ C O L L A T E orL C _ A L L environmentvariabletothevalueC . Within[ and] ,characterclassescanbespecifiedusingthesyntax[ : class: ] ,whereclassisoneofthefollowingclassesdefinedinthe POSIXstandard:
a l n u m p r i n t a l p h a p u n c t a s c i i s p a c e b l a n k u p p e r c n t r l w o r d d i g i t g r a p h x d i g i t l o w e r
Acharacterclassmatchesanycharacterbelongingtothatclass.Thew o r d characterclassmatchesletters,digits,andthecharacter_ . Within[ and] ,anequivalenceclasscanbespecifiedusingthesyntax[ = c= ] ,whichmatchesallcharacterswiththesamecollationweight(as definedbythecurrentlocale)asthecharacterc. Within[ and] ,thesyntax[ . symbol. ] matchesthecollatingsymbolsymbol. Ifthee x t g l o b shelloptionisenabledusingthes h o p t builtin,severalextendedpatternmatchingoperatorsarerecognized.Inthefollowingdescription, apatternlistisalistofoneormorepatternsseparatedbya| .Compositepatternsmaybeformedusingoneormoreofthefollowingsubpatterns:
? ( p a t t e r n l i s t )
Matcheszerooroneoccurrenceofthegivenpatterns.
* ( p a t t e r n l i s t )
Matcheszeroormoreoccurrencesofthegivenpatterns.
+ ( p a t t e r n l i s t )
Matchesoneormoreoccurrencesofthegivenpatterns.
@ ( p a t t e r n l i s t )
Matchesoneofthegivenpatterns.
! ( p a t t e r n l i s t )
3.6Redirections
Beforeacommandisexecuted,itsinputandoutputmayberedirectedusingaspecialnotationinterpretedbytheshell.Redirectionmayalsobeusedto openandclosefilesforthecurrentshellexecutionenvironment.Thefollowingredirectionoperatorsmayprecedeorappearanywherewithinasimple commandormayfollowacommand.Redirectionsareprocessedintheordertheyappear,fromlefttoright. Eachredirectionthatmaybeprecededbyafiledescriptornumbermayinsteadbeprecededbyawordoftheform{varname}.Inthiscase,foreach redirectionoperatorexcept>&and<&,theshellwillallocateafiledescriptorgreaterthan10andassignitto{varname}.If>&or<&ispreceded by{varname},thevalueofvarnamedefinesthefiledescriptortoclose. Inthefollowingdescriptions,ifthefiledescriptornumberisomitted,andthefirstcharacteroftheredirectionoperatoris< ,theredirectionreferstothe standardinput(filedescriptor0).Ifthefirstcharacteroftheredirectionoperatoris> ,theredirectionreferstothestandardoutput(filedescriptor1).
directsbothstandardoutput(filedescriptor1)andstandarderror(filedescriptor2)tothefiledirlist,whilethecommand
l s2 > & 1>d i r l i s t
Iffdisavalidinteger,filedescriptorfdisduplicated.
/ d e v / s t d i n
Filedescriptor0isduplicated.
/ d e v / s t d o u t
Filedescriptor1isduplicated.
/ d e v / s t d e r r
Filedescriptor2isduplicated.
/ d e v / t c p / h o s t / p o r t
IfhostisavalidhostnameorInternetaddress,andportisanintegerportnumberorservicename,BashattemptstoopenaTCPconnectiontothe correspondingsocket.
/ d e v / u d p / h o s t / p o r t
IfhostisavalidhostnameorInternetaddress,andportisanintegerportnumberorservicename,BashattemptstoopenaUDPconnectionto thecorrespondingsocket. Afailuretoopenorcreateafilecausestheredirectiontofail. Redirectionsusingfiledescriptorsgreaterthan9shouldbeusedwithcare,astheymayconflictwithfiledescriptorstheshellusesinternally. 3.6.1RedirectingInput Redirectionofinputcausesthefilewhosenameresultsfromtheexpansionofwordtobeopenedforreadingonfiledescriptorn ,orthestandardinput (filedescriptor0)ifn isnotspecified. Thegeneralformatforredirectinginputis:
[ n ] < w o r d
Iftheredirectionoperatoris> ,andthen o c l o b b e r optiontothes e t builtinhasbeenenabled,theredirectionwillfailifthefilewhosenameresults fromtheexpansionofwordexistsandisaregularfile.Iftheredirectionoperatoris> | ,ortheredirectionoperatoris> andthen o c l o b b e r optionis notenabled,theredirectionisattemptedevenifthefilenamedbywordexists. 3.6.3AppendingRedirectedOutput Redirectionofoutputinthisfashioncausesthefilewhosenameresultsfromtheexpansionofwordtobeopenedforappendingonfiledescriptorn,or thestandardoutput(filedescriptor1)ifnisnotspecified.Ifthefiledoesnotexistitiscreated. Thegeneralformatforappendingoutputis:
[ n ] > > w o r d
3.6.4RedirectingStandardOutputandStandardError
and
> & w o r d
Ofthetwoforms,thefirstispreferred.Thisissemanticallyequivalentto
> w o r d2 > & 1
Thisissemanticallyequivalentto
> > w o r d2 > & 1
Noparameterexpansion,commandsubstitution,arithmeticexpansion,orfilenameexpansionisperformedonword.Ifanycharactersinwordare quoted,thedelimiteristheresultofquoteremovalonword,andthelinesintheheredocumentarenotexpanded.Ifwordisunquoted,alllinesofthe heredocumentaresubjectedtoparameterexpansion,commandsubstitution,andarithmeticexpansion.Inthelattercase,thecharactersequence \ n e w l i n e isignored,and\ mustbeusedtoquotethecharacters\ ,$ ,and` . Iftheredirectionoperatoris< < ,thenallleadingtabcharactersarestrippedfrominputlinesandthelinecontainingdelimiter.Thisallowshere documentswithinshellscriptstobeindentedinanaturalfashion. 3.6.7HereStrings Avariantofheredocuments,theformatis:
< < <w o r d
movesthefiledescriptordigittofiledescriptorn,orthestandardinput(filedescriptor0)ifnisnotspecified.digitisclosedafterbeingduplicatedton. Similarly,theredirectionoperator
[ n ] > & d i g i t -
3.7ExecutingCommands
SimpleCommandExpansion: HowBashexpandssimplecommandsbeforeexecutingthem. CommandSearchandExecution: HowBashfindscommandsandrunsthem. CommandExecutionEnvironment: TheenvironmentinwhichBashexecutescommandsthatarenotshellbuiltins. Environment: Theenvironmentgiventoacommand. ExitStatus: ThestatusreturnedbycommandsandhowBashinterpretsit. Signals: WhathappenswhenBashoracommanditrunsreceivesasignal. Next:CommandSearchandExecution,Up:ExecutingCommands[Contents][Index] 3.7.1SimpleCommandExpansion Whenasimplecommandisexecuted,theshellperformsthefollowingexpansions,assignments,andredirections,fromlefttoright. 1. Thewordsthattheparserhasmarkedasvariableassignments(thoseprecedingthecommandname)andredirectionsaresavedforlater processing. 2. Thewordsthatarenotvariableassignmentsorredirectionsareexpanded(seeShellExpansions).Ifanywordsremainafterexpansion,thefirst wordistakentobethenameofthecommandandtheremainingwordsarethearguments. 3. Redirectionsareperformedasdescribedabove(seeRedirections). 4. Thetextafterthe= ineachvariableassignmentundergoestildeexpansion,parameterexpansion,commandsubstitution,arithmeticexpansion, andquoteremovalbeforebeingassignedtothevariable. Ifnocommandnameresults,thevariableassignmentsaffectthecurrentshellenvironment.Otherwise,thevariablesareaddedtotheenvironmentofthe executedcommandanddonotaffectthecurrentshellenvironment.Ifanyoftheassignmentsattemptstoassignavaluetoareadonlyvariable,anerror occurs,andthecommandexitswithanonzerostatus. Ifnocommandnameresults,redirectionsareperformed,butdonotaffectthecurrentshellenvironment.Aredirectionerrorcausesthecommandtoexit withanonzerostatus. Ifthereisacommandnameleftafterexpansion,executionproceedsasdescribedbelow.Otherwise,thecommandexits.Ifoneoftheexpansions containedacommandsubstitution,theexitstatusofthecommandistheexitstatusofthelastcommandsubstitutionperformed.Iftherewereno commandsubstitutions,thecommandexitswithastatusofzero. Next:CommandExecutionEnvironment,Previous:SimpleCommandExpansion,Up:ExecutingCommands[Contents][Index] 3.7.2CommandSearchandExecution Afteracommandhasbeensplitintowords,ifitresultsinasimplecommandandanoptionallistofarguments,thefollowingactionsaretaken. 1. Ifthecommandnamecontainsnoslashes,theshellattemptstolocateit.Ifthereexistsashellfunctionbythatname,thatfunctionisinvokedas describedinShellFunctions. 2. Ifthenamedoesnotmatchafunction,theshellsearchesforitinthelistofshellbuiltins.Ifamatchisfound,thatbuiltinisinvoked. 3. Ifthenameisneitherashellfunctionnorabuiltin,andcontainsnoslashes,Bashsearcheseachelementof$ P A T H foradirectorycontainingan executablefilebythatname.BashusesahashtabletorememberthefullpathnamesofexecutablefilestoavoidmultipleP A T H searches(seethe descriptionofh a s h inBourneShellBuiltins).Afullsearchofthedirectoriesin$ P A T H isperformedonlyifthecommandisnotfoundinthehash table.Ifthesearchisunsuccessful,theshellsearchesforadefinedshellfunctionnamedc o m m a n d _ n o t _ f o u n d _ h a n d l e .Ifthatfunctionexists,itis invokedwiththeoriginalcommandandtheoriginalcommandsargumentsasitsarguments,andthefunctionsexitstatusbecomestheexitstatus oftheshell.Ifthatfunctionisnotdefined,theshellprintsanerrormessageandreturnsanexitstatusof127. 4. Ifthesearchissuccessful,orifthecommandnamecontainsoneormoreslashes,theshellexecutesthenamedprograminaseparateexecution environment.Argument0issettothenamegiven,andtheremainingargumentstothecommandaresettotheargumentssupplied,ifany. 5. Ifthisexecutionfailsbecausethefileisnotinexecutableformat,andthefileisnotadirectory,itisassumedtobeashellscriptandtheshell
executesitasdescribedinShellScripts. 6. Ifthecommandwasnotbegunasynchronously,theshellwaitsforthecommandtocompleteandcollectsitsexitstatus. Next:Environment,Previous:CommandSearchandExecution,Up:ExecutingCommands[Contents][Index] 3.7.3CommandExecutionEnvironment Theshellhasanexecutionenvironment,whichconsistsofthefollowing: openfilesinheritedbytheshellatinvocation,asmodifiedbyredirectionssuppliedtothee x e c builtin thecurrentworkingdirectoryassetbyc d ,p u s h d ,orp o p d ,orinheritedbytheshellatinvocation thefilecreationmodemaskassetbyu m a s k orinheritedfromtheshellsparent currenttrapssetbyt r a p shellparametersthataresetbyvariableassignmentorwiths e t orinheritedfromtheshellsparentintheenvironment shellfunctionsdefinedduringexecutionorinheritedfromtheshellsparentintheenvironment optionsenabledatinvocation(eitherbydefaultorwithcommandlinearguments)orbys e t optionsenabledbys h o p t (seeTheShoptBuiltin) shellaliasesdefinedwitha l i a s (seeAliases) variousprocessIDs,includingthoseofbackgroundjobs(seeLists),thevalueof$ $ ,andthevalueof$ P P I D Whenasimplecommandotherthanabuiltinorshellfunctionistobeexecuted,itisinvokedinaseparateexecutionenvironmentthatconsistsofthe following.Unlessotherwisenoted,thevaluesareinheritedfromtheshell. theshellsopenfiles,plusanymodificationsandadditionsspecifiedbyredirectionstothecommand thecurrentworkingdirectory thefilecreationmodemask shellvariablesandfunctionsmarkedforexport,alongwithvariablesexportedforthecommand,passedintheenvironment(seeEnvironment) trapscaughtbytheshellareresettothevaluesinheritedfromtheshellsparent,andtrapsignoredbytheshellareignored Acommandinvokedinthisseparateenvironmentcannotaffecttheshellsexecutionenvironment. Commandsubstitution,commandsgroupedwithparentheses,andasynchronouscommandsareinvokedinasubshellenvironmentthatisaduplicateof theshellenvironment,exceptthattrapscaughtbytheshellareresettothevaluesthattheshellinheritedfromitsparentatinvocation.Builtincommands thatareinvokedaspartofapipelinearealsoexecutedinasubshellenvironment.Changesmadetothesubshellenvironmentcannotaffecttheshells executionenvironment. Subshellsspawnedtoexecutecommandsubstitutionsinheritthevalueofthee optionfromtheparentshell.WhennotinPOSIXmode,Bashclearsthe e optioninsuchsubshells. Ifacommandisfollowedbya& andjobcontrolisnotactive,thedefaultstandardinputforthecommandistheemptyfile/ d e v / n u l l .Otherwise,the invokedcommandinheritsthefiledescriptorsofthecallingshellasmodifiedbyredirections. Next:ExitStatus,Previous:CommandExecutionEnvironment,Up:ExecutingCommands[Contents][Index] 3.7.4Environment Whenaprogramisinvokeditisgivenanarrayofstringscalledtheenvironment.Thisisalistofnamevaluepairs,oftheformn a m e = v a l u e . Bashprovidesseveralwaystomanipulatetheenvironment.Oninvocation,theshellscansitsownenvironmentandcreatesaparameterforeachname found,automaticallymarkingitforexporttochildprocesses.Executedcommandsinherittheenvironment.Thee x p o r t andd e c l a r ex commands allowparametersandfunctionstobeaddedtoanddeletedfromtheenvironment.Ifthevalueofaparameterintheenvironmentismodified,thenew valuebecomespartoftheenvironment,replacingtheold.Theenvironmentinheritedbyanyexecutedcommandconsistsoftheshellsinitial environment,whosevaluesmaybemodifiedintheshell,lessanypairsremovedbytheu n s e t ande x p o r tn commands,plusanyadditionsviathe e x p o r t andd e c l a r ex commands. Theenvironmentforanysimplecommandorfunctionmaybeaugmentedtemporarilybyprefixingitwithparameterassignments,asdescribedinShell Parameters.Theseassignmentstatementsaffectonlytheenvironmentseenbythatcommand. Ifthek optionisset(seeTheSetBuiltin),thenallparameterassignmentsareplacedintheenvironmentforacommand,notjustthosethatprecedethe commandname. WhenBashinvokesanexternalcommand,thevariable$ _ issettothefullpathnameofthecommandandpassedtothatcommandinitsenvironment. Next:Signals,Previous:Environment,Up:ExecutingCommands[Contents][Index] 3.7.5ExitStatus Theexitstatusofanexecutedcommandisthevaluereturnedbythewaitpidsystemcallorequivalentfunction.Exitstatusesfallbetween0and255, though,asexplainedbelow,theshellmayusevaluesabove125specially.Exitstatusesfromshellbuiltinsandcompoundcommandsarealsolimitedto thisrange.Undercertaincircumstances,theshellwillusespecialvaluestoindicatespecificfailuremodes. Fortheshellspurposes,acommandwhichexitswithazeroexitstatushassucceeded.Anonzeroexitstatusindicatesfailure.Thisseeminglycounter
intuitiveschemeisusedsothereisonewelldefinedwaytoindicatesuccessandavarietyofwaystoindicatevariousfailuremodes.Whenacommand terminatesonafatalsignalwhosenumberisN,Bashusesthevalue128+Nastheexitstatus. Ifacommandisnotfound,thechildprocesscreatedtoexecuteitreturnsastatusof127.Ifacommandisfoundbutisnotexecutable,thereturnstatusis 126. Ifacommandfailsbecauseofanerrorduringexpansionorredirection,theexitstatusisgreaterthanzero. TheexitstatusisusedbytheBashconditionalcommands(seeConditionalConstructs)andsomeofthelistconstructs(seeLists). AlloftheBashbuiltinsreturnanexitstatusofzeroiftheysucceedandanonzerostatusonfailure,sotheymaybeusedbytheconditionalandlist constructs.Allbuiltinsreturnanexitstatusof2toindicateincorrectusage. Previous:ExitStatus,Up:ExecutingCommands[Contents][Index] 3.7.6Signals WhenBashisinteractive,intheabsenceofanytraps,itignoresS I G T E R M (sothatk i l l0 doesnotkillaninteractiveshell),andS I G I N T iscaughtand handled(sothatthew a i t builtinisinterruptible).WhenBashreceivesaS I G I N T ,itbreaksoutofanyexecutingloops.Inallcases,Bashignores S I G Q U I T .Ifjobcontrolisineffect(seeJobControl),BashignoresS I G T T I N ,S I G T T O U ,andS I G T S T P . NonbuiltincommandsstartedbyBashhavesignalhandlerssettothevaluesinheritedbytheshellfromitsparent.Whenjobcontrolisnotineffect, asynchronouscommandsignoreS I G I N T andS I G Q U I T inadditiontotheseinheritedhandlers.Commandsrunasaresultofcommandsubstitutionignore thekeyboardgeneratedjobcontrolsignalsS I G T T I N ,S I G T T O U ,andS I G T S T P . TheshellexitsbydefaultuponreceiptofaS I G H U P .Beforeexiting,aninteractiveshellresendstheS I G H U P toalljobs,runningorstopped.Stoppedjobs aresentS I G C O N T toensurethattheyreceivetheS I G H U P .TopreventtheshellfromsendingtheS I G H U P signaltoaparticularjob,itshouldberemoved fromthejobstablewiththed i s o w n builtin(seeJobControlBuiltins)ormarkedtonotreceiveS I G H U P usingd i s o w nh . Iftheh u p o n e x i t shelloptionhasbeensetwiths h o p t (seeTheShoptBuiltin),BashsendsaS I G H U P toalljobswhenaninteractiveloginshellexits. IfBashiswaitingforacommandtocompleteandreceivesasignalforwhichatraphasbeenset,thetrapwillnotbeexecuteduntilthecommand completes.WhenBashiswaitingforanasynchronouscommandviathew a i t builtin,thereceptionofasignalforwhichatraphasbeensetwillcause thew a i t builtintoreturnimmediatelywithanexitstatusgreaterthan128,immediatelyafterwhichthetrapisexecuted. Previous:ExecutingCommands,Up:BasicShellFeatures[Contents][Index]
3.8ShellScripts
Ashellscriptisatextfilecontainingshellcommands.WhensuchafileisusedasthefirstnonoptionargumentwheninvokingBash,andneitherthec nors optionissupplied(seeInvokingBash),Bashreadsandexecutescommandsfromthefile,thenexits.Thismodeofoperationcreatesanon interactiveshell.Theshellfirstsearchesforthefileinthecurrentdirectory,andlooksinthedirectoriesin$ P A T H ifnotfoundthere. WhenBashrunsashellscript,itsetsthespecialparameter0 tothenameofthefile,ratherthanthenameoftheshell,andthepositionalparametersare settotheremainingarguments,ifanyaregiven.Ifnoadditionalargumentsaresupplied,thepositionalparametersareunset. Ashellscriptmaybemadeexecutablebyusingthec h m o d commandtoturnontheexecutebit.WhenBashfindssuchafilewhilesearchingthe$ P A T H foracommand,itspawnsasubshelltoexecuteit.Inotherwords,executing
f i l e n a m ea r g u m e n t s
isequivalenttoexecuting
b a s hf i l e n a m ea r g u m e n t s
iff i l e n a m e isanexecutableshellscript.Thissubshellreinitializesitself,sothattheeffectisasifanewshellhadbeeninvokedtointerpretthescript, withtheexceptionthatthelocationsofcommandsrememberedbytheparent(seethedescriptionofh a s h inBourneShellBuiltins)areretainedbythe child. MostversionsofUnixmakethisapartoftheoperatingsystemscommandexecutionmechanism.Ifthefirstlineofascriptbeginswiththetwo characters# ! ,theremainderofthelinespecifiesaninterpreterfortheprogram.Thus,youcanspecifyBash,a w k ,Perl,orsomeotherinterpreterand writetherestofthescriptfileinthatlanguage. Theargumentstotheinterpreterconsistofasingleoptionalargumentfollowingtheinterpreternameonthefirstlineofthescriptfile,followedbythe nameofthescriptfile,followedbytherestofthearguments.Bashwillperformthisactiononoperatingsystemsthatdonothandleitthemselves.Note thatsomeolderversionsofUnixlimittheinterpreternameandargumenttoamaximumof32characters. Bashscriptsoftenbeginwith# !/ b i n / b a s h (assumingthatBashhasbeeninstalledin/ b i n ),sincethisensuresthatBashwillbeusedtointerpretthe script,evenifitisexecutedunderanothershell. Next:ShellVariables,Previous:BasicShellFeatures,Up:Top[Contents][Index]
4ShellBuiltinCommands
BourneShellBuiltins: BuiltincommandsinheritedfromtheBourneShell. BashBuiltins: TableofbuiltinsspecifictoBash. ModifyingShellBehavior: Builtinstomodifyshellattributesandoptionalbehavior. SpecialBuiltins: BuiltincommandsclassifiedspeciallybyPOSIX. Builtincommandsarecontainedwithintheshellitself.Whenthenameofabuiltincommandisusedasthefirstwordofasimplecommand(seeSimple Commands),theshellexecutesthecommanddirectly,withoutinvokinganotherprogram.Builtincommandsarenecessarytoimplementfunctionality impossibleorinconvenienttoobtainwithseparateutilities. ThissectionbrieflydescribesthebuiltinswhichBashinheritsfromtheBourneShell,aswellasthebuiltincommandswhichareuniquetoorhavebeen extendedinBash. Severalbuiltincommandsaredescribedinotherchapters:builtincommandswhichprovidetheBashinterfacetothejobcontrolfacilities(seeJob ControlBuiltins),thedirectorystack(seeDirectoryStackBuiltins),thecommandhistory(seeBashHistoryBuiltins),andtheprogrammable completionfacilities(seeProgrammableCompletionBuiltins). ManyofthebuiltinshavebeenextendedbyPOSIXorBash. Unlessotherwisenoted,eachbuiltincommanddocumentedasacceptingoptionsprecededbyacceptstosignifytheendoftheoptions.The: , t r u e ,f a l s e ,andt e s t builtinsdonotacceptoptionsanddonottreatspecially.Thee x i t ,l o g o u t ,b r e a k ,c o n t i n u e ,l e t ,ands h i f t builtins acceptandprocessargumentsbeginningwithwithoutrequiring.Otherbuiltinsthatacceptargumentsbutarenotspecifiedasacceptingoptions interpretargumentsbeginningwithasinvalidoptionsandrequiretopreventthisinterpretation. Next:BashBuiltins,Up:ShellBuiltinCommands[Contents][Index]
4.1BourneShellBuiltins
ThefollowingshellbuiltincommandsareinheritedfromtheBourneShell.ThesecommandsareimplementedasspecifiedbythePOSIXstandard.
: (acolon) :[ a r g u m e n t s ]
Donothingbeyondexpandingargumentsandperformingredirections.Thereturnstatusiszero.
. (aperiod) .f i l e n a m e[ a r g u m e n t s ]
Changethecurrentworkingdirectorytodirectory.Ifdirectoryisnotgiven,thevalueoftheH O M E shellvariableisused.Iftheshellvariable C D P A T H exists,itisusedasasearchpath.Ifdirectorybeginswithaslash,C D P A T H isnotused. TheP optionmeanstonotfollowsymboliclinkssymboliclinksarefollowedbydefaultorwiththeL option.Ifthee optionissuppliedwith P andthecurrentworkingdirectorycannotbesuccessfullydeterminedafterasuccessfuldirectorychange,c d willreturnanunsuccessfulstatus. Ifdirectoryis,itisequivalentto$ O L D P W D . IfanonemptydirectorynamefromC D P A T H isused,orifisthefirstargument,andthedirectorychangeissuccessful,theabsolutepathname ofthenewworkingdirectoryiswrittentothestandardoutput. Thereturnstatusiszeroifthedirectoryissuccessfullychanged,nonzerootherwise.
c o n t i n u e c o n t i n u e[ n ]
Theargumentsareconcatenatedtogetherintoasinglecommand,whichisthenreadandexecuted,anditsexitstatusreturnedastheexitstatusof e v a l .Iftherearenoargumentsoronlyemptyarguments,thereturnstatusiszero.
e x e c e x e c[ c l ][ an a m e ][ c o m m a n d[ a r g u m e n t s ] ]
Exittheshell,returningastatusofntotheshellsparent.Ifnisomitted,theexitstatusisthatofthelastcommandexecuted.AnytraponE X I T is executedbeforetheshellterminates.
e x p o r t e x p o r t[ f n ][ p ][ n a m e [ = v a l u e ] ]
Markeachnametobepassedtochildprocessesintheenvironment.Ifthef optionissupplied,thenamesrefertoshellfunctionsotherwisethe namesrefertoshellvariables.Then optionmeanstonolongermarkeachnameforexport.Ifnonamesaresupplied,orifthep optionis given,alistofexportednamesisdisplayed.Thep optiondisplaysoutputinaformthatmaybereusedasinput.Ifavariablenameisfollowed by=value,thevalueofthevariableissettovalue. Thereturnstatusiszerounlessaninvalidoptionissupplied,oneofthenamesisnotavalidshellvariablename,orf issuppliedwithaname thatisnotashellfunction.
g e t o p t s g e t o p t so p t s t r i n gn a m e[ a r g s ] g e t o p t s isusedbyshellscriptstoparsepositionalparameters.optstringcontainstheoptioncharacterstoberecognizedifacharacterisfollowed byacolon,theoptionisexpectedtohaveanargument,whichshouldbeseparatedfromitbywhitespace.Thecolon(: )andquestionmark (? )maynotbeusedasoptioncharacters.Eachtimeitisinvoked,g e t o p t s placesthenextoptionintheshellvariablename,initializingnameif itdoesnotexist,andtheindexofthenextargumenttobeprocessedintothevariableO P T I N D .O P T I N D isinitializedto1eachtimetheshellora shellscriptisinvoked.Whenanoptionrequiresanargument,g e t o p t s placesthatargumentintothevariableO P T A R G .Theshelldoesnotreset O P T I N D automaticallyitmustbemanuallyresetbetweenmultiplecallstog e t o p t s withinthesameshellinvocationifanewsetofparametersis
Ifaninvalidoptionisseen,g e t o p t s places? intonameand,ifnotsilent,printsanerrormessageandunsetsO P T A R G .Ifg e t o p t s issilent,the optioncharacterfoundisplacedinO P T A R G andnodiagnosticmessageisprinted. Ifarequiredargumentisnotfound,andg e t o p t s isnotsilent,aquestionmark(? )isplacedinname,O P T A R G isunset,andadiagnosticmessage isprinted.Ifg e t o p t s issilent,thenacolon(: )isplacedinnameandO P T A R G issettotheoptioncharacterfound.
h a s h h a s h[ r ][ pf i l e n a m e ][ d t ][ n a m e ]
Eachtimeh a s h isinvoked,itremembersthefullpathnamesofthecommandsspecifiedasnamearguments,sotheyneednotbesearchedforon subsequentinvocations.Thecommandsarefoundbysearchingthroughthedirectorieslistedin$ P A T H .Anypreviouslyrememberedpathnameis discarded.Thep optioninhibitsthepathsearch,andfilenameisusedasthelocationofname.Ther optioncausestheshelltoforgetall rememberedlocations.Thed optioncausestheshelltoforgettherememberedlocationofeachname.Ifthet optionissupplied,thefull pathnametowhicheachnamecorrespondsisprinted.Ifmultiplenameargumentsaresuppliedwitht thenameisprintedbeforethehashedfull pathname.Thel optioncausesoutputtobedisplayedinaformatthatmaybereusedasinput.Ifnoargumentsaregiven,orifonlyl is supplied,informationaboutrememberedcommandsisprinted.Thereturnstatusiszerounlessanameisnotfoundoraninvalidoptionis supplied.
p w d p w d[ L P ]
r e a d o n l y[ a A f ][ p ][ n a m e [ = v a l u e ] ]
Markeachnameasreadonly.Thevaluesofthesenamesmaynotbechangedbysubsequentassignment.Ifthef optionissupplied,eachname referstoashellfunction.Thea optionmeanseachnamereferstoanindexedarrayvariabletheA optionmeanseachnamereferstoan associativearrayvariable.Ifbothoptionsaresupplied,A takesprecedence.Ifnonameargumentsaregiven,orifthep optionissupplied,alist ofallreadonlynamesisprinted.Theotheroptionsmaybeusedtorestricttheoutputtoasubsetofthesetofreadonlynames.Thep option causesoutputtobedisplayedinaformatthatmaybereusedasinput.Ifavariablenameisfollowedby=value,thevalueofthevariableissetto value.Thereturnstatusiszerounlessaninvalidoptionissupplied,oneofthenameargumentsisnotavalidshellvariableorfunctionname,or thef optionissuppliedwithanamethatisnotashellfunction.
r e t u r n r e t u r n[ n ]
Causeashellfunctiontoexitwiththereturnvaluen.Ifnisnotsupplied,thereturnvalueistheexitstatusofthelastcommandexecutedinthe function.Thismayalsobeusedtoterminateexecutionofascriptbeingexecutedwiththe. (ors o u r c e )builtin,returningeithernortheexit statusofthelastcommandexecutedwithinthescriptastheexitstatusofthescript.AnycommandassociatedwiththeR E T U R N trapisexecuted beforeexecutionresumesafterthefunctionorscript.Thereturnstatusisnonzeroifr e t u r n isusedoutsideafunctionandnotduringthe executionofascriptby. ors o u r c e .
s h i f t s h i f t[ n ]
Shiftthepositionalparameterstotheleftbyn.Thepositionalparametersfromn+1$ # arerenamedto$ 1 $ # n.Parametersrepresentedby thenumbers$ # to$ # n+1areunset.nmustbeanonnegativenumberlessthanorequalto$ # .Ifniszeroorgreaterthan$ # ,thepositional parametersarenotchanged.Ifnisnotsupplied,itisassumedtobe1.Thereturnstatusiszerounlessnisgreaterthan$ # orlessthanzero,non zerootherwise.
t e s t [
Trueifexprisfalse.
(e x p r)
Returnsthevalueofexpr.Thismaybeusedtooverridethenormalprecedenceofoperators.
e x p r 1ae x p r 2
Trueifbothexpr1andexpr2aretrue.
e x p r 1oe x p r 2
Trueifeitherexpr1orexpr2istrue. Thet e s t and[ builtinsevaluateconditionalexpressionsusingasetofrulesbasedonthenumberofarguments. 0arguments Theexpressionisfalse. 1argument Theexpressionistrueifandonlyiftheargumentisnotnull. 2arguments Ifthefirstargumentis! ,theexpressionistrueifandonlyifthesecondargumentisnull.Ifthefirstargumentisoneoftheunary conditionaloperators(seeBashConditionalExpressions),theexpressionistrueiftheunarytestistrue.Ifthefirstargumentisnotavalid unaryoperator,theexpressionisfalse. 3arguments Thefollowingconditionsareappliedintheorderlisted.Ifthesecondargumentisoneofthebinaryconditionaloperators(seeBash ConditionalExpressions),theresultoftheexpressionistheresultofthebinarytestusingthefirstandthirdargumentsasoperands.Thea ando operatorsareconsideredbinaryoperatorswhentherearethreearguments.Ifthefirstargumentis! ,thevalueisthenegation ofthetwoargumenttestusingthesecondandthirdarguments.Ifthefirstargumentisexactly( andthethirdargumentisexactly) ,the resultistheoneargumenttestofthesecondargument.Otherwise,theexpressionisfalse.
4arguments Ifthefirstargumentis! ,theresultisthenegationofthethreeargumentexpressioncomposedoftheremainingarguments.Otherwise,the expressionisparsedandevaluatedaccordingtoprecedenceusingtheruleslistedabove. 5ormorearguments Theexpressionisparsedandevaluatedaccordingtoprecedenceusingtheruleslistedabove. Whenusedwitht e s t or[ ,the< and> operatorssortlexicographicallyusingASCIIordering.
t i m e s t i m e s
Printouttheuserandsystemtimesusedbytheshellanditschildren.Thereturnstatusiszero.
t r a p t r a p[ l p ][ a r g ][ s i g s p e c ]
Thecommandsinargaretobereadandexecutedwhentheshellreceivessignalsigspec.Ifargisabsent(andthereisasinglesigspec)orequal to,eachspecifiedsignalsdispositionisresettothevalueithadwhentheshellwasstarted.Ifargisthenullstring,thenthesignalspecifiedby eachsigspecisignoredbytheshellandcommandsitinvokes.Ifargisnotpresentandp hasbeensupplied,theshelldisplaysthetrap commandsassociatedwitheachsigspec.Ifnoargumentsaresupplied,oronlyp isgiven,t r a p printsthelistofcommandsassociatedwitheach signalnumberinaformthatmaybereusedasshellinput.Thel optioncausestheshelltoprintalistofsignalnamesandtheircorresponding numbers.Eachsigspeciseitherasignalnameorasignalnumber.SignalnamesarecaseinsensitiveandtheS I G prefixisoptional. Ifasigspecis0 orE X I T ,argisexecutedwhentheshellexits.IfasigspecisD E B U G ,thecommandargisexecutedbeforeeverysimplecommand, f o r command,c a s e command,s e l e c t command,everyarithmeticf o r command,andbeforethefirstcommandexecutesinashellfunction. Refertothedescriptionofthee x t d e b u g optiontothes h o p t builtin(seeTheShoptBuiltin)fordetailsofitseffectontheD E B U G trap.Ifasigspec isR E T U R N ,thecommandargisexecutedeachtimeashellfunctionorascriptexecutedwiththe. ors o u r c e builtinsfinishesexecuting. IfasigspecisE R R ,thecommandargisexecutedwheneverasimplecommandhasanonzeroexitstatus,subjecttothefollowingconditions.The E R R trapisnotexecutedifthefailedcommandispartofthecommandlistimmediatelyfollowinganu n t i l orw h i l e keyword,partofthetest followingthei f ore l i f reservedwords,partofacommandexecutedina& & or| | list,orifthecommandsreturnstatusisbeinginvertedusing ! .Thesearethesameconditionsobeyedbythee r r e x i t option. Signalsignoreduponentrytotheshellcannotbetrappedorreset.Trappedsignalsthatarenotbeingignoredareresettotheiroriginalvaluesina subshellorsubshellenvironmentwhenoneiscreated. Thereturnstatusiszerounlessasigspecdoesnotspecifyavalidsignal.
u m a s k u m a s k[ p ][ S ][ m o d e ]
Settheshellprocesssfilecreationmasktomode.Ifmodebeginswithadigit,itisinterpretedasanoctalnumberifnot,itisinterpretedasa symbolicmodemasksimilartothatacceptedbythec h m o d command.Ifmodeisomitted,thecurrentvalueofthemaskisprinted.IftheS option issuppliedwithoutamodeargument,themaskisprintedinasymbolicformat.Ifthep optionissupplied,andmodeisomitted,theoutputisina formthatmaybereusedasinput.Thereturnstatusiszeroifthemodeissuccessfullychangedorifnomodeargumentissupplied,andnonzero otherwise. Notethatwhenthemodeisinterpretedasanoctalnumber,eachnumberoftheumaskissubtractedfrom7 .Thus,aumaskof0 2 2 resultsin permissionsof7 5 5 .
u n s e t u n s e t[ f v ][ n a m e ]
4.2BashBuiltinCommands
ThissectiondescribesbuiltincommandswhichareuniquetoorhavebeenextendedinBash.SomeofthesecommandsarespecifiedinthePOSIX standard.
a l i a s a l i a s[ p ][ n a m e [ = v a l u e ] ]
b i n d b i n d[ mk e y m a p ][ l p s v P S V ] b i n d[ mk e y m a p ][ qf u n c t i o n ][ uf u n c t i o n ][ rk e y s e q ] b i n d[ mk e y m a p ]ff i l e n a m e b i n d[ mk e y m a p ]xk e y s e q : s h e l l c o m m a n d b i n d[ mk e y m a p ]k e y s e q : f u n c t i o n n a m e b i n dr e a d l i n e c o m m a n d
ListthenamesofallReadlinefunctions.
p
DisplayReadlinefunctionnamesandbindingsinsuchawaythattheycanbeusedasinputorinaReadlineinitializationfile.
P
ListcurrentReadlinefunctionnamesandbindings.
v
DisplayReadlinevariablenamesandvaluesinsuchawaythattheycanbeusedasinputorinaReadlineinitializationfile.
V
ListcurrentReadlinevariablenamesandvalues.
s
DisplayReadlinekeysequencesboundtomacrosandthestringstheyoutputinsuchawaythattheycanbeusedasinputorinaReadline initializationfile.
S
DisplayReadlinekeysequencesboundtomacrosandthestringstheyoutput.
ff i l e n a m e
Readkeybindingsfromfilename.
qf u n c t i o n
Queryaboutwhichkeysinvokethenamedfunction.
uf u n c t i o n
Unbindallkeysboundtothenamedfunction.
rk e y s e q
Removeanycurrentbindingforkeyseq.
xk e y s e q : s h e l l c o m m a n d
Runashellbuiltin,passingitargs,andreturnitsexitstatus.Thisisusefulwhendefiningashellfunctionwiththesamenameasashellbuiltin, retainingthefunctionalityofthebuiltinwithinthefunction.Thereturnstatusisnonzeroifshellbuiltinisnotashellbuiltincommand.
c a l l e r c a l l e r[ e x p r ]
Runscommandwithargumentsignoringanyshellfunctionnamedcommand.Onlyshellbuiltincommandsorcommandsfoundbysearchingthe P A T H areexecuted.Ifthereisashellfunctionnamedl s ,runningc o m m a n dl s withinthefunctionwillexecutetheexternalcommandl s instead ofcallingthefunctionrecursively.Thep optionmeanstouseadefaultvalueforP A T H thatisguaranteedtofindallofthestandardutilities.The returnstatusinthiscaseis127ifcommandcannotbefoundoranerroroccurred,andtheexitstatusofcommandotherwise. IfeithertheV orv optionissupplied,adescriptionofcommandisprinted.Thev optioncausesasinglewordindicatingthecommandorfile nameusedtoinvokecommandtobedisplayedtheV optionproducesamoreverbosedescription.Inthiscase,thereturnstatusiszeroif commandisfound,andnonzeroifnot.
d e c l a r e d e c l a r e[ a A f F i l r t u x ][ p ][ n a m e [ = v a l u e ] ]
Declarevariablesandgivethemattributes.Ifnonamesaregiven,thendisplaythevaluesofvariablesinstead. Thep optionwilldisplaytheattributesandvaluesofeachname.Whenp isusedwithnamearguments,additionaloptionsareignored. Whenp issuppliedwithoutnamearguments,d e c l a r e willdisplaytheattributesandvaluesofallvariableshavingtheattributesspecifiedbythe additionaloptions.Ifnootheroptionsaresuppliedwithp ,d e c l a r e willdisplaytheattributesandvaluesofallshellvariables.Thef option willrestrictthedisplaytoshellfunctions. TheF optioninhibitsthedisplayoffunctiondefinitionsonlythefunctionnameandattributesareprinted.Ifthee x t d e b u g shelloptionis enabledusings h o p t (seeTheShoptBuiltin),thesourcefilenameandlinenumberwherethefunctionisdefinedaredisplayedaswell.F impliesf . Theg optionforcesvariablestobecreatedormodifiedattheglobalscope,evenwhend e c l a r e isexecutedinashellfunction.Itisignoredin allothercases. Thefollowingoptionscanbeusedtorestrictoutputtovariableswiththespecifiedattributesortogivevariablesattributes:
a
Eachnameisanindexedarrayvariable(seeArrays).
A
Eachnameisanassociativearrayvariable(seeArrays).
f
Usefunctionnamesonly.
i
Thevariableistobetreatedasanintegerarithmeticevaluation(seeShellArithmetic)isperformedwhenthevariableisassignedavalue.
l
Whenthevariableisassignedavalue,alluppercasecharactersareconvertedtolowercase.Theuppercaseattributeisdisabled.
r
Makenamesreadonly.Thesenamescannotthenbeassignedvaluesbysubsequentassignmentstatementsorunset.
t
Whenthevariableisassignedavalue,alllowercasecharactersareconvertedtouppercase.Thelowercaseattributeisdisabled.
x
Outputtheargs,separatedbyspaces,terminatedwithanewline.Thereturnstatusisalways0.Ifn isspecified,thetrailingnewlineis suppressed.Ifthee optionisgiven,interpretationofthefollowingbackslashescapedcharactersisenabled.TheE optiondisablesthe interpretationoftheseescapecharacters,evenonsystemswheretheyareinterpretedbydefault.Thex p g _ e c h o shelloptionmaybeusedto dynamicallydeterminewhetherornote c h o expandstheseescapecharactersbydefault.e c h o doesnotinterprettomeantheendofoptions.
e c h o interpretsthefollowingescapesequences: \ a
alert(bell)
\ b
backspace
\ c
suppressfurtheroutput
\ e \ E
escape
\ f
formfeed
\ n
newline
\ r
carriagereturn
\ t
horizontaltab
\ v
verticaltab
\ \
backslash
\ 0 n n n
theeightbitcharacterwhosevalueistheoctalvaluennn(zerotothreeoctaldigits)
\ x H H
theeightbitcharacterwhosevalueisthehexadecimalvalueHH(oneortwohexdigits)
\ u H H H H
theUnicode(ISO/IEC10646)characterwhosevalueisthehexadecimalvalueHHHH(onetofourhexdigits)
\ U H H H H H H H H
theUnicode(ISO/IEC10646)characterwhosevalueisthehexadecimalvalueHHHHHHHH(onetoeighthexdigits)
e n a b l e e n a b l e[ a ][ d n p s ][ ff i l e n a m e ][ n a m e ]
Ifthep optionissupplied,ornonameargumentsappear,alistofshellbuiltinsisprinted.Withnootherarguments,thelistconsistsofall enabledshellbuiltins.Thea optionmeanstolisteachbuiltinwithanindicationofwhetherornotitisenabled. Thef optionmeanstoloadthenewbuiltincommandnamefromsharedobjectfilename,onsystemsthatsupportdynamicloading.Thed optionwilldeleteabuiltinloadedwithf . Iftherearenooptions,alistoftheshellbuiltinsisdisplayed.Thes optionrestrictse n a b l e tothePOSIXspecialbuiltins.Ifs isusedwithf , thenewbuiltinbecomesaspecialbuiltin(seeSpecialBuiltins). Thereturnstatusiszerounlessanameisnotashellbuiltinorthereisanerrorloadinganewbuiltinfromasharedobject.
h e l p h e l p[ d m s ][ p a t t e r n ]
Displayashortdescriptionofeachpattern
m
Displaythedescriptionofeachpatterninamanpagelikeformat
s
Displayonlyashortusagesynopsisforeachpattern Thereturnstatusiszerounlessnocommandmatchespattern.
l e t l e te x p r e s s i o n[ e x p r e s s i o n ]
Exitaloginshell,returningastatusofntotheshellsparent.
m a p f i l e m a p f i l e[ nc o u n t ][ Oo r i g i n ][ sc o u n t ][ t ][ uf d ][ Cc a l l b a c k ][ cq u a n t u m ][ a r r a y ]
Copyatmostcountlines.Ifcountis0,alllinesarecopied.
O
Beginassigningtoarrayatindexorigin.Thedefaultindexis0.
s
Discardthefirstcountlinesread.
t
Removeatrailingnewlinefromeachlineread.
u
Readlinesfromfiledescriptorfdinsteadofthestandardinput.
C
EvaluatecallbackeachtimequantumPlinesareread.Thec optionspecifiesquantum.
c
array.
p r i n t f p r i n t f[ vv a r ]f o r m a t[ a r g u m e n t s ]
causesp r i n t f tooutputthecorrespondingargumentinaformatthatcanbereusedasshellinput.
% ( d a t e f m t ) T
Onelineisreadfromthestandardinput,orfromthefiledescriptorfdsuppliedasanargumenttotheu option,andthefirstwordisassignedto thefirstname,thesecondwordtothesecondname,andsoon,withleftoverwordsandtheirinterveningseparatorsassignedtothelastname.If therearefewerwordsreadfromtheinputstreamthannames,theremainingnamesareassignedemptyvalues.Thecharactersinthevalueofthe I F S variableareusedtosplitthelineintowords.Thebackslashcharacter\ maybeusedtoremoveanyspecialmeaningforthenextcharacter readandforlinecontinuation.Ifnonamesaresupplied,thelinereadisassignedtothevariableR E P L Y .Thereturncodeiszero,unlessendoffile isencountered,r e a d timesout(inwhichcasethereturncodeisgreaterthan128),oraninvalidfiledescriptorissuppliedastheargumenttou . Options,ifsupplied,havethefollowingmeanings:
aa n a m e
Thewordsareassignedtosequentialindicesofthearrayvariableaname,startingat0.Allelementsareremovedfromanamebeforethe assignment.Othernameargumentsareignored.
dd e l i m
Thefirstcharacterofdelimisusedtoterminatetheinputline,ratherthannewline.
e
Readline(seeCommandLineEditing)isusedtoobtaintheline.Readlineusesthecurrent(ordefault,iflineeditingwasnotpreviously active)editingsettings.
it e x t
IfReadlineisbeingusedtoreadtheline,textisplacedintotheeditingbufferbeforeeditingbegins.
nn c h a r s r e a d returnsafterreadingncharscharactersratherthanwaitingforacompletelineofinput,buthonoradelimiteriffewerthannchars
charactersarereadbeforethedelimiter.
Nn c h a r s r e a d returnsafterreadingexactlyncharscharactersratherthanwaitingforacompletelineofinput,unlessEOFisencounteredorr e a d timesout.Delimitercharactersencounteredintheinputarenottreatedspeciallyanddonotcauser e a d toreturnuntilncharscharactersare
read.
pp r o m p t
Displayprompt,withoutatrailingnewline,beforeattemptingtoreadanyinput.Thepromptisdisplayedonlyifinputiscomingfroma terminal.
r
Ifthisoptionisgiven,backslashdoesnotactasanescapecharacter.Thebackslashisconsideredtobepartoftheline.Inparticular,a backslashnewlinepairmaynotbeusedasalinecontinuation.
s
Silentmode.Ifinputiscomingfromaterminal,charactersarenotechoed.
tt i m e o u t
Readinputfromfiledescriptorfd.
r e a d a r r a y r e a d a r r a y[ nc o u n t ][ Oo r i g i n ][ sc o u n t ][ t ][ uf d ][ Cc a l l b a c k ][ cq u a n t u m ][ a r r a y ]
Asynonymfor. (seeBourneShellBuiltins).
t y p e t y p e[ a f p t P ][ n a m e ]
Foreachname,indicatehowitwouldbeinterpretedifusedasacommandname. Ifthet optionisused,t y p e printsasinglewordwhichisoneofa l i a s ,f u n c t i o n ,b u i l t i n ,f i l e ork e y w o r d ,ifnameisanalias, shellfunction,shellbuiltin,diskfile,orshellreservedword,respectively.Ifthenameisnotfound,thennothingisprinted,andt y p e returnsa failurestatus. Ifthep optionisused,t y p e eitherreturnsthenameofthediskfilethatwouldbeexecuted,ornothingift wouldnotreturnf i l e . TheP optionforcesapathsearchforeachname,evenift wouldnotreturnf i l e . Ifacommandishashed,p andP printthehashedvalue,notnecessarilythefilethatappearsfirstin$ P A T H . Ifthea optionisused,t y p e returnsalloftheplacesthatcontainanexecutablenamedfile.Thisincludesaliasesandfunctions,ifandonlyifthe p optionisnotalsoused. Ifthef optionisused,t y p e doesnotattempttofindshellfunctions,aswiththec o m m a n d builtin. Thereturnstatusiszeroifallofthenamesarefound,nonzeroifanyarenotfound.
t y p e s e t t y p e s e t[ a f F r x i ][ p ][ n a m e [ = v a l u e ] ]
isinterpretedasfollows:
S
Changeandreportthesoftlimitassociatedwitharesource.
H
Changeandreportthehardlimitassociatedwitharesource.
a
Allcurrentlimitsarereported.
b
Themaximumsocketbuffersize.
c
Themaximumsizeofcorefilescreated.
d
Themaximumsizeofaprocesssdatasegment.
e
Themaximumschedulingpriority("nice").
f
Themaximumsizeoffileswrittenbytheshellanditschildren.
i
Themaximumnumberofpendingsignals.
l
Themaximumsizethatmaybelockedintomemory.
m
Themaximumresidentsetsize(manysystemsdonothonorthislimit).
n
Themaximumnumberofopenfiledescriptors(mostsystemsdonotallowthisvaluetobeset).
p
Thepipebuffersize.
q
ThemaximumnumberofbytesinPOSIXmessagequeues.
r
Themaximumrealtimeschedulingpriority.
s
Themaximumstacksize.
t
Themaximumamountofcputimeinseconds.
u
Themaximumnumberofprocessesavailabletoasingleuser.
v
Themaximumamountofvirtualmemoryavailabletotheshell,and,onsomesystems,toitschildren.
x
Themaximumnumberoffilelocks.
T
Themaximumnumberofthreads. Iflimitisgiven,itisthenewvalueofthespecifiedresourcethespeciallimitvaluesh a r d ,s o f t ,andu n l i m i t e d standforthecurrenthardlimit, thecurrentsoftlimit,andnolimit,respectively.Ahardlimitcannotbeincreasedbyanonrootuseronceitissetasoftlimitmaybeincreasedup tothevalueofthehardlimit.Otherwise,thecurrentvalueofthesoftlimitforthespecifiedresourceisprinted,unlesstheH optionissupplied. Whensettingnewlimits,ifneitherH norS issupplied,boththehardandsoftlimitsareset.Ifnooptionisgiven,thenf isassumed.Values arein1024byteincrements,exceptfort ,whichisinseconds,p ,whichisinunitsof512byteblocks,andn andu ,whichareunscaled values. Thereturnstatusiszerounlessaninvalidoptionorargumentissupplied,oranerroroccurswhilesettinganewlimit.
u n a l i a s u n a l i a s[ a ][ n a m e]
4.3ModifyingShellBehavior
TheSetBuiltin: Changethevaluesofshellattributesandpositionalparameters. TheShoptBuiltin: Modifyshelloptionalbehavior. Next:TheShoptBuiltin,Up:ModifyingShellBehavior[Contents][Index] 4.3.1TheSetBuiltin Thisbuiltinissocomplicatedthatitdeservesitsownsection.s e t allowsyoutochangethevaluesofshelloptionsandsetthepositionalparameters,or todisplaythenamesandvaluesofshellvariables.
s e t s e t[ a b e f h k m n p t u v x B C E H P T ][ oo p t i o n n a m e ][ a r g u m e n t ] s e t[ + a b e f h k m n p t u v x B C E H P T ][ + oo p t i o n n a m e ][ a r g u m e n t ]
Markvariablesandfunctionwhicharemodifiedorcreatedforexporttotheenvironmentofsubsequentcommands.
b
Causethestatusofterminatedbackgroundjobstobereportedimmediately,ratherthanbeforeprintingthenextprimaryprompt.
e
Exitimmediatelyifapipeline(seePipelines),whichmayconsistofasinglesimplecommand(seeSimpleCommands),asubshell commandenclosedinparentheses(seeCommandGrouping),oroneofthecommandsexecutedaspartofacommandlistenclosedby braces(seeCommandGrouping)returnsanonzerostatus.Theshelldoesnotexitifthecommandthatfailsispartofthecommandlist immediatelyfollowingaw h i l e oru n t i l keyword,partofthetestinani f statement,partofanycommandexecutedina& & or| | list exceptthecommandfollowingthefinal& & or| | ,anycommandinapipelinebutthelast,orifthecommandsreturnstatusisbeing invertedwith! .AtraponE R R ,ifset,isexecutedbeforetheshellexits. Thisoptionappliestotheshellenvironmentandeachsubshellenvironmentseparately(seeCommandExecutionEnvironment),andmay causesubshellstoexitbeforeexecutingallthecommandsinthesubshell.
f
Disablefilenameexpansion(globbing).
h
Locateandremember(hash)commandsastheyarelookedupforexecution.Thisoptionisenabledbydefault.
k
Allargumentsintheformofassignmentstatementsareplacedintheenvironmentforacommand,notjustthosethatprecedethecommand name.
m
Jobcontrolisenabled(seeJobControl).
Readcommandsbutdonotexecutethemthismaybeusedtocheckascriptforsyntaxerrors.Thisoptionisignoredbyinteractiveshells.
oo p t i o n n a m e
Settheoptioncorrespondingtooptionname:
a l l e x p o r t
Sameasa .
b r a c e e x p a n d
SameasB .
e m a c s
Useane m a c s stylelineeditinginterface(seeCommandLineEditing).Thisalsoaffectstheeditinginterfaceusedforr e a de .
e r r e x i t
Samease .
e r r t r a c e
SameasE .
f u n c t r a c e
SameasT .
h a s h a l l
Sameash .
h i s t e x p a n d
SameasH .
h i s t o r y
Enablecommandhistory,asdescribedinBashHistoryFacilities.Thisoptionisonbydefaultininteractiveshells.
i g n o r e e o f
AninteractiveshellwillnotexituponreadingEOF.
k e y w o r d
Sameask .
m o n i t o r
Sameasm .
n o c l o b b e r
SameasC .
n o e x e c
Sameasn .
n o g l o b
Sameasf .
n o l o g
Currentlyignored.
n o t i f y
Sameasb .
n o u n s e t
Sameasu .
o n e c m d
Sameast .
p h y s i c a l
SameasP .
p i p e f a i l
Ifset,thereturnvalueofapipelineisthevalueofthelast(rightmost)commandtoexitwithanonzerostatus,orzeroifall commandsinthepipelineexitsuccessfully.Thisoptionisdisabledbydefault.
p o s i x
ChangethebehaviorofBashwherethedefaultoperationdiffersfromthePOSIXstandardtomatchthestandard(seeBashPOSIX Mode).ThisisintendedtomakeBashbehaveasastrictsupersetofthatstandard.
p r i v i l e g e d
Sameasp .
v e r b o s e
Sameasv .
v i
Useav i stylelineeditinginterface.Thisalsoaffectstheeditinginterfaceusedforr e a de .
x t r a c e
Sameasx .
p
Turnonprivilegedmode.Inthismode,the$ B A S H _ E N V and$ E N V filesarenotprocessed,shellfunctionsarenotinheritedfromthe environment,andtheS H E L L O P T S ,B A S H O P T S ,C D P A T H andG L O B I G N O R E variables,iftheyappearintheenvironment,areignored.Ifthe shellisstartedwiththeeffectiveuser(group)idnotequaltotherealuser(group)id,andthep optionisnotsupplied,theseactionsare takenandtheeffectiveuseridissettotherealuserid.Ifthep optionissuppliedatstartup,theeffectiveuseridisnotreset.Turningthis optionoffcausestheeffectiveuserandgroupidstobesettotherealuserandgroupids.
t
Exitafterreadingandexecutingonecommand.
u
Printshellinputlinesastheyareread.
x
Theshellwillperformbraceexpansion(seeBraceExpansion).Thisoptionisonbydefault.
C
Enable! stylehistorysubstitution(seeHistoryInteraction).Thisoptionisonbydefaultforinteractiveshells.
P
/ u s r / s y s $c d. . ;p w d / u s r
Ifs e tP ison,then:
$c d/ u s r / s y s ;e c h o$ P W D / u s r / l o c a l / s y s $c d. . ;p w d / u s r / l o c a l T
Ifnoargumentsfollowthisoption,thenthepositionalparametersareunset.Otherwise,thepositionalparametersaresettothearguments, evenifsomeofthembeginwitha.
-
Signaltheendofoptions,causeallremainingargumentstobeassignedtothepositionalparameters.Thex andv optionsareturnedoff. Iftherearenoarguments,thepositionalparametersremainunchanged. Using+ ratherthancausestheseoptionstobeturnedoff.Theoptionscanalsobeuseduponinvocationoftheshell.Thecurrentsetof optionsmaybefoundin$ . TheremainingNargumentsarepositionalparametersandareassigned,inorder,to$ 1 ,$ 2 ,$ N .Thespecialparameter# issettoN. Thereturnstatusisalwayszerounlessaninvalidoptionissupplied. Previous:TheSetBuiltin,Up:ModifyingShellBehavior[Contents][Index] 4.3.2TheShoptBuiltin Thisbuiltinallowsyoutochangeadditionalshelloptionalbehavior.
s h o p t s h o p t[ p q s u ][ o ][ o p t n a m e ]
Enable(set)eachoptname.
u
Disable(unset)eachoptname.
q
Suppressesnormaloutputthereturnstatusindicateswhethertheoptnameissetorunset.Ifmultipleoptnameargumentsaregivenwithq , thereturnstatusiszeroifalloptnamesareenablednonzerootherwise.
o
Restrictsthevaluesofoptnametobethosedefinedfortheo optiontothes e t builtin(seeTheSetBuiltin). Ifeithers oru isusedwithnooptnamearguments,thedisplayislimitedtothoseoptionswhicharesetorunset,respectively. Unlessotherwisenoted,thes h o p t optionsaredisabled(off)bydefault. Thereturnstatuswhenlistingoptionsiszeroifalloptnamesareenabled,nonzerootherwise.Whensettingorunsettingoptions,thereturnstatus iszerounlessanoptnameisnotavalidshelloption. Thelistofs h o p t optionsis:
a u t o c d
Ifthisisset,anargumenttothec d builtincommandthatisnotadirectoryisassumedtobethenameofavariablewhosevalueisthe
directorytochangeto.
c d s p e l l
Ifthisisset,Bashchecksthatacommandfoundinthehashtableexistsbeforetryingtoexecuteit.Ifahashedcommandnolongerexists,a normalpathsearchisperformed.
c h e c k j o b s
Ifset,Bashchecksthewindowsizeaftereachcommandand,ifnecessary,updatesthevaluesofL I N E S andC O L U M N S .
c m d h i s t
Ifset,Bashattemptstosavealllinesofamultiplelinecommandinthesamehistoryentry.Thisallowseasyreeditingofmultiline commands.
c o m p a t 3 1
Ifset,Bashchangesitsbehaviortothatofversion3.1withrespecttoquotedargumentstotheconditionalcommands= ~ operator.
c o m p a t 3 2
Ifset,Bashattemptsspellingcorrectionondirectorynamesduringwordcompletionifthedirectorynameinitiallysupplieddoesnotexist.
d o t g l o b
Ifset,Bashincludesfilenamesbeginningwitha.intheresultsoffilenameexpansion.
e x e c f a i l
Ifset,aliasesareexpandedasdescribedbelowunderAliases,Aliases.Thisoptionisenabledbydefaultforinteractiveshells.
e x t d e b u g
Ifset,behaviorintendedforusebydebuggersisenabled: 1. TheF optiontothed e c l a r e builtin(seeBashBuiltins)displaysthesourcefilenameandlinenumbercorrespondingtoeach functionnamesuppliedasanargument. 2. IfthecommandrunbytheD E B U G trapreturnsanonzerovalue,thenextcommandisskippedandnotexecuted. 3. IfthecommandrunbytheD E B U G trapreturnsavalueof2,andtheshellisexecutinginasubroutine(ashellfunctionorashellscript executedbythe. ors o u r c e builtins),acalltor e t u r n issimulated. 4. B A S H _ A R G C andB A S H _ A R G V areupdatedasdescribedintheirdescriptions(seeBashVariables). 5. Functiontracingisenabled:commandsubstitution,shellfunctions,andsubshellsinvokedwith( c o m m a n d) inherittheD E B U G and R E T U R N traps. 6. Errortracingisenabled:commandsubstitution,shellfunctions,andsubshellsinvokedwith( c o m m a n d) inherittheE R R trap.
e x t g l o b
Ifset,theextendedpatternmatchingfeaturesdescribedabove(seePatternMatching)areenabled.
e x t q u o t e
Ifset,patternswhichfailtomatchfilenamesduringfilenameexpansionresultinanexpansionerror.
f o r c e _ f i g n o r e
Ifset,shellerrormessagesarewritteninthestandardGNUerrormessageformat.
h i s t a p p e n d
Ifset,andReadlineisbeingused,auserisgiventheopportunitytoreeditafailedhistorysubstitution.
h i s t v e r i f y
Ifset,andReadlineisbeingused,theresultsofhistorysubstitutionarenotimmediatelypassedtotheshellparser.Instead,theresultingline isloadedintotheReadlineeditingbuffer,allowingfurthermodification.
h o s t c o m p l e t e
Ifset,BashwillsendS I G H U P toalljobswhenaninteractiveloginshellexits(seeSignals).
i n t e r a c t i v e _ c o m m e n t s
Ifset,andjobcontrolisnotactive,theshellrunsthelastcommandofapipelinenotexecutedinthebackgroundinthecurrentshell environment.
l i t h i s t
Theshellsetsthisoptionifitisstartedasaloginshell(seeInvokingBash).Thevaluemaynotbechanged.
m a i l w a r n
Ifset,Bashmatchesfilenamesinacaseinsensitivefashionwhenperformingfilenameexpansion.
n o c a s e m a t c h
Ifset,Bashallowsfilenamepatternswhichmatchnofilestoexpandtoanullstring,ratherthanthemselves.
p r o g c o m p
Ifset,theprogrammablecompletionfacilities(seeProgrammableCompletion)areenabled.Thisoptionisenabledbydefault.
p r o m p t v a r s
Ifset,promptstringsundergoparameterexpansion,commandsubstitution,arithmeticexpansion,andquoteremovalafterbeingexpanded asdescribedbelow(seePrintingaPrompt).Thisoptionisenabledbydefault.
r e s t r i c t e d _ s h e l l
Theshellsetsthisoptionifitisstartedinrestrictedmode(seeTheRestrictedShell).Thevaluemaynotbechanged.Thisisnotresetwhen thestartupfilesareexecuted,allowingthestartupfilestodiscoverwhetherornotashellisrestricted.
s h i f t _ v e r b o s e
Ifthisisset,thes h i f t builtinprintsanerrormessagewhentheshiftcountexceedsthenumberofpositionalparameters.
s o u r c e p a t h
4.4SpecialBuiltins
Forhistoricalreasons,thePOSIXstandardhasclassifiedseveralbuiltincommandsasspecial.WhenBashisexecutinginPOSIXmode,thespecial builtinsdifferfromotherbuiltincommandsinthreerespects: 1. Specialbuiltinsarefoundbeforeshellfunctionsduringcommandlookup. 2. Ifaspecialbuiltinreturnsanerrorstatus,anoninteractiveshellexits. 3. Assignmentstatementsprecedingthecommandstayineffectintheshellenvironmentafterthecommandcompletes. WhenBashisnotexecutinginPOSIXmode,thesebuiltinsbehavenodifferentlythantherestoftheBashbuiltincommands.TheBashPOSIXmodeis describedinBashPOSIXMode. ThesearethePOSIXspecialbuiltins:
b r e a k:.c o n t i n u ee v a le x e ce x i te x p o r tr e a d o n l yr e t u r ns e t s h i f tt r a pu n s e t
Next:BashFeatures,Previous:ShellBuiltinCommands,Up:Top[Contents][Index]
5ShellVariables
BourneShellVariables: VariableswhichBashusesinthesamewayastheBourneShell. BashVariables: ListofvariablesthatexistinBash. ThischapterdescribestheshellvariablesthatBashuses.Bashautomaticallyassignsdefaultvaluestoanumberofvariables. Next:BashVariables,Up:ShellVariables[Contents][Index]
5.1BourneShellVariables
BashusescertainshellvariablesinthesamewayastheBourneshell.Insomecases,Bashassignsadefaultvaluetothevariable.
C D P A T H
Acolonseparatedlistofdirectoriesusedasasearchpathforthec d builtincommand.
H O M E
Alistofcharactersthatseparatefieldsusedwhentheshellsplitswordsaspartofexpansion.
M A I L
Thevalueofthelastoptionargumentprocessedbytheg e t o p t s builtin.
O P T I N D
Theindexofthelastoptionargumentprocessedbytheg e t o p t s builtin.
P A T H
Thesecondarypromptstring.Thedefaultvalueis> . Previous:BourneShellVariables,Up:ShellVariables[Contents][Index]
5.2BashVariables
ThesevariablesaresetorusedbyBash,butothershellsdonotnormallytreatthemspecially. AfewvariablesusedbyBasharedescribedindifferentchapters:variablesforcontrollingthejobcontrolfacilities(seeJobControlVariables).
B A S H
ThefullpathnameusedtoexecutethecurrentinstanceofBash.
B A S H O P T S
Anarrayvariablewhosevaluesarethenumberofparametersineachframeofthecurrentbashexecutioncallstack.Thenumberofparametersto thecurrentsubroutine(shellfunctionorscriptexecutedwith. ors o u r c e )isatthetopofthestack.Whenasubroutineisexecuted,thenumberof parameterspassedispushedontoB A S H _ A R G C .TheshellsetsB A S H _ A R G C onlywheninextendeddebuggingmode(seeTheShoptBuiltinfora descriptionofthee x t d e b u g optiontothes h o p t builtin).
B A S H _ A R G V
Anarrayvariablecontainingalloftheparametersinthecurrentbashexecutioncallstack.Thefinalparameterofthelastsubroutinecallisatthe topofthestackthefirstparameteroftheinitialcallisatthebottom.Whenasubroutineisexecuted,theparameterssuppliedarepushedonto
Thecommandcurrentlybeingexecutedorabouttobeexecuted,unlesstheshellisexecutingacommandastheresultofatrap,inwhichcaseitis thecommandexecutingatthetimeofthetrap.
B A S H _ E N V
IfthisvariableissetwhenBashisinvokedtoexecuteashellscript,itsvalueisexpandedandusedasthenameofastartupfiletoreadbefore executingthescript.SeeBashStartupFiles.
B A S H _ E X E C U T I O N _ S T R I N G
Thecommandargumenttothec invocationoption.
B A S H _ L I N E N O
Incrementedbyoneeachtimeasubshellorsubshellenvironmentisspawned.Theinitialvalueis0.
B A S H _ V E R S I N F O
Areadonlyarrayvariable(seeArrays)whosemembersholdversioninformationforthisinstanceofBash.Thevaluesassignedtothearray membersareasfollows:
B A S H _ V E R S I N F O [ 0 ]
Themajorversionnumber(therelease).
B A S H _ V E R S I N F O [ 1 ]
Theminorversionnumber(theversion).
B A S H _ V E R S I N F O [ 2 ]
Thepatchlevel.
B A S H _ V E R S I N F O [ 3 ]
Thebuildversion.
B A S H _ V E R S I N F O [ 4 ]
Thereleasestatus(e.g.,beta1).
B A S H _ V E R S I N F O [ 5 ]
ThevalueofM A C H T Y P E .
B A S H _ V E R S I O N
TheversionnumberofthecurrentinstanceofBash.
B A S H _ X T R A C E F D
NotethatsettingB A S H _ X T R A C E F D to2(thestandarderrorfiledescriptor)andthenunsettingitwillresultinthestandarderrorbeingclosed.
C O L U M N S
Usedbythes e l e c t commandtodeterminetheterminalwidthwhenprintingselectionlists.AutomaticallysetuponreceiptofaS I G W I N C H .
C O M P _ C W O R D
Thecurrentcommandline.Thisvariableisavailableonlyinshellfunctionsandexternalcommandsinvokedbytheprogrammablecompletion facilities(seeProgrammableCompletion).
C O M P _ P O I N T
Thekey(orfinalkeyofakeysequence)usedtoinvokethecurrentcompletionfunction.
C O M P _ W O R D B R E A K S
AnarrayvariablefromwhichBashreadsthepossiblecompletionsgeneratedbyashellfunctioninvokedbytheprogrammablecompletion facility(seeProgrammableCompletion).
C O P R O C
Anarrayvariablecreatedtoholdthefiledescriptorsforoutputfromandinputtoanunnamedcoprocess(seeCoprocesses).
D I R S T A C K
SimilartoB A S H _ E N V usedwhentheshellisinvokedinPOSIXMode(seeBashPOSIXMode).
E U I D
Thenumericeffectiveuseridofthecurrentuser.Thisvariableisreadonly.
F C E D I T
Acolonseparatedlistofsuffixestoignorewhenperformingfilenamecompletion.Afilenamewhosesuffixmatchesoneoftheentriesin F I G N O R E isexcludedfromthelistofmatchedfilenames.Asamplevalueis. o : ~
F U N C N A M E
Anarrayvariablecontainingthenamesofallshellfunctionscurrentlyintheexecutioncallstack.Theelementwithindex0isthenameofany currentlyexecutingshellfunction.Thebottommostelement(theonewiththehighestindex)is" m a i n " .Thisvariableexistsonlywhenashell functionisexecuting.AssignmentstoF U N C N A M E havenoeffectandreturnanerrorstatus.IfF U N C N A M E isunset,itlosesitsspecialproperties,even ifitissubsequentlyreset. ThisvariablecanbeusedwithB A S H _ L I N E N O andB A S H _ S O U R C E .EachelementofF U N C N A M E hascorrespondingelementsinB A S H _ L I N E N O and B A S H _ S O U R C E todescribethecallstack.Forinstance,$ { F U N C N A M E [ $ i ] } wascalledfromthefile$ { B A S H _ S O U R C E [ $ i + 1 ] } atlinenumber $ { B A S H _ L I N E N O [ $ i ] } .Thec a l l e r builtindisplaysthecurrentcallstackusingthisinformation.
F U N C N E S T
Ifsettoanumericvaluegreaterthan0,definesamaximumfunctionnestinglevel.Functioninvocationsthatexceedthisnestinglevelwillcause thecurrentcommandtoabort.
G L O B I G N O R E
Acolonseparatedlistofvaluescontrollinghowcommandsaresavedonthehistorylist.Ifthelistofvaluesincludesi g n o r e s p a c e ,lineswhich beginwithaspacecharacterarenotsavedinthehistorylist.Avalueofi g n o r e d u p s causeslineswhichmatchtheprevioushistoryentrytonot besaved.Avalueofi g n o r e b o t h isshorthandfori g n o r e s p a c e andi g n o r e d u p s .Avalueofe r a s e d u p s causesallpreviouslines matchingthecurrentlinetoberemovedfromthehistorylistbeforethatlineissaved.Anyvaluenotintheabovelistisignored.IfH I S T C O N T R O L isunset,ordoesnotincludeavalidvalue,alllinesreadbytheshellparseraresavedonthehistorylist,subjecttothevalueofH I S T I G N O R E .The secondandsubsequentlinesofamultilinecompoundcommandarenottested,andareaddedtothehistoryregardlessofthevalueof H I S T C O N T R O L .
H I S T F I L E
Thenameofthefiletowhichthecommandhistoryissaved.Thedefaultvalueis~ / . b a s h _ h i s t o r y .
H I S T F I L E S I Z E
Themaximumnumberofcommandstorememberonthehistorylist.Thedefaultvalueis500.
H I S T T I M E F O R M A T
Thisusesthehistorycommentcharactertodistinguishtimestampsfromotherhistorylines.
H O S T F I L E
Thenameofthecurrenthost.
H O S T T Y P E
AstringdescribingthemachineBashisrunningon.
I G N O R E E O F
ThenameoftheReadlineinitializationfile,overridingthedefaultof~ / . i n p u t r c .
L A N G
UsedtodeterminethelocalecategoryforanycategorynotspecificallyselectedwithavariablestartingwithL C _ .
L C _ A L L
Thisvariabledeterminesthecollationorderusedwhensortingtheresultsoffilenameexpansion,anddeterminesthebehaviorofrange expressions,equivalenceclasses,andcollatingsequenceswithinfilenameexpansionandpatternmatching(seeFilenameExpansion).
L C _ C T Y P E
Thisvariabledeterminestheinterpretationofcharactersandthebehaviorofcharacterclasseswithinfilenameexpansionandpatternmatching (seeFilenameExpansion).
L C _ M E S S A G E S
Thisvariabledeterminesthelocaleusedtotranslatedoublequotedstringsprecededbya$ (seeLocaleTranslation).
L C _ N U M E R I C
Thisvariabledeterminesthelocalecategoryusedfornumberformatting.
L I N E N O
Thelinenumberinthescriptorshellfunctioncurrentlyexecuting.
L I N E S
Usedbythes e l e c t commandtodeterminethecolumnlengthforprintingselectionlists.AutomaticallysetuponreceiptofaS I G W I N C H .
M A C H T Y P E
AstringthatfullydescribesthesystemtypeonwhichBashisexecuting,inthestandardGNUcpucompanysystemformat.
M A I L C H E C K
Anarrayvariablecreatedtoholdthetextreadbythem a p f i l e builtinwhennovariablenameissupplied.
O L D P W D
Thepreviousworkingdirectoryassetbythec d builtin.
O P T E R R
Ifsettothevalue1,Bashdisplayserrormessagesgeneratedbytheg e t o p t s builtincommand.
O S T Y P E
AstringdescribingtheoperatingsystemBashisrunningon.
P I P E S T A T U S
Anarrayvariable(seeArrays)containingalistofexitstatusvaluesfromtheprocessesinthemostrecentlyexecutedforegroundpipeline(which maycontainonlyasinglecommand).
P O S I X L Y _ C O R R E C T
hadbeenexecuted.
P P I D
TheprocessIDoftheshellsparentprocess.Thisvariableisreadonly.
P R O M P T _ C O M M A N D
Ifset,thevalueisinterpretedasacommandtoexecutebeforetheprintingofeachprimaryprompt($ P S 1 ).
P R O M P T _ D I R T R I M
Thecurrentworkingdirectoryassetbythec d builtin.
R A N D O M
Eachtimethisparameterisreferenced,arandomintegerbetween0and32767isgenerated.Assigningavaluetothisvariableseedstherandom numbergenerator.
R E A D L I N E _ L I N E
ThecontentsoftheReadlinelinebuffer,forusewithb i n dx (seeBashBuiltins).
R E A D L I N E _ P O I N T
ThepositionoftheinsertionpointintheReadlinelinebuffer,forusewithb i n dx (seeBashBuiltins).
R E P L Y
Thedefaultvariableforther e a d builtin.
S E C O N D S
Thisvariableexpandstothenumberofsecondssincetheshellwasstarted.Assignmenttothisvariableresetsthecounttothevalueassigned,and theexpandedvaluebecomesthevalueassignedplusthenumberofsecondssincetheassignment.
S H E L L
Thefullpathnametotheshelliskeptinthisenvironmentvariable.Ifitisnotsetwhentheshellstarts,Bashassignstoitthefullpathnameofthe currentusersloginshell.
S H E L L O P T S
IncrementedbyoneeachtimeanewinstanceofBashisstarted.ThisisintendedtobeacountofhowdeeplyyourBashshellsarenested.
T I M E F O R M A T
Aliteral% .
% [ p ] [ l ] R
Theelapsedtimeinseconds.
% [ p ] [ l ] U
ThenumberofCPUsecondsspentinusermode.
% [ p ] [ l ] S
ThenumberofCPUsecondsspentinsystemmode.
% P
Ifthevalueisnull,notiminginformationisdisplayed.Atrailingnewlineisaddedwhentheformatstringisdisplayed.
T M O U T
Ifset,BashusesitsvalueasthenameofadirectoryinwhichBashcreatestemporaryfilesfortheshellsuse.
U I D
Thenumericrealuseridofthecurrentuser.Thisvariableisreadonly. Next:JobControl,Previous:ShellVariables,Up:Top[Contents][Index]
6BashFeatures
ThissectiondescribesfeaturesuniquetoBash. InvokingBash: CommandlineoptionsthatyoucangivetoBash. BashStartupFiles: WhenandhowBashexecutesscripts. InteractiveShells: Whataninteractiveshellis. BashConditionalExpressions: Primitivesusedincomposingexpressionsforthet e s t builtin. ShellArithmetic: Arithmeticonshellvariables. Aliases: Substitutingonecommandforanother. Arrays: ArrayVariables. TheDirectoryStack: Historyofvisiteddirectories. PrintingaPrompt: ControllingthePS1string. TheRestrictedShell: Amorecontrolledmodeofshellexecution. BashPOSIXMode: MakingBashbehavemorecloselytowhatthePOSIXstandardspecifies. Next:BashStartupFiles,Up:BashFeatures[Contents][Index]
6.1InvokingBash
b a s h[ l o n g o p t ][ i r ][ a b e f h k m n p t u v x d B C D H P ][ oo p t i o n ][ Os h o p t _ o p t i o n ][ a r g u m e n t ] b a s h[ l o n g o p t ][ a b e f h k m n p t u v x d B C D H P ][ oo p t i o n ][ Os h o p t _ o p t i o n ]cs t r i n g[ a r g u m e n t ] b a s h[ l o n g o p t ]s[ a b e f h k m n p t u v x d B C D H P ][ oo p t i o n ][ Os h o p t _ o p t i o n ][ a r g u m e n t ]
EquivalenttoD .
h e l p
Displayausagemessageonstandardoutputandexitsuccessfully.
i n i t f i l ef i l e n a m e r c f i l ef i l e n a m e
Executecommandsfromfilename(insteadof~ / . b a s h r c )inaninteractiveshell.
l o g i n
Equivalenttol .
n o e d i t i n g
DonotusetheGNUReadlinelibrary(seeCommandLineEditing)toreadcommandlineswhentheshellisinteractive.
n o p r o f i l e
Dontreadthe~ / . b a s h r c initializationfileinaninteractiveshell.Thisisonbydefaultiftheshellisinvokedass h .
p o s i x
ChangethebehaviorofBashwherethedefaultoperationdiffersfromthePOSIXstandardtomatchthestandard.ThisisintendedtomakeBash behaveasastrictsupersetofthatstandard.SeeBashPOSIXMode,foradescriptionoftheBashPOSIXmode.
r e s t r i c t e d
Maketheshellarestrictedshell(seeTheRestrictedShell).
v e r b o s e
Equivalenttov .Printshellinputlinesastheyreread.
v e r s i o n
Readandexecutecommandsfromstringafterprocessingtheoptions,thenexit.Anyremainingargumentsareassignedtothepositional parameters,startingwith$ 0 .
i
Forcetheshelltoruninteractively.InteractiveshellsaredescribedinInteractiveShells.
l
Maketheshellarestrictedshell(seeTheRestrictedShell).
s
Ifthisoptionispresent,orifnoargumentsremainafteroptionprocessing,thencommandsarereadfromthestandardinput.Thisoptionallows thepositionalparameterstobesetwheninvokinganinteractiveshell.
D
Asignalstheendofoptionsanddisablesfurtheroptionprocessing.Anyargumentsafterthearetreatedasfilenamesandarguments. Aloginshellisonewhosefirstcharacterofargumentzerois,oroneinvokedwiththel o g i n option. Aninteractiveshellisonestartedwithoutnonoptionarguments,unlesss isspecified,withoutspecifyingthec option,andwhoseinputandoutput arebothconnectedtoterminals(asdeterminedbyi s a t t y ( 3 ) ),oronestartedwiththei option.SeeInteractiveShells,formoreinformation. Ifargumentsremainafteroptionprocessing,andneitherthec northes optionhasbeensupplied,thefirstargumentisassumedtobethenameofa filecontainingshellcommands(seeShellScripts).WhenBashisinvokedinthisfashion,$ 0 issettothenameofthefile,andthepositionalparameters aresettotheremainingarguments.Bashreadsandexecutescommandsfromthisfile,thenexits.Bashsexitstatusistheexitstatusofthelastcommand executedinthescript.Ifnocommandsareexecuted,theexitstatusis0. Next:InteractiveShells,Previous:InvokingBash,Up:BashFeatures[Contents][Index]
6.2BashStartupFiles
ThissectiondescribeshowBashexecutesitsstartupfiles.Ifanyofthefilesexistbutcannotberead,Bashreportsanerror.Tildesareexpandedinfile namesasdescribedaboveunderTildeExpansion(seeTildeExpansion). InteractiveshellsaredescribedinInteractiveShells. Invokedasaninteractiveloginshell,orwithl o g i n WhenBashisinvokedasaninteractiveloginshell,orasanoninteractiveshellwiththel o g i n option,itfirstreadsandexecutescommandsfromthe file/ e t c / p r o f i l e ,ifthatfileexists.Afterreadingthatfile,itlooksfor~ / . b a s h _ p r o f i l e ,~ / . b a s h _ l o g i n ,and~ / . p r o f i l e ,inthatorder,andreads andexecutescommandsfromthefirstonethatexistsandisreadable.Then o p r o f i l e optionmaybeusedwhentheshellisstartedtoinhibitthis behavior. Whenaloginshellexits,Bashreadsandexecutescommandsfromthefile~ / . b a s h _ l o g o u t ,ifitexists. Invokedasaninteractivenonloginshell Whenaninteractiveshellthatisnotaloginshellisstarted,Bashreadsandexecutescommandsfrom~ / . b a s h r c ,ifthatfileexists.Thismaybe inhibitedbyusingthen o r c option.Ther c f i l ef i l e optionwillforceBashtoreadandexecutecommandsfromfileinsteadof~ / . b a s h r c . So,typically,your~ / . b a s h _ p r o f i l e containstheline
i f[f~ / . b a s h r c] ;t h e n.~ / . b a s h r c ;f i
IfBashisinvokedwiththenames h ,ittriestomimicthestartupbehaviorofhistoricalversionsofs h ascloselyaspossible,whileconformingtothe POSIXstandardaswell. Wheninvokedasaninteractiveloginshell,orasanoninteractiveshellwiththel o g i n option,itfirstattemptstoreadandexecutecommandsfrom / e t c / p r o f i l e and~ / . p r o f i l e ,inthatorder.Then o p r o f i l e optionmaybeusedtoinhibitthisbehavior.Wheninvokedasaninteractiveshell withthenames h ,BashlooksforthevariableE N V ,expandsitsvalueifitisdefined,andusestheexpandedvalueasthenameofafiletoreadand execute.Sinceashellinvokedass h doesnotattempttoreadandexecutecommandsfromanyotherstartupfiles,ther c f i l e optionhasnoeffect.A noninteractiveshellinvokedwiththenames h doesnotattempttoreadanyotherstartupfiles. Wheninvokedass h ,BashentersPOSIXmodeafterthestartupfilesareread. InvokedinPOSIXmode WhenBashisstartedinPOSIXmode,aswiththep o s i x commandlineoption,itfollowsthePOSIXstandardforstartupfiles.Inthismode,interactive shellsexpandtheE N V variableandcommandsarereadandexecutedfromthefilewhosenameistheexpandedvalue.Nootherstartupfilesareread. Invokedbyremoteshelldaemon Bashattemptstodeterminewhenitisbeingrunwithitsstandardinputconnectedtoanetworkconnection,aswhenexecutedbytheremoteshell daemon,usuallyr s h d ,orthesecureshelldaemons s h d .IfBashdeterminesitisbeingruninthisfashion,itreadsandexecutescommandsfrom ~ / . b a s h r c ,ifthatfileexistsandisreadable.Itwillnotdothisifinvokedass h .Then o r c optionmaybeusedtoinhibitthisbehavior,andther c f i l e optionmaybeusedtoforceanotherfiletoberead,butr s h d doesnotgenerallyinvoketheshellwiththoseoptionsorallowthemtobe specified. InvokedwithunequaleffectiveandrealUID/GIDs IfBashisstartedwiththeeffectiveuser(group)idnotequaltotherealuser(group)id,andthep optionisnotsupplied,nostartupfilesareread,shell functionsarenotinheritedfromtheenvironment,theS H E L L O P T S ,B A S H O P T S ,C D P A T H ,andG L O B I G N O R E variables,iftheyappearintheenvironment,are ignored,andtheeffectiveuseridissettotherealuserid.Ifthep optionissuppliedatinvocation,thestartupbehavioristhesame,buttheeffective useridisnotreset. Next:BashConditionalExpressions,Previous:BashStartupFiles,Up:BashFeatures[Contents][Index]
6.3InteractiveShells
WhatisanInteractiveShell?: WhatdetermineswhetherashellisInteractive. IsthisShellInteractive?: Howtotellifashellisinteractive. InteractiveShellBehavior: Whatchangesinainteractiveshell? Next:IsthisShellInteractive?,Up:InteractiveShells[Contents][Index] 6.3.1WhatisanInteractiveShell? Aninteractiveshellisonestartedwithoutnonoptionarguments,unlesss isspecified,withoutspecifyingthec option,andwhoseinputanderror outputarebothconnectedtoterminals(asdeterminedbyi s a t t y ( 3 ) ),oronestartedwiththei option. Aninteractiveshellgenerallyreadsfromandwritestoausersterminal. Thes invocationoptionmaybeusedtosetthepositionalparameterswhenaninteractiveshellisstarted. Next:InteractiveShellBehavior,Previous:WhatisanInteractiveShell?,Up:InteractiveShells[Contents][Index] 6.3.2IsthisShellInteractive? TodeterminewithinastartupscriptwhetherornotBashisrunninginteractively,testthevalueofthespecialparameter.Itcontainsi whentheshell isinteractive.Forexample:
c a s e" $ "i n * i * ) e c h oT h i ss h e l li si n t e r a c t i v e; ; * ) e c h oT h i ss h e l li sn o ti n t e r a c t i v e; ; e s a c
Alternatively,startupscriptsmayexaminethevariableP S 1 itisunsetinnoninteractiveshells,andsetininteractiveshells.Thus:
i f[z" $ P S 1 "] ;t h e n e c h oT h i ss h e l li sn o ti n t e r a c t i v e e l s e e c h oT h i ss h e l li si n t e r a c t i v e f i
Previous:IsthisShellInteractive?,Up:InteractiveShells[Contents][Index]
6.3.3InteractiveShellBehavior Whentheshellisrunninginteractively,itchangesitsbehaviorinseveralways. 1. StartupfilesarereadandexecutedasdescribedinBashStartupFiles. 2. JobControl(seeJobControl)isenabledbydefault.Whenjobcontrolisineffect,Bashignoresthekeyboardgeneratedjobcontrolsignals S I G T T I N ,S I G T T O U ,andS I G T S T P . 3. BashexpandsanddisplaysP S 1 beforereadingthefirstlineofacommand,andexpandsanddisplaysP S 2 beforereadingthesecondand subsequentlinesofamultilinecommand. 4. BashexecutesthevalueoftheP R O M P T _ C O M M A N D variableasacommandbeforeprintingtheprimaryprompt,$ P S 1 (seeBashVariables). 5. Readline(seeCommandLineEditing)isusedtoreadcommandsfromtheusersterminal. 6. Bashinspectsthevalueofthei g n o r e e o f optiontos e to insteadofexitingimmediatelywhenitreceivesanE O F onitsstandardinputwhen readingacommand(seeTheSetBuiltin). 7. Commandhistory(seeBashHistoryFacilities)andhistoryexpansion(seeHistoryInteraction)areenabledbydefault.Bashwillsavethe commandhistorytothefilenamedby$ H I S T F I L E whenaninteractiveshellexits. 8. Aliasexpansion(seeAliases)isperformedbydefault. 9. Intheabsenceofanytraps,BashignoresS I G T E R M (seeSignals). 10. Intheabsenceofanytraps,S I G I N T iscaughtandhandled((seeSignals).S I G I N T willinterruptsomeshellbuiltins. 11. AninteractiveloginshellsendsaS I G H U P toalljobsonexitiftheh u p o n e x i t shelloptionhasbeenenabled(seeSignals). 12. Then invocationoptionisignored,ands e tn hasnoeffect(seeTheSetBuiltin). 13. Bashwillcheckformailperiodically,dependingonthevaluesoftheM A I L ,M A I L P A T H ,andM A I L C H E C K shellvariables(seeBashVariables). 14. Expansionerrorsduetoreferencestounboundshellvariablesafters e tu hasbeenenabledwillnotcausetheshelltoexit(seeTheSet Builtin). 15. Theshellwillnotexitonexpansionerrorscausedbyvarbeingunsetornullin$ { v a r : ? w o r d } expansions(seeShellParameterExpansion). 16. Redirectionerrorsencounteredbyshellbuiltinswillnotcausetheshelltoexit. 17. WhenrunninginPOSIXmode,aspecialbuiltinreturninganerrorstatuswillnotcausetheshelltoexit(seeBashPOSIXMode). 18. Afailede x e c willnotcausetheshelltoexit(seeBourneShellBuiltins). 19. Parsersyntaxerrorswillnotcausetheshelltoexit. 20. Simplespellingcorrectionfordirectoryargumentstothec d builtinisenabledbydefault(seethedescriptionofthec d s p e l l optiontothes h o p t builtininTheShoptBuiltin). 21. TheshellwillcheckthevalueoftheT M O U T variableandexitifacommandisnotreadwithinthespecifiednumberofsecondsafterprinting$ P S 1 (seeBashVariables). Next:ShellArithmetic,Previous:InteractiveShells,Up:BashFeatures[Contents][Index]
6.4BashConditionalExpressions
Conditionalexpressionsareusedbythe[ [ compoundcommandandthet e s t and[ builtincommands. Expressionsmaybeunaryorbinary.Unaryexpressionsareoftenusedtoexaminethestatusofafile.Therearestringoperatorsandnumeric comparisonoperatorsaswell.Ifthefileargumenttooneoftheprimariesisoftheform/ d e v / f d / N ,thenfiledescriptorNischecked.Ifthefile argumenttooneoftheprimariesisoneof/ d e v / s t d i n ,/ d e v / s t d o u t ,or/ d e v / s t d e r r ,filedescriptor0,1,or2,respectively,ischecked. Whenusedwith[ [ ,the< and> operatorssortlexicographicallyusingthecurrentlocale.Thet e s t commandusesASCIIordering. Unlessotherwisespecified,primariesthatoperateonfilesfollowsymboliclinksandoperateonthetargetofthelink,ratherthanthelinkitself.
af i l e
Trueiffileexists.
bf i l e
Trueiffileexistsandisablockspecialfile.
cf i l e
Trueiffileexistsandisacharacterspecialfile.
df i l e
Trueiffileexistsandisadirectory.
ef i l e
Trueiffileexists.
ff i l e
Trueiffileexistsandisaregularfile.
gf i l e
Trueiffileexistsanditssetgroupidbitisset.
hf i l e
Trueiffileexistsandisasymboliclink.
kf i l e
Trueiffileexistsandits"sticky"bitisset.
pf i l e
Trueiffileexistsandisanamedpipe(FIFO).
rf i l e
Trueiffileexistsandisreadable.
sf i l e
Trueiffileexistsandhasasizegreaterthanzero.
tf d
Trueiffiledescriptorfdisopenandreferstoaterminal.
uf i l e
Trueiffileexistsanditssetuseridbitisset.
wf i l e
Trueiffileexistsandiswritable.
xf i l e
Trueiffileexistsandisexecutable.
Gf i l e
Trueiffileexistsandisownedbytheeffectivegroupid.
Lf i l e
Trueiffileexistsandisasymboliclink.
Nf i l e
Trueiffileexistsandhasbeenmodifiedsinceitwaslastread.
Of i l e
Trueiffileexistsandisownedbytheeffectiveuserid.
Sf i l e
Trueiffileexistsandisasocket.
f i l e 1e ff i l e 2
Trueiffile1andfile2refertothesamedeviceandinodenumbers.
f i l e 1n tf i l e 2
Trueiffile1isnewer(accordingtomodificationdate)thanfile2,oriffile1existsandfile2doesnot.
f i l e 1o tf i l e 2
Trueiffile1isolderthanfile2,oriffile2existsandfile1doesnot.
oo p t n a m e
Trueiftheshellvariablevarnameisset(hasbeenassignedavalue).
zs t r i n g
Trueifthelengthofstringiszero.
ns t r i n g s t r i n g
Trueifthelengthofstringisnonzero.
s t r i n g 1= =s t r i n g 2
s t r i n g 1=s t r i n g 2
Trueifthestringsarenotequal.
s t r i n g 1<s t r i n g 2
Trueifstring1sortsbeforestring2lexicographically.
s t r i n g 1>s t r i n g 2
Trueifstring1sortsafterstring2lexicographically.
a r g 1O Pa r g 2 O P isoneofe q ,n e ,l t ,l e ,g t ,org e .Thesearithmeticbinaryoperatorsreturntrueifarg1isequalto,notequalto,lessthan,
lessthanorequalto,greaterthan,orgreaterthanorequaltoarg2,respectively.Arg1andarg2maybepositiveornegativeintegers. Next:Aliases,Previous:BashConditionalExpressions,Up:BashFeatures[Contents][Index]
6.5ShellArithmetic
Theshellallowsarithmeticexpressionstobeevaluated,asoneoftheshellexpansionsorbythel e t andthei optiontothed e c l a r e builtins. Evaluationisdoneinfixedwidthintegerswithnocheckforoverflow,thoughdivisionby0istrappedandflaggedasanerror.Theoperatorsandtheir precedence,associativity,andvaluesarethesameasintheClanguage.Thefollowinglistofoperatorsisgroupedintolevelsofequalprecedence operators.Thelevelsarelistedinorderofdecreasingprecedence.
i d + +i d -
variablepostincrementandpostdecrement
+ + i di d
variablepreincrementandpredecrement
-+
unaryminusandplus
!~
logicalandbitwisenegation
* *
exponentiation
*/%
multiplication,division,remainder
+-
addition,subtraction
< <> >
leftandrightbitwiseshifts
< => =<>
comparison
= =! =
equalityandinequality
&
bitwiseAND
^
bitwiseexclusiveOR
|
bitwiseOR
& &
logicalAND
| |
logicalOR
e x p r?e x p r:e x p r
conditionaloperator
=* =/ =% =+ ==< < => > =& =^ =| =
assignment
e x p r 1,e x p r 2
comma Shellvariablesareallowedasoperandsparameterexpansionisperformedbeforetheexpressionisevaluated.Withinanexpression,shellvariablesmay alsobereferencedbynamewithoutusingtheparameterexpansionsyntax.Ashellvariablethatisnullorunsetevaluatesto0whenreferencedbyname withoutusingtheparameterexpansionsyntax.Thevalueofavariableisevaluatedasanarithmeticexpressionwhenitisreferenced,orwhenavariable whichhasbeengiventheintegerattributeusingd e c l a r ei isassignedavalue.Anullvalueevaluatesto0.Ashellvariableneednothaveits integerattributeturnedontobeusedinanexpression. Constantswithaleading0areinterpretedasoctalnumbers.Aleading0 x or0 X denoteshexadecimal.Otherwise,numberstaketheform[base# ]n, wheretheoptionalbaseisadecimalnumberbetween2and64representingthearithmeticbase,andnisanumberinthatbase.Ifbase# isomitted,then base10isused.Thedigitsgreaterthan9arerepresentedbythelowercaseletters,theuppercaseletters,@ ,and_ ,inthatorder.Ifbaseislessthanor equalto36,lowercaseanduppercaselettersmaybeusedinterchangeablytorepresentnumbersbetween10and35. Operatorsareevaluatedinorderofprecedence.Subexpressionsinparenthesesareevaluatedfirstandmayoverridetheprecedencerulesabove. Next:Arrays,Previous:ShellArithmetic,Up:BashFeatures[Contents][Index]
6.6Aliases
Aliasesallowastringtobesubstitutedforawordwhenitisusedasthefirstwordofasimplecommand.Theshellmaintainsalistofaliasesthatmaybe setandunsetwiththea l i a s andu n a l i a s builtincommands. Thefirstwordofeachsimplecommand,ifunquoted,ischeckedtoseeifithasanalias.Ifso,thatwordisreplacedbythetextofthealias.The characters/ ,$ ,` ,= andanyoftheshellmetacharactersorquotingcharacterslistedabovemaynotappearinanaliasname.Thereplacementtext maycontainanyvalidshellinput,includingshellmetacharacters.Thefirstwordofthereplacementtextistestedforaliases,butawordthatisidentical toanaliasbeingexpandedisnotexpandedasecondtime.Thismeansthatonemayaliasl s to" l sF " ,forinstance,andBashdoesnottryto recursivelyexpandthereplacementtext.Ifthelastcharacterofthealiasvalueisaspaceortabcharacter,thenthenextcommandwordfollowingthe aliasisalsocheckedforaliasexpansion. Aliasesarecreatedandlistedwiththea l i a s command,andremovedwiththeu n a l i a s command. Thereisnomechanismforusingargumentsinthereplacementtext,asinc s h .Ifargumentsareneeded,ashellfunctionshouldbeused(seeShell Functions). Aliasesarenotexpandedwhentheshellisnotinteractive,unlessthee x p a n d _ a l i a s e s shelloptionissetusings h o p t (seeTheShoptBuiltin). Therulesconcerningthedefinitionanduseofaliasesaresomewhatconfusing.Bashalwaysreadsatleastonecompletelineofinputbeforeexecuting anyofthecommandsonthatline.Aliasesareexpandedwhenacommandisread,notwhenitisexecuted.Therefore,analiasdefinitionappearingon thesamelineasanothercommanddoesnottakeeffectuntilthenextlineofinputisread.Thecommandsfollowingthealiasdefinitiononthatlineare notaffectedbythenewalias.Thisbehaviorisalsoanissuewhenfunctionsareexecuted.Aliasesareexpandedwhenafunctiondefinitionisread,not whenthefunctionisexecuted,becauseafunctiondefinitionisitselfacompoundcommand.Asaconsequence,aliasesdefinedinafunctionarenot availableuntilafterthatfunctionisexecuted.Tobesafe,alwaysputaliasdefinitionsonaseparateline,anddonotusea l i a s incompoundcommands. Foralmosteverypurpose,shellfunctionsarepreferredoveraliases. Next:TheDirectoryStack,Previous:Aliases,Up:BashFeatures[Contents][Index]
6.7Arrays
Bashprovidesonedimensionalindexedandassociativearrayvariables.Anyvariablemaybeusedasanindexedarraythed e c l a r e builtinwill explicitlydeclareanarray.Thereisnomaximumlimitonthesizeofanarray,noranyrequirementthatmembersbeindexedorassignedcontiguously. Indexedarraysarereferencedusingintegers(includingarithmeticexpressions(seeShellArithmetic)andarezerobasedassociativearraysusearbitrary strings. Anindexedarrayiscreatedautomaticallyifanyvariableisassignedtousingthesyntax
n a m e [ s u b s c r i p t ] = v a l u e
Thesubscriptistreatedasanarithmeticexpressionthatmustevaluatetoanumber.Ifsubscriptevaluatestoanumberlessthanzero,itisusedasan offsetfromonegreaterthanthearraysmaximumindex(soasubcriptof1referstothelastelementofthearray).Toexplicitlydeclareanarray,use
d e c l a r ean a m e
Thesyntax
d e c l a r ean a m e [ s u b s c r i p t ]
isalsoacceptedthesubscriptisignored. Associativearraysarecreatedusing
d e c l a r eAn a m e .
whereeachvalueisoftheform[ s u b s c r i p t ] = string.Indexedarrayassignmentsdonotrequirethebracketandsubscript.Whenassigningtoindexed arrays,iftheoptionalsubscriptissupplied,thatindexisassignedtootherwisetheindexoftheelementassignedisthelastindexassignedtobythe statementplusone.Indexingstartsatzero. Whenassigningtoanassociativearray,thesubscriptisrequired. Thissyntaxisalsoacceptedbythed e c l a r e builtin.Individualarrayelementsmaybeassignedtousingthen a m e [ subscript] = valuesyntaxintroduced above. Anyelementofanarraymaybereferencedusing$ { n a m e [ subscript] } .Thebracesarerequiredtoavoidconflictswiththeshellsfilenameexpansion operators.Ifthesubscriptis@ or* ,thewordexpandstoallmembersofthearrayname.Thesesubscriptsdifferonlywhenthewordappearswithin doublequotes.Ifthewordisdoublequoted,$ { n a m e [ * ] } expandstoasinglewordwiththevalueofeacharraymemberseparatedbythefirstcharacter oftheI F S variable,and$ { n a m e [ @ ] } expandseachelementofnametoaseparateword.Whentherearenoarraymembers,$ { n a m e [ @ ] } expandsto nothing.Ifthedoublequotedexpansionoccurswithinaword,theexpansionofthefirstparameterisjoinedwiththebeginningpartoftheoriginal word,andtheexpansionofthelastparameterisjoinedwiththelastpartoftheoriginalword.Thisisanalogoustotheexpansionofthespecial parameters@ and* .$ { # n a m e [ subscript] } expandstothelengthof$ { n a m e [ subscript] } .Ifsubscriptis@ or* ,theexpansionisthenumberof elementsinthearray.Referencinganarrayvariablewithoutasubscriptisequivalenttoreferencingwithasubscriptof0. Anarrayvariableisconsideredsetifasubscripthasbeenassignedavalue.Thenullstringisavalidvalue. Theu n s e t builtinisusedtodestroyarrays.u n s e t name[subscript]destroysthearrayelementatindexsubscript.Caremustbetakentoavoidunwanted sideeffectscausedbyfilenameexpansion.u n s e t name,wherenameisanarray,removestheentirearray.Asubscriptof* or@ alsoremovesthe entirearray. Thed e c l a r e ,l o c a l ,andr e a d o n l y builtinseachacceptaa optiontospecifyanindexedarrayandaA optiontospecifyanassociativearray.Ifboth optionsaresupplied,A takesprecedence.Ther e a d builtinacceptsaa optiontoassignalistofwordsreadfromthestandardinputtoanarray,and canreadvaluesfromthestandardinputintoindividualarrayelements.Thes e t andd e c l a r e builtinsdisplayarrayvaluesinawaythatallowsthemto bereusedasinput. Next:PrintingaPrompt,Previous:Arrays,Up:BashFeatures[Contents][Index]
6.8TheDirectoryStack
DirectoryStackBuiltins: Bashbuiltincommandstomanipulatethedirectorystack. Thedirectorystackisalistofrecentlyvisiteddirectories.Thep u s h d builtinaddsdirectoriestothestackasitchangesthecurrentdirectory,andthe p o p d builtinremovesspecifieddirectoriesfromthestackandchangesthecurrentdirectorytothedirectoryremoved.Thed i r s builtindisplaysthe contentsofthedirectorystack. ThecontentsofthedirectorystackarealsovisibleasthevalueoftheD I R S T A C K shellvariable. Up:TheDirectoryStack[Contents][Index] 6.8.1DirectoryStackBuiltins
d i r s d i r s[ + N|N ][ c l p v ]
DisplaystheNthdirectory(countingfromtheleftofthelistprintedbyd i r s wheninvokedwithoutoptions),startingwithzero.
N
DisplaystheNthdirectory(countingfromtherightofthelistprintedbyd i r s wheninvokedwithoutoptions),startingwithzero.
c
Clearsthedirectorystackbydeletingalloftheelements.
l
Producesalongerlistingthedefaultlistingformatusesatildetodenotethehomedirectory.
p
Causesd i r s toprintthedirectorystackwithoneentryperline.
v
Causesd i r s toprintthedirectorystackwithoneentryperline,prefixingeachentrywithitsindexinthestack.
p o p d p o p d[ + N|N ][ n ]
RemovestheNthdirectory(countingfromtheleftofthelistprintedbyd i r s ),startingwithzero.
N
RemovestheNthdirectory(countingfromtherightofthelistprintedbyd i r s ),startingwithzero.
n
Suppressesthenormalchangeofdirectorywhenremovingdirectoriesfromthestack,sothatonlythestackismanipulated.
p u s h d p u s h d[ n ][ + N|N|d i r]
Suppressesthenormalchangeofdirectorywhenaddingdirectoriestothestack,sothatonlythestackismanipulated.
+ N
BringstheNthdirectory(countingfromtheleftofthelistprintedbyd i r s ,startingwithzero)tothetopofthelistbyrotatingthestack.
N
BringstheNthdirectory(countingfromtherightofthelistprintedbyd i r s ,startingwithzero)tothetopofthelistbyrotatingthestack.
d i r
6.9ControllingthePrompt
ThevalueofthevariableP R O M P T _ C O M M A N D isexaminedjustbeforeBashprintseachprimaryprompt.IfP R O M P T _ C O M M A N D issetandhasanonnull value,thenthevalueisexecutedjustasifithadbeentypedonthecommandline. Inaddition,thefollowingtabledescribesthespecialcharacterswhichcanappearinthepromptvariables:
\ a
Abellcharacter.
\ d
Thedate,in"WeekdayMonthDate"format(e.g.,"TueMay26").
\ D { f o r m a t }
Anescapecharacter.
\ h
Thehostname,uptothefirst..
\ H
Thehostname.
\ j
Thenumberofjobscurrentlymanagedbytheshell.
\ l
Thebasenameoftheshellsterminaldevicename.
\ n
Anewline.
\ r
Acarriagereturn.
\ s
Thenameoftheshell,thebasenameof$ 0 (theportionfollowingthefinalslash).
\ t
Thetime,in24hourHH:MM:SSformat.
\ T
Thetime,in12hourHH:MM:SSformat.
\ @
Thetime,in12houram/pmformat.
\ A
Thetime,in24hourHH:MMformat.
\ u
Theusernameofthecurrentuser.
\ v
TheversionofBash(e.g.,2.00)
\ V
ThereleaseofBash,version+patchlevel(e.g.,2.00.0)
\ w
Thehistorynumberofthiscommand.
\ #
Thecommandnumberofthiscommand.
\ $
Iftheeffectiveuidis0,# ,otherwise$ .
\ n n n
ThecharacterwhoseASCIIcodeistheoctalvaluennn.
\ \
Abackslash.
\ [
Beginasequenceofnonprintingcharacters.Thiscouldbeusedtoembedaterminalcontrolsequenceintotheprompt.
\ ]
6.10TheRestrictedShell
IfBashisstartedwiththenamer b a s h ,orther e s t r i c t e d orr optionissuppliedatinvocation,theshellbecomesrestricted.Arestrictedshellis usedtosetupanenvironmentmorecontrolledthanthestandardshell.Arestrictedshellbehavesidenticallytob a s h withtheexceptionthatthe followingaredisallowedornotperformed: Changingdirectorieswiththec d builtin. SettingorunsettingthevaluesoftheS H E L L ,P A T H ,E N V ,orB A S H _ E N V variables. Specifyingcommandnamescontainingslashes. Specifyingafilenamecontainingaslashasanargumenttothe. builtincommand. Specifyingafilenamecontainingaslashasanargumenttothep optiontotheh a s h builtincommand. Importingfunctiondefinitionsfromtheshellenvironmentatstartup. ParsingthevalueofS H E L L O P T S fromtheshellenvironmentatstartup. Redirectingoutputusingthe> ,> | ,< > ,> & ,& > ,and> > redirectionoperators. Usingthee x e c builtintoreplacetheshellwithanothercommand. Addingordeletingbuiltincommandswiththef andd optionstothee n a b l e builtin. Usingthee n a b l e builtincommandtoenabledisabledshellbuiltins. Specifyingthep optiontothec o m m a n d builtin. Turningoffrestrictedmodewiths e t+ r ors e t+ or e s t r i c t e d . Theserestrictionsareenforcedafteranystartupfilesareread. Whenacommandthatisfoundtobeashellscriptisexecuted(seeShellScripts),r b a s h turnsoffanyrestrictionsintheshellspawnedtoexecutethe script. Previous:TheRestrictedShell,Up:BashFeatures[Contents][Index]
6.11BashPOSIXMode
StartingBashwiththep o s i x commandlineoptionorexecutings e top o s i x whileBashisrunningwillcauseBashtoconformmorecloselyto thePOSIXstandardbychangingthebehaviortomatchthatspecifiedbyPOSIXinareaswheretheBashdefaultdiffers. Wheninvokedass h ,BashentersPOSIXmodeafterreadingthestartupfiles. ThefollowinglistiswhatschangedwhenPOSIXmodeisineffect: 1. Whenacommandinthehashtablenolongerexists,Bashwillresearch$ P A T H tofindthenewlocation.Thisisalsoavailablewiths h o p ts c h e c k h a s h . 2. ThemessageprintedbythejobcontrolcodeandbuiltinswhenajobexitswithanonzerostatusisDone(status). 3. ThemessageprintedbythejobcontrolcodeandbuiltinswhenajobisstoppedisStopped(signame),wheresignameis,forexample,S I G T S T P . 4. Theb g builtinusestherequiredformattodescribeeachjobplacedinthebackground,whichdoesnotincludeanindicationofwhetherthejobis thecurrentorpreviousjob. 5. Reservedwordsappearinginacontextwherereservedwordsarerecognizeddonotundergoaliasexpansion. 6. ThePOSIXP S 1 andP S 2 expansionsof! tothehistorynumberand! ! to! areenabled,andparameterexpansionisperformedonthevalues ofP S 1 andP S 2 regardlessofthesettingofthep r o m p t v a r s option. 7. ThePOSIXstartupfilesareexecuted($ E N V )ratherthanthenormalBashfiles. 8. Tildeexpansionisonlyperformedonassignmentsprecedingacommandname,ratherthanonallassignmentstatementsontheline. 9. Thedefaulthistoryfileis~ / . s h _ h i s t o r y (thisisthedefaultvalueof$ H I S T F I L E ). 10. Theoutputofk i l ll printsallthesignalnamesonasingleline,separatedbyspaces,withouttheS I G prefix. 11. Thek i l l builtindoesnotacceptsignalnameswithaS I G prefix. 12. Noninteractiveshellsexitiffilenamein. filenameisnotfound.
13. Noninteractiveshellsexitifasyntaxerrorinanarithmeticexpansionresultsinaninvalidexpression. 14. Noninteractiveshellsexitifthereisasyntaxerrorinascriptreadwiththe. ors o u r c e builtins,orinastringprocessedbythee v a l builtin. 15. Redirectionoperatorsdonotperformfilenameexpansiononthewordintheredirectionunlesstheshellisinteractive. 16. Redirectionoperatorsdonotperformwordsplittingonthewordintheredirection. 17. Functionnamesmustbevalidshelln a m e s.Thatis,theymaynotcontaincharactersotherthanletters,digits,andunderscores,andmaynotstart withadigit.Declaringafunctionwithaninvalidnamecausesafatalsyntaxerrorinnoninteractiveshells. 18. POSIXspecialbuiltinsarefoundbeforeshellfunctionsduringcommandlookup. 19. Thet i m e reservedwordmaybeusedbyitselfasacommand.Whenusedinthisway,itdisplaystimingstatisticsfortheshellanditscompleted children.TheT I M E F O R M A T variablecontrolstheformatofthetiminginformation. 20. Whenparsingandexpandinga${}expansionthatappearswithindoublequotes,singlequotesarenolongerspecialandcannotbeusedto quoteaclosingbraceorotherspecialcharacter,unlesstheoperatorisoneofthosedefinedtoperformpatternremoval.Inthiscase,theydonot havetoappearasmatchedpairs. 21. Theparserdoesnotrecognizet i m e asareservedwordifthenexttokenbeginswitha. 22. IfaPOSIXspecialbuiltinreturnsanerrorstatus,anoninteractiveshellexits.ThefatalerrorsarethoselistedinthePOSIXstandard,andinclude thingslikepassingincorrectoptions,redirectionerrors,variableassignmenterrorsforassignmentsprecedingthecommandname,andsoon. 23. Anoninteractiveshellexitswithanerrorstatusifavariableassignmenterroroccurswhennocommandnamefollowstheassignmentstatements. Avariableassignmenterroroccurs,forexample,whentryingtoassignavaluetoareadonlyvariable. 24. Anoninteractiveshellexistswithanerrorstatusifavariableassignmenterroroccursinanassignmentstatementprecedingaspecialbuiltin,but notwithanyothersimplecommand. 25. Anoninteractiveshellexitswithanerrorstatusiftheiterationvariableinaf o r statementortheselectionvariableinas e l e c t statementisa readonlyvariable. 26. Processsubstitutionisnotavailable. 27. AssignmentstatementsprecedingPOSIXspecialbuiltinspersistintheshellenvironmentafterthebuiltincompletes. 28. Assignmentstatementsprecedingshellfunctioncallspersistintheshellenvironmentafterthefunctionreturns,asifaPOSIXspecialbuiltin commandhadbeenexecuted. 29. Thee x p o r t andr e a d o n l y builtincommandsdisplaytheiroutputintheformatrequiredbyPOSIX. 30. Thet r a p builtindisplayssignalnameswithouttheleadingS I G . 31. Thet r a p builtindoesntcheckthefirstargumentforapossiblesignalspecificationandrevertthesignalhandlingtotheoriginaldispositionifit is,unlessthatargumentconsistssolelyofdigitsandisavalidsignalnumber.Ifuserswanttoresetthehandlerforagivensignaltotheoriginal disposition,theyshoulduseasthefirstargument. 32. The. ands o u r c e builtinsdonotsearchthecurrentdirectoryforthefilenameargumentifitisnotfoundbysearchingP A T H . 33. Subshellsspawnedtoexecutecommandsubstitutionsinheritthevalueofthee optionfromtheparentshell.WhennotinPOSIXmode,Bash clearsthee optioninsuchsubshells. 34. Aliasexpansionisalwaysenabled,eveninnoninteractiveshells. 35. Whenthea l i a s builtindisplaysaliasdefinitions,itdoesnotdisplaythemwithaleadinga l i a s unlessthep optionissupplied. 36. Whenthes e t builtinisinvokedwithoutoptions,itdoesnotdisplayshellfunctionnamesanddefinitions. 37. Whenthes e t builtinisinvokedwithoutoptions,itdisplaysvariablevalueswithoutquotes,unlesstheycontainshellmetacharacters,evenifthe resultcontainsnonprintingcharacters. 38. Whenthec d builtinisinvokedinlogicalmode,andthepathnameconstructedfrom$ P W D andthedirectorynamesuppliedasanargumentdoes notrefertoanexistingdirectory,c d willfailinsteadoffallingbacktophysicalmode. 39. Thep w d builtinverifiesthatthevalueitprintsisthesameasthecurrentdirectory,evenifitisnotaskedtocheckthefilesystemwiththeP option. 40. Whenlistingthehistory,thef c builtindoesnotincludeanindicationofwhetherornotahistoryentryhasbeenmodified. 41. Thedefaulteditorusedbyf c ise d . 42. Thet y p e andc o m m a n d builtinswillnotreportanonexecutablefileashavingbeenfound,thoughtheshellwillattempttoexecutesuchafileifit istheonlysonamedfilefoundin$ P A T H . 43. Thev i editingmodewillinvokethev i editordirectlywhenthev commandisrun,insteadofchecking$ V I S U A L and$ E D I T O R . 44. Whenthex p g _ e c h o optionisenabled,Bashdoesnotattempttointerpretanyargumentstoe c h o asoptions.Eachargumentisdisplayed,after escapecharactersareconverted. 45. Theu l i m i t builtinusesablocksizeof512bytesforthec andf options. 46. ThearrivalofS I G C H L D whenatrapissetonS I G C H L D doesnotinterruptthew a i t builtinandcauseittoreturnimmediately.Thetrapcommandis runonceforeachchildthatexits. ThereisotherPOSIXbehaviorthatBashdoesnotimplementbydefaultevenwheninPOSIXmode.Specifically: 1. Thef c builtinchecks$ E D I T O R asaprogramtoedithistoryentriesifF C E D I T isunset,ratherthandefaultingdirectlytoe d .f c usese d ifE D I T O R is unset. 2. Asnotedabove,Bashrequiresthex p g _ e c h o optiontobeenabledforthee c h o builtintobefullyconformant. BashcanbeconfiguredtobePOSIXconformantbydefault,byspecifyingthee n a b l e s t r i c t p o s i x d e f a u l t toc o n f i g u r e whenbuilding(see OptionalFeatures). Next:CommandLineEditing,Previous:BashFeatures,Up:Top[Contents][Index]
7JobControl
Thischapterdiscusseswhatjobcontrolis,howitworks,andhowBashallowsyoutoaccessitsfacilities. JobControlBasics: Howjobcontrolworks. JobControlBuiltins: Bashbuiltincommandsusedtointeractwithjobcontrol. JobControlVariables: VariablesBashusestocustomizejobcontrol.
Next:JobControlBuiltins,Up:JobControl[Contents][Index]
7.1JobControlBasics
Jobcontrolreferstotheabilitytoselectivelystop(suspend)theexecutionofprocessesandcontinue(resume)theirexecutionatalaterpoint.Auser typicallyemploysthisfacilityviaaninteractiveinterfacesuppliedjointlybytheoperatingsystemkernelsterminaldriverandBash. Theshellassociatesajobwitheachpipeline.Itkeepsatableofcurrentlyexecutingjobs,whichmaybelistedwiththej o b s command.WhenBash startsajobasynchronously,itprintsalinethatlookslike:
[ 1 ]2 5 6 4 7
indicatingthatthisjobisjobnumber1andthattheprocessIDofthelastprocessinthepipelineassociatedwiththisjobis25647.Alloftheprocessesin asinglepipelinearemembersofthesamejob.Bashusesthejobabstractionasthebasisforjobcontrol. Tofacilitatetheimplementationoftheuserinterfacetojobcontrol,theoperatingsystemmaintainsthenotionofacurrentterminalprocessgroupID. Membersofthisprocessgroup(processeswhoseprocessgroupIDisequaltothecurrentterminalprocessgroupID)receivekeyboardgeneratedsignals suchasS I G I N T .Theseprocessesaresaidtobeintheforeground.BackgroundprocessesarethosewhoseprocessgroupIDdiffersfromtheterminals suchprocessesareimmunetokeyboardgeneratedsignals.Onlyforegroundprocessesareallowedtoreadfromor,iftheusersospecifieswiths t t y t o s t o p ,writetotheterminal.Backgroundprocesseswhichattempttoreadfrom(writetowhens t t yt o s t o p isineffect)theterminalaresenta S I G T T I N (S I G T T O U )signalbythekernelsterminaldriver,which,unlesscaught,suspendstheprocess. IftheoperatingsystemonwhichBashisrunningsupportsjobcontrol,Bashcontainsfacilitiestouseit.Typingthesuspendcharacter(typically^ Z , ControlZ)whileaprocessisrunningcausesthatprocesstobestoppedandreturnscontroltoBash.Typingthedelayedsuspendcharacter(typically ^ Y ,ControlY)causestheprocesstobestoppedwhenitattemptstoreadinputfromtheterminal,andcontroltobereturnedtoBash.Theuserthen manipulatesthestateofthisjob,usingtheb g commandtocontinueitinthebackground,thef g commandtocontinueitintheforeground,orthek i l l commandtokillit.A^ Z takeseffectimmediately,andhastheadditionalsideeffectofcausingpendingoutputandtypeaheadtobediscarded. Thereareanumberofwaystorefertoajobintheshell.Thecharacter% introducesajobspecification(jobspec). Jobnumbern maybereferredtoas% n .Thesymbols% % and% + refertotheshellsnotionofthecurrentjob,whichisthelastjobstoppedwhileit wasintheforegroundorstartedinthebackground.Asingle% (withnoaccompanyingjobspecification)alsoreferstothecurrentjob.Theprevious jobmaybereferencedusing% .Ifthereisonlyasinglejob,% + and% canbothbeusedtorefertothatjob.Inoutputpertainingtojobs(e.g.,the outputofthej o b s command),thecurrentjobisalwaysflaggedwitha+ ,andthepreviousjobwitha. Ajobmayalsobereferredtousingaprefixofthenameusedtostartit,orusingasubstringthatappearsinitscommandline.Forexample,% c e refers toastoppedc e job.Using% ? c e ,ontheotherhand,referstoanyjobcontainingthestringc e initscommandline.Iftheprefixorsubstringmatches morethanonejob,Bashreportsanerror. Simplynamingajobcanbeusedtobringitintotheforeground:% 1 isasynonymforf g% 1 ,bringingjob1fromthebackgroundintothe foreground.Similarly,% 1& resumesjob1inthebackground,equivalenttob g% 1 Theshelllearnsimmediatelywheneverajobchangesstate.Normally,Bashwaitsuntilitisabouttoprintapromptbeforereportingchangesinajobs statussoastonotinterruptanyotheroutput.Iftheb optiontothes e t builtinisenabled,Bashreportssuchchangesimmediately(seeTheSetBuiltin). AnytraponS I G C H L D isexecutedforeachchildprocessthatexits. IfanattempttoexitBashismadewhilejobsarestopped,(orrunning,ifthec h e c k j o b s optionisenabledseeTheShoptBuiltin),theshellprintsa warningmessage,andifthec h e c k j o b s optionisenabled,liststhejobsandtheirstatuses.Thej o b s commandmaythenbeusedtoinspecttheirstatus. Ifasecondattempttoexitismadewithoutaninterveningcommand,Bashdoesnotprintanotherwarning,andanystoppedjobsareterminated. Next:JobControlVariables,Previous:JobControlBasics,Up:JobControl[Contents][Index]
7.2JobControlBuiltins
b g b g[ j o b s p e c ]
Thefirstformliststheactivejobs.Theoptionshavethefollowingmeanings:
ListprocessIDsinadditiontothenormalinformation.
n
Displayinformationonlyaboutjobsthathavechangedstatussincetheuserwaslastnotifiedoftheirstatus.
p
ListonlytheprocessIDofthejobsprocessgroupleader.
r
Restrictoutputtorunningjobs.
s
SendasignalspecifiedbysigspecorsignumtotheprocessnamedbyjobspecificationjobspecorprocessIDpid.sigspeciseitheracase insensitivesignalnamesuchasS I G I N T (withorwithouttheS I G prefix)orasignalnumbersignumisasignalnumber.Ifsigspecandsignumare notpresent,S I G T E R M isused.Thel optionliststhesignalnames.Ifanyargumentsaresuppliedwhenl isgiven,thenamesofthesignals correspondingtotheargumentsarelisted,andthereturnstatusiszero.exit_statusisanumberspecifyingasignalnumberortheexitstatusofa processterminatedbyasignal.Thereturnstatusiszeroifatleastonesignalwassuccessfullysent,ornonzeroifanerroroccursoraninvalid optionisencountered.
w a i t w a i t[ j o b s p e co rp i d. . . ]
Withoutoptions,eachjobspecisremovedfromthetableofactivejobs.Iftheh optionisgiven,thejobisnotremovedfromthetable,butis markedsothatS I G H U P isnotsenttothejobiftheshellreceivesaS I G H U P .Ifjobspecisnotpresent,andneitherthea norr optionissupplied, thecurrentjobisused.Ifnojobspecissupplied,thea optionmeanstoremoveormarkalljobsther optionwithoutajobspecargument restrictsoperationtorunningjobs.
s u s p e n d s u s p e n d[ f ]
7.3JobControlVariables
a u t o _ r e s u m e
Thisvariablecontrolshowtheshellinteractswiththeuserandjobcontrol.Ifthisvariableexiststhensinglewordsimplecommandswithout redirectionsaretreatedascandidatesforresumptionofanexistingjob.Thereisnoambiguityallowedifthereismorethanonejobbeginning withthestringtyped,thenthemostrecentlyaccessedjobwillbeselected.Thenameofastoppedjob,inthiscontext,isthecommandlineusedto startit.Ifthisvariableissettothevaluee x a c t ,thestringsuppliedmustmatchthenameofastoppedjobexactlyifsettos u b s t r i n g ,the stringsuppliedneedstomatchasubstringofthenameofastoppedjob.Thes u b s t r i n g valueprovidesfunctionalityanalogoustothe% ? job ID(seeJobControlBasics).Ifsettoanyothervalue,thesuppliedstringmustbeaprefixofastoppedjobsnamethisprovidesfunctionality analogoustothe% jobID. Next:UsingHistoryInteractively,Previous:JobControl,Up:Top[Contents][Index]
8CommandLineEditing
ThischapterdescribesthebasicfeaturesoftheGNUcommandlineeditinginterface.CommandlineeditingisprovidedbytheReadlinelibrary,whichis usedbyseveraldifferentprograms,includingBash.Commandlineeditingisenabledbydefaultwhenusinganinteractiveshell,unlessthen o e d i t i n g optionissuppliedatshellinvocation.Lineeditingisalsousedwhenusingthee optiontother e a d builtincommand(seeBashBuiltins). Bydefault,thelineeditingcommandsaresimilartothoseofEmacs.Avistylelineeditinginterfaceisalsoavailable.Lineeditingcanbeenabledatany timeusingtheoe m a c s orov i optionstothes e t builtincommand(seeTheSetBuiltin),ordisabledusingthe+ oe m a c s or+ ov i optionstos e t . IntroductionandNotation: Notationusedinthistext. ReadlineInteraction: Theminimumsetofcommandsforeditingaline. ReadlineInitFile: CustomizingReadlinefromausersview. BindableReadlineCommands: AdescriptionofmostoftheReadlinecommandsavailableforbinding ReadlineviMode: AshortdescriptionofhowtomakeReadlinebehavelikethevieditor. ProgrammableCompletion: Howtospecifythepossiblecompletionsforaspecificcommand. ProgrammableCompletionBuiltins: Builtincommandstospecifyhowtocompleteargumentsforaparticularcommand. Next:ReadlineInteraction,Up:CommandLineEditing[Contents][Index]
8.1IntroductiontoLineEditing
Thefollowingparagraphsdescribethenotationusedtorepresentkeystrokes. ThetextC k isreadasControlKanddescribesthecharacterproducedwhenthek keyispressedwhiletheControlkeyisdepressed. ThetextM k isreadasMetaKanddescribesthecharacterproducedwhentheMetakey(ifyouhaveone)isdepressed,andthek keyispressed.The MetakeyislabeledA L T onmanykeyboards.OnkeyboardswithtwokeyslabeledA L T (usuallytoeithersideofthespacebar),theA L T ontheleftside isgenerallysettoworkasaMetakey.TheA L T keyontherightmayalsobeconfiguredtoworkasaMetakeyormaybeconfiguredassomeother modifier,suchasaComposekeyfortypingaccentedcharacters. IfyoudonothaveaMetaorA L T key,oranotherkeyworkingasaMetakey,theidenticalkeystrokecanbegeneratedbytypingE S C first,andthen typingk .Eitherprocessisknownasmetafyingthek key. ThetextM C k isreadasMetaControlkanddescribesthecharacterproducedbymetafyingC k . Inaddition,severalkeyshavetheirownnames.Specifically,D E L ,E S C ,L F D ,S P C ,R E T ,andT A B allstandforthemselveswhenseeninthistext,orinan initfile(seeReadlineInitFile).IfyourkeyboardlacksaL F D key,typingC j willproducethedesiredcharacter.TheR E T keymaybelabeledR e t u r n or E n t e r onsomekeyboards. Next:ReadlineInitFile,Previous:IntroductionandNotation,Up:CommandLineEditing[Contents][Index]
8.2ReadlineInteraction
Oftenduringaninteractivesessionyoutypeinalonglineoftext,onlytonoticethatthefirstwordonthelineismisspelled.TheReadlinelibrarygives youasetofcommandsformanipulatingthetextasyoutypeitin,allowingyoutojustfixyourtypo,andnotforcingyoutoretypethemajorityofthe line.Usingtheseeditingcommands,youmovethecursortotheplacethatneedscorrection,anddeleteorinsertthetextofthecorrections.Then,when youaresatisfiedwiththeline,yousimplypressR E T .YoudonothavetobeattheendofthelinetopressR E T theentirelineisacceptedregardlessof thelocationofthecursorwithintheline. ReadlineBareEssentials: TheleastyouneedtoknowaboutReadline. ReadlineMovementCommands: Movingabouttheinputline. ReadlineKillingCommands: Howtodeletetext,andhowtogetitback! ReadlineArguments: Givingnumericargumentstocommands. Searching: Searchingthroughpreviouslines. Next:ReadlineMovementCommands,Up:ReadlineInteraction[Contents][Index] 8.2.1ReadlineBareEssentials Inordertoentercharactersintotheline,simplytypethem.Thetypedcharacterappearswherethecursorwas,andthenthecursormovesonespaceto theright.Ifyoumistypeacharacter,youcanuseyourerasecharactertobackupanddeletethemistypedcharacter. Sometimesyoumaymistypeacharacter,andnotnoticetheerroruntilyouhavetypedseveralothercharacters.Inthatcase,youcantypeC b tomove thecursortotheleft,andthencorrectyourmistake.Afterwards,youcanmovethecursortotherightwithC f . Whenyouaddtextinthemiddleofaline,youwillnoticethatcharacterstotherightofthecursorarepushedovertomakeroomforthetextthatyou haveinserted.Likewise,whenyoudeletetextbehindthecursor,characterstotherightofthecursorarepulledbacktofillintheblankspacecreated bytheremovalofthetext.Alistofthebareessentialsforeditingthetextofaninputlinefollows.
C b
Movebackonecharacter.
C f
Moveforwardonecharacter.
D E L orB a c k s p a c e
Deletethecharactertotheleftofthecursor.
C d
Undothelasteditingcommand.Youcanundoallthewaybacktoanemptyline. (Dependingonyourconfiguration,theB a c k s p a c e keybesettodeletethecharactertotheleftofthecursorandtheD E L keysettodeletethecharacter underneaththecursor,likeC d ,ratherthanthecharactertotheleftofthecursor.) Next:ReadlineKillingCommands,Previous:ReadlineBareEssentials,Up:ReadlineInteraction[Contents][Index] 8.2.2ReadlineMovementCommands Theabovetabledescribesthemostbasickeystrokesthatyouneedinordertodoeditingoftheinputline.Foryourconvenience,manyothercommands havebeenaddedinadditiontoC b ,C f ,C d ,andD E L .Herearesomecommandsformovingmorerapidlyabouttheline.
C a
Movetothestartoftheline.
C e
Movetotheendoftheline.
M f
Moveforwardaword,whereawordiscomposedoflettersanddigits.
M b
Movebackwardaword.
C l
Clearthescreen,reprintingthecurrentlineatthetop. NoticehowC f movesforwardacharacter,whileM f movesforwardaword.Itisalooseconventionthatcontrolkeystrokesoperateoncharacters whilemetakeystrokesoperateonwords. Next:ReadlineArguments,Previous:ReadlineMovementCommands,Up:ReadlineInteraction[Contents][Index] 8.2.3ReadlineKillingCommands Killingtextmeanstodeletethetextfromtheline,buttosaveitawayforlateruse,usuallybyyanking(reinserting)itbackintotheline.(Cutand pastearemorerecentjargonforkillandyank.) Ifthedescriptionforacommandsaysthatitkillstext,thenyoucanbesurethatyoucangetthetextbackinadifferent(orthesame)placelater. Whenyouuseakillcommand,thetextissavedinakillring.Anynumberofconsecutivekillssaveallofthekilledtexttogether,sothatwhenyou yankitback,yougetitall.Thekillringisnotlinespecificthetextthatyoukilledonapreviouslytypedlineisavailabletobeyankedbacklater,when youaretypinganotherline. Hereisthelistofcommandsforkillingtext.
C k
Killthetextfromthecurrentcursorpositiontotheendoftheline.
M d
Killfromthecursortotheendofthecurrentword,or,ifbetweenwords,totheendofthenextword.Wordboundariesarethesameasthose usedbyM f .
M D E L
Killfromthecursorthestartofthecurrentword,or,ifbetweenwords,tothestartofthepreviousword.Wordboundariesarethesameasthose usedbyM b .
C w
Yankthemostrecentlykilledtextbackintothebufferatthecursor.
M y
Rotatethekillring,andyankthenewtop.YoucanonlydothisifthepriorcommandisC y orM y . Next:Searching,Previous:ReadlineKillingCommands,Up:ReadlineInteraction[Contents][Index] 8.2.4ReadlineArguments YoucanpassnumericargumentstoReadlinecommands.Sometimestheargumentactsasarepeatcount,othertimesitisthesignoftheargumentthat issignificant.Ifyoupassanegativeargumenttoacommandwhichnormallyactsinaforwarddirection,thatcommandwillactinabackwarddirection. Forexample,tokilltextbacktothestartoftheline,youmighttypeM -C k . Thegeneralwaytopassnumericargumentstoacommandistotypemetadigitsbeforethecommand.Ifthefirstdigittypedisaminussign(),then thesignoftheargumentwillbenegative.Onceyouhavetypedonemetadigittogettheargumentstarted,youcantypetheremainderofthedigits,and thenthecommand.Forexample,togivetheC d commandanargumentof10,youcouldtypeM 10C d ,whichwilldeletethenexttencharacters ontheinputline. Previous:ReadlineArguments,Up:ReadlineInteraction[Contents][Index] 8.2.5SearchingforCommandsintheHistory Readlineprovidescommandsforsearchingthroughthecommandhistory(seeBashHistoryFacilities)forlinescontainingaspecifiedstring.Thereare twosearchmodes:incrementalandnonincremental. Incrementalsearchesbeginbeforetheuserhasfinishedtypingthesearchstring.Aseachcharacterofthesearchstringistyped,Readlinedisplaysthe nextentryfromthehistorymatchingthestringtypedsofar.Anincrementalsearchrequiresonlyasmanycharactersasneededtofindthedesired historyentry.Tosearchbackwardinthehistoryforaparticularstring,typeC r .TypingC s searchesforwardthroughthehistory.Thecharacters presentinthevalueofthei s e a r c h t e r m i n a t o r s variableareusedtoterminateanincrementalsearch.Ifthatvariablehasnotbeenassignedavalue, theE S C andC J characterswillterminateanincrementalsearch.C g willabortanincrementalsearchandrestoretheoriginalline.Whenthesearchis terminated,thehistoryentrycontainingthesearchstringbecomesthecurrentline. Tofindothermatchingentriesinthehistorylist,typeC r orC s asappropriate.Thiswillsearchbackwardorforwardinthehistoryforthenextentry matchingthesearchstringtypedsofar.AnyotherkeysequenceboundtoaReadlinecommandwillterminatethesearchandexecutethatcommand. Forinstance,aR E T willterminatethesearchandaccepttheline,therebyexecutingthecommandfromthehistorylist.Amovementcommandwill terminatethesearch,makethelastlinefoundthecurrentline,andbeginediting. Readlineremembersthelastincrementalsearchstring.IftwoC r saretypedwithoutanyinterveningcharactersdefininganewsearchstring,any rememberedsearchstringisused. Nonincrementalsearchesreadtheentiresearchstringbeforestartingtosearchformatchinghistorylines.Thesearchstringmaybetypedbytheuseror bepartofthecontentsofthecurrentline. Next:BindableReadlineCommands,Previous:ReadlineInteraction,Up:CommandLineEditing[Contents][Index]
8.3ReadlineInitFile
AlthoughtheReadlinelibrarycomeswithasetofEmacslikekeybindingsinstalledbydefault,itispossibletouseadifferentsetofkeybindings.Any usercancustomizeprogramsthatuseReadlinebyputtingcommandsinaninputrcfile,conventionallyinhishomedirectory.Thenameofthisfileis takenfromthevalueoftheshellvariableI N P U T R C .Ifthatvariableisunset,thedefaultis~ / . i n p u t r c .Ifthatfiledoesnotexistorcannotberead,the ultimatedefaultis/ e t c / i n p u t r c . WhenaprogramwhichusestheReadlinelibrarystartsup,theinitfileisread,andthekeybindingsareset. Inaddition,theC xC r commandrereadsthisinitfile,thusincorporatinganychangesthatyoumighthavemadetoit. ReadlineInitFileSyntax: Syntaxforthecommandsintheinputrcfile. ConditionalInitConstructs: Conditionalkeybindingsintheinputrcfile.
SampleInitFile:
Anexampleinputrcfile.
Next:ConditionalInitConstructs,Up:ReadlineInitFile[Contents][Index] 8.3.1ReadlineInitFileSyntax ThereareonlyafewbasicconstructsallowedintheReadlineinitfile.Blanklinesareignored.Linesbeginningwitha# arecomments.Lines beginningwitha$ indicateconditionalconstructs(seeConditionalInitConstructs).Otherlinesdenotevariablesettingsandkeybindings. VariableSettings YoucanmodifytheruntimebehaviorofReadlinebyalteringthevaluesofvariablesinReadlineusingthes e t commandwithintheinitfile.The syntaxissimple:
s e tv a r i a b l ev a l u e
Here,forexample,ishowtochangefromthedefaultEmacslikekeybindingtousev i lineeditingcommands:
s e te d i t i n g m o d ev i
Ifsettoo n ,ReadlineattemptstobindthecontrolcharacterstreatedspeciallybythekernelsterminaldrivertotheirReadlineequivalents.
c o m m e n t b e g i n
Thenumberofscreencolumnsusedtodisplaypossiblematcheswhenperformingcompletion.Thevalueisignoredifitislessthan0or greaterthantheterminalscreenwidth.Avalueof0willcausematchestobedisplayedoneperline.Thedefaultvalueis1.
c o m p l e t i o n i g n o r e c a s e
Ifsettoo n ,Readlineperformsfilenamematchingandcompletioninacaseinsensitivefashion.Thedefaultvalueiso f f .
c o m p l e t i o n m a p c a s e
Thelengthincharactersofthecommonprefixofalistofpossiblecompletionsthatisdisplayedwithoutmodification.Whensettoavalue greaterthanzero,commonprefixeslongerthanthisvaluearereplacedwithanellipsiswhendisplayingpossiblecompletions.
c o m p l e t i o n q u e r y i t e m s
Ifsettoo n ,tildeexpansionisperformedwhenReadlineattemptswordcompletion.Thedefaultiso f f .
h i s t o r y p r e s e r v e p o i n t
Setthemaximumnumberofhistoryentriessavedinthehistorylist.Ifsettozero,thenumberofentriesinthehistorylistisnotlimited.
h o r i z o n t a l s c r o l l m o d e
Ifsettoo n ,completeddirectorynameshaveaslashappended.Thedefaultiso n .
m a r k m o d i f i e d l i n e s
Ifsettoo n ,Readlinewilldisplaycharacterswiththeeighthbitsetdirectlyratherthanasametaprefixedescapesequence.Thedefaultis o f f .
p a g e c o m p l e t i o n s
Ifsettoo n ,thisaltersthedefaultcompletionbehaviorwheninsertingasinglematchintotheline.Itsonlyactivewhenperforming completioninthemiddleofaword.Ifenabled,readlinedoesnotinsertcharactersfromthecompletionthatmatchcharactersafterpointin thewordbeingcompleted,soportionsofthewordfollowingthecursorarenotduplicated.Forinstance,ifthisisenabled,attempting completionwhenthecursorisafterthee inM a k e f i l e willresultinM a k e f i l e ratherthanM a k e f i l e f i l e ,assumingthereisasingle possiblecompletion.Thedefaultvalueiso f f .
v i s i b l e s t a t s
Ifsettoo n ,acharacterdenotingafilestypeisappendedtothefilenamewhenlistingpossiblecompletions.Thedefaultiso f f . KeyBindings Thesyntaxforcontrollingkeybindingsintheinitfileissimple.Firstyouneedtofindthenameofthecommandthatyouwanttochange.The followingsectionscontaintablesofthecommandname,thedefaultkeybinding,ifany,andashortdescriptionofwhatthecommanddoes. Onceyouknowthenameofthecommand,simplyplaceonalineintheinitfilethenameofthekeyyouwishtobindthecommandto,acolon, andthenthenameofthecommand.Therecanbenospacebetweenthekeynameandthecolonthatwillbeinterpretedaspartofthekeyname. Thenameofthekeycanbeexpressedindifferentways,dependingonwhatyoufindmostcomfortable. Inadditiontocommandnames,readlineallowskeystobeboundtoastringthatisinsertedwhenthekeyispressed(amacro). Theb i n dp commanddisplaysReadlinefunctionnamesandbindingsinaformatthatcanputdirectlyintoaninitializationfile.SeeBash Builtins. keyname:functionnameormacro keynameisthenameofakeyspelledoutinEnglish.Forexample:
C o n t r o l u :u n i v e r s a l a r g u m e n t M e t a R u b o u t :b a c k w a r d k i l l w o r d C o n t r o l o :" >o u t p u t "
Intheaboveexample,C u isboundtothefunctionu n i v e r s a l a r g u m e n t ,M D E L isboundtothefunctionb a c k w a r d k i l l w o r d ,andC o isboundtorunthemacroexpressedontherighthandside(thatis,toinsertthetext> o u t p u t intotheline). Anumberofsymboliccharacternamesarerecognizedwhileprocessingthiskeybindingsyntax:DEL,ESC,ESCAPE,LFD,NEWLINE, RET,RETURN,RUBOUT,SPACE,SPC,andTAB. "keyseq":functionnameormacro keyseqdiffersfromkeynameaboveinthatstringsdenotinganentirekeysequencecanbespecified,byplacingthekeysequenceindouble quotes.SomeGNUEmacsstylekeyescapescanbeused,asinthefollowingexample,butthespecialcharacternamesarenotrecognized.
" \ C u " :u n i v e r s a l a r g u m e n t " \ C x \ C r " :r e r e a d i n i t f i l e " \ e [ 1 1 ~ " :" F u n c t i o nK e y1 "
\ C -
controlprefix
\ M -
metaprefix
\ e
anescapecharacter
\ \
backslash
\ " " ,adoublequotationmark \ ' ' ,asinglequoteorapostrophe
InadditiontotheGNUEmacsstyleescapesequences,asecondsetofbackslashescapesisavailable:
\ a
alert(bell)
\ b
backspace
\ d
delete
\ f
formfeed
\ n
newline
\ r
carriagereturn
\ t
horizontaltab
\ v
verticaltab
\ n n n
theeightbitcharacterwhosevalueistheoctalvaluennn(onetothreedigits)
\ x H H
Thiscommand,asseeninthepreviousexample,terminatesan$ i f command.
$ e l s e
Commandsinthisbranchofthe$ i f directiveareexecutedifthetestfails.
$ i n c l u d e
Thisdirectivetakesasinglefilenameasanargumentandreadscommandsandbindingsfromthatfile.Forexample,thefollowingdirectivereads from/ e t c / i n p u t r c :
$ i n c l u d e/ e t c / i n p u t r c
# " \ M \ C O D " : b a c k w a r d c h a r # " \ M \ C O C " : f o r w a r d c h a r # " \ M \ C O A " : p r e v i o u s h i s t o r y # " \ M \ C O B " : n e x t h i s t o r y # #A r r o wk e y si n8b i tA N S Im o d e # # " \ M \ C [ D " : b a c k w a r d c h a r # " \ M \ C [ C " : f o r w a r d c h a r # " \ M \ C [ A " : p r e v i o u s h i s t o r y # " \ M \ C [ B " : n e x t h i s t o r y C q :q u o t e d i n s e r t $ e n d i f #A no l d s t y l eb i n d i n g . T h i sh a p p e n st ob et h ed e f a u l t . T A B :c o m p l e t e #M a c r o st h a ta r ec o n v e n i e n tf o rs h e l li n t e r a c t i o n $ i fB a s h #e d i tt h ep a t h " \ C x p " :" P A T H = $ { P A T H } \ e \ C e \ C a \ e f \ C f " #p r e p a r et ot y p eaq u o t e dw o r d#i n s e r to p e na n dc l o s ed o u b l eq u o t e s #a n dm o v et oj u s ta f t e rt h eo p e nq u o t e " \ C x \ " " :" \ " \ " \ C b " #i n s e r tab a c k s l a s h( t e s t i n gb a c k s l a s he s c a p e s #i ns e q u e n c e sa n dm a c r o s ) " \ C x \ \ " :" \ \ " #Q u o t et h ec u r r e n to rp r e v i o u sw o r d " \ C x q " :" \ e b \ " \ e f \ " " #A d dab i n d i n gt or e f r e s ht h el i n e ,w h i c hi su n b o u n d " \ C x r " :r e d r a w c u r r e n t l i n e #E d i tv a r i a b l eo nc u r r e n tl i n e . " \ M \ C v " :" \ C a \ C k $ \ C y \ M \ C e \ C a \ C y = " $ e n d i f #u s eav i s i b l eb e l li fo n ei sa v a i l a b l e s e tb e l l s t y l ev i s i b l e #d o n ' ts t r i pc h a r a c t e r st o7b i t sw h e nr e a d i n g s e ti n p u t m e t ao n #a l l o wi s o l a t i n 1c h a r a c t e r st ob ei n s e r t e dr a t h e r #t h a nc o n v e r t e dt op r e f i x m e t as e q u e n c e s s e tc o n v e r t m e t ao f f #d i s p l a yc h a r a c t e r sw i t ht h ee i g h t hb i ts e td i r e c t l y #r a t h e rt h a na sm e t a p r e f i x e dc h a r a c t e r s s e to u t p u t m e t ao n #i ft h e r ea r em o r et h a n1 5 0p o s s i b l ec o m p l e t i o n sf o r #aw o r d ,a s kt h eu s e ri fh ew a n t st os e ea l lo ft h e m s e tc o m p l e t i o n q u e r y i t e m s1 5 0 #F o rF T P $ i fF t p " \ C x g " :" g e t\ M ? " " \ C x t " :" p u t\ M ? " " \ M . " :y a n k l a s t a r g $ e n d i f
Next:ReadlineviMode,Previous:ReadlineInitFile,Up:CommandLineEditing[Contents][Index]
8.4BindableReadlineCommands
CommandsForMoving: Movingabouttheline. CommandsForHistory: Gettingatpreviouslines. CommandsForText: Commandsforchangingtext. CommandsForKilling: Commandsforkillingandyanking. NumericArguments: Specifyingnumericarguments,repeatcounts. CommandsForCompletion: GettingReadlinetodothetypingforyou. KeyboardMacros: Savingandreexecutingtypedcharacters MiscellaneousCommands: Othermiscellaneouscommands. ThissectiondescribesReadlinecommandsthatmaybeboundtokeysequences.Youcanlistyourkeybindingsbyexecutingb i n dP or,foramore terseformat,suitableforaninputrcfile,b i n dp .(SeeBashBuiltins.)Commandnameswithoutanaccompanyingkeysequenceareunboundby default. Inthefollowingdescriptions,pointreferstothecurrentcursorposition,andmarkreferstoacursorpositionsavedbythes e t m a r k command.Thetext betweenthepointandmarkisreferredtoastheregion. Next:CommandsForHistory,Up:BindableReadlineCommands[Contents][Index]
8.4.1CommandsForMoving
b e g i n n i n g o f l i n e( C a )
Movetothestartofthecurrentline.
e n d o f l i n e( C e )
Movetotheendoftheline.
f o r w a r d c h a r( C f )
Moveforwardacharacter.
b a c k w a r d c h a r( C b )
Movebackacharacter.
f o r w a r d w o r d( M f )
Moveforwardtotheendofthenextword.Wordsarecomposedoflettersanddigits.
b a c k w a r d w o r d( M b )
Movebacktothestartofthecurrentorpreviousword.Wordsarecomposedoflettersanddigits.
s h e l l f o r w a r d w o r d( )
Moveforwardtotheendofthenextword.Wordsaredelimitedbynonquotedshellmetacharacters.
s h e l l b a c k w a r d w o r d( )
Movebacktothestartofthecurrentorpreviousword.Wordsaredelimitedbynonquotedshellmetacharacters.
c l e a r s c r e e n( C l )
Clearthescreenandredrawthecurrentline,leavingthecurrentlineatthetopofthescreen.
r e d r a w c u r r e n t l i n e( )
Movebackthroughthehistorylist,fetchingthepreviouscommand.
n e x t h i s t o r y( C n )
Moveforwardthroughthehistorylist,fetchingthenextcommand.
b e g i n n i n g o f h i s t o r y( M < )
Movetothefirstlineinthehistory.
e n d o f h i s t o r y( M > )
Movetotheendoftheinputhistory,i.e.,thelinecurrentlybeingentered.
r e v e r s e s e a r c h h i s t o r y( C r )
Searchbackwardstartingatthecurrentlineandmovingupthroughthehistoryasnecessary.Thisisanincrementalsearch.
f o r w a r d s e a r c h h i s t o r y( C s )
Searchforwardstartingatthecurrentlineandmovingdownthroughthethehistoryasnecessary.Thisisanincrementalsearch.
n o n i n c r e m e n t a l r e v e r s e s e a r c h h i s t o r y( M p )
Searchbackwardstartingatthecurrentlineandmovingupthroughthehistoryasnecessaryusinganonincrementalsearchforastringsupplied bytheuser.
n o n i n c r e m e n t a l f o r w a r d s e a r c h h i s t o r y( M n )
Searchforwardstartingatthecurrentlineandmovingdownthroughthethehistoryasnecessaryusinganonincrementalsearchforastring suppliedbytheuser.
h i s t o r y s e a r c h f o r w a r d( )
Searchforwardthroughthehistoryforthestringofcharactersbetweenthestartofthecurrentlineandthepoint.Thisisanonincrementalsearch. Bydefault,thiscommandisunbound.
h i s t o r y s e a r c h b a c k w a r d( )
Searchbackwardthroughthehistoryforthestringofcharactersbetweenthestartofthecurrentlineandthepoint.Thisisanonincremental search.Bydefault,thiscommandisunbound.
y a n k n t h a r g( M C y )
Deletethecharacterbehindthecursor.Anumericargumentmeanstokillthecharactersinsteadofdeletingthem.
f o r w a r d b a c k w a r d d e l e t e c h a r( )
Deletethecharacterunderthecursor,unlessthecursorisattheendoftheline,inwhichcasethecharacterbehindthecursorisdeleted.By default,thisisnotboundtoakey.
q u o t e d i n s e r t( C qo rC v )
Addthenextcharactertypedtothelineverbatim.ThisishowtoinsertkeysequenceslikeC q ,forexample.
s e l f i n s e r t( a ,b ,A ,1 ,! , )
Insertyourself.
t r a n s p o s e c h a r s( C t )
Dragthecharacterbeforethecursorforwardoverthecharacteratthecursor,movingthecursorforwardaswell.Iftheinsertionpointisattheend oftheline,thenthistransposesthelasttwocharactersoftheline.Negativeargumentshavenoeffect.
t r a n s p o s e w o r d s( M t )
Dragthewordbeforepointpastthewordafterpoint,movingpointpastthatwordaswell.Iftheinsertionpointisattheendoftheline,this transposesthelasttwowordsontheline.
u p c a s e w o r d( M u )
Uppercasethecurrent(orfollowing)word.Withanegativeargument,uppercasethepreviousword,butdonotmovethecursor.
d o w n c a s e w o r d( M l )
Lowercasethecurrent(orfollowing)word.Withanegativeargument,lowercasethepreviousword,butdonotmovethecursor.
c a p i t a l i z e w o r d( M c )
Capitalizethecurrent(orfollowing)word.Withanegativeargument,capitalizethepreviousword,butdonotmovethecursor.
o v e r w r i t e m o d e( )
Killthetextfrompointtotheendoftheline.
b a c k w a r d k i l l l i n e( C xR u b o u t )
Killbackwardtothebeginningoftheline.
u n i x l i n e d i s c a r d( C u )
Killbackwardfromthecursortothebeginningofthecurrentline.
k i l l w h o l e l i n e( )
Killallcharactersonthecurrentline,nomatterwherepointis.Bydefault,thisisunbound.
k i l l w o r d( M d )
Killfrompointtotheendofthecurrentword,orifbetweenwords,totheendofthenextword.Wordboundariesarethesameasf o r w a r d w o r d .
b a c k w a r d k i l l w o r d( M D E L )
Killthewordbehindpoint.Wordboundariesarethesameasb a c k w a r d w o r d .
s h e l l k i l l w o r d( )
Killfrompointtotheendofthecurrentword,orifbetweenwords,totheendofthenextword.Wordboundariesarethesameass h e l l f o r w a r d w o r d .
s h e l l b a c k w a r d k i l l w o r d( )
Killthewordbehindpoint.Wordboundariesarethesameass h e l l b a c k w a r d w o r d .
u n i x w o r d r u b o u t( C w )
Killthewordbehindpoint,usingwhitespaceasawordboundary.Thekilledtextissavedonthekillring.
u n i x f i l e n a m e r u b o u t( )
Killthewordbehindpoint,usingwhitespaceandtheslashcharacterasthewordboundaries.Thekilledtextissavedonthekillring.
d e l e t e h o r i z o n t a l s p a c e( )
Deleteallspacesandtabsaroundpoint.Bydefault,thisisunbound.
k i l l r e g i o n( )
Killthetextinthecurrentregion.Bydefault,thiscommandisunbound.
c o p y r e g i o n a s k i l l( )
Copythetextintheregiontothekillbuffer,soitcanbeyankedrightaway.Bydefault,thiscommandisunbound.
c o p y b a c k w a r d w o r d( )
Copythewordbeforepointtothekillbuffer.Thewordboundariesarethesameasb a c k w a r d w o r d .Bydefault,thiscommandisunbound.
c o p y f o r w a r d w o r d( )
Copythewordfollowingpointtothekillbuffer.Thewordboundariesarethesameasf o r w a r d w o r d .Bydefault,thiscommandisunbound.
y a n k( C y )
Yankthetopofthekillringintothebufferatpoint.
y a n k p o p( M y )
Rotatethekillring,andyankthenewtop.Youcanonlydothisifthepriorcommandisy a n k ory a n k p o p .
Next:CommandsForCompletion,Previous:CommandsForKilling,Up:BindableReadlineCommands[Contents][Index] 8.4.5SpecifyingNumericArguments
d i g i t a r g u m e n t( M 0 ,M 1 ,M )
Addthisdigittotheargumentalreadyaccumulating,orstartanewargument.M startsanegativeargument.
u n i v e r s a l a r g u m e n t( )
Insertallcompletionsofthetextbeforepointthatwouldhavebeengeneratedbyp o s s i b l e c o m p l e t i o n s .
m e n u c o m p l e t e( )
Attemptfilenamecompletiononthetextbeforepoint.
p o s s i b l e f i l e n a m e c o m p l e t i o n s( C x/ )
Listthepossiblecompletionsofthetextbeforepoint,treatingitasafilename.
c o m p l e t e u s e r n a m e( M ~ )
Attemptcompletiononthetextbeforepoint,treatingitasausername.
p o s s i b l e u s e r n a m e c o m p l e t i o n s( C x~ )
Listthepossiblecompletionsofthetextbeforepoint,treatingitasausername.
c o m p l e t e v a r i a b l e( M $ )
Attemptcompletiononthetextbeforepoint,treatingitasashellvariable.
p o s s i b l e v a r i a b l e c o m p l e t i o n s( C x$ )
Listthepossiblecompletionsofthetextbeforepoint,treatingitasashellvariable.
c o m p l e t e h o s t n a m e( M @ )
Attemptcompletiononthetextbeforepoint,treatingitasahostname.
p o s s i b l e h o s t n a m e c o m p l e t i o n s( C x@ )
Listthepossiblecompletionsofthetextbeforepoint,treatingitasahostname.
c o m p l e t e c o m m a n d( M ! )
Attemptcompletiononthetextbeforepoint,treatingitasacommandname.Commandcompletionattemptstomatchthetextagainstaliases, reservedwords,shellfunctions,shellbuiltins,andfinallyexecutablefilenames,inthatorder.
p o s s i b l e c o m m a n d c o m p l e t i o n s( C x! )
Listthepossiblecompletionsofthetextbeforepoint,treatingitasacommandname.
d y n a m i c c o m p l e t e h i s t o r y( M T A B )
Attemptcompletiononthetextbeforepoint,comparingthetextagainstlinesfromthehistorylistforpossiblecompletionmatches.
d a b b r e v e x p a n d( )
Attemptmenucompletiononthetextbeforepoint,comparingthetextagainstlinesfromthehistorylistforpossiblecompletionmatches.
c o m p l e t e i n t o b r a c e s( M { )
Beginsavingthecharacterstypedintothecurrentkeyboardmacro.
e n d k b d m a c r o( C x) )
Stopsavingthecharacterstypedintothecurrentkeyboardmacroandsavethedefinition.
c a l l l a s t k b d m a c r o( C xe )
Readinthecontentsoftheinputrcfile,andincorporateanybindingsorvariableassignmentsfoundthere.
a b o r t( C g )
Abortthecurrenteditingcommandandringtheterminalsbell(subjecttothesettingofb e l l s t y l e ).
d o u p p e r c a s e v e r s i o n( M a ,M b ,M x , )
Ifthemetafiedcharacterxislowercase,runthecommandthatisboundtothecorrespondinguppercasecharacter.
p r e f i x m e t a( E S C )
Metafythenextcharactertyped.Thisisforkeyboardswithoutametakey.TypingE S Cf isequivalenttotypingM f .
u n d o( C _o rC xC u )
Incrementalundo,separatelyrememberedforeachline.
r e v e r t l i n e( M r )
Undoallchangesmadetothisline.Thisislikeexecutingtheu n d o commandenoughtimestogetbacktothebeginning.
t i l d e e x p a n d( M & )
Performtildeexpansiononthecurrentword.
s e t m a r k( C @ )
Setthemarktothepoint.Ifanumericargumentissupplied,themarkissettothatposition.
e x c h a n g e p o i n t a n d m a r k( C xC x )
Swapthepointwiththemark.Thecurrentcursorpositionissettothesavedposition,andtheoldcursorpositionissavedasthemark.
c h a r a c t e r s e a r c h( C ] )
Acharacterisreadandpointismovedtothenextoccurrenceofthatcharacter.Anegativecountsearchesforpreviousoccurrences.
c h a r a c t e r s e a r c h b a c k w a r d( M C ] )
Acharacterisreadandpointismovedtothepreviousoccurrenceofthatcharacter.Anegativecountsearchesforsubsequentoccurrences.
s k i p c s i s e q u e n c e( )
PrintallofthefunctionsandtheirkeybindingstotheReadlineoutputstream.Ifanumericargumentissupplied,theoutputisformattedinsucha waythatitcanbemadepartofaninputrcfile.Thiscommandisunboundbydefault.
d u m p v a r i a b l e s( )
PrintallofthesettablevariablesandtheirvaluestotheReadlineoutputstream.Ifanumericargumentissupplied,theoutputisformattedinsuch awaythatitcanbemadepartofaninputrcfile.Thiscommandisunboundbydefault.
d u m p m a c r o s( )
PrintalloftheReadlinekeysequencesboundtomacrosandthestringstheyoutput.Ifanumericargumentissupplied,theoutputisformattedin suchawaythatitcanbemadepartofaninputrcfile.Thiscommandisunboundbydefault.
g l o b c o m p l e t e w o r d( M g )
Thewordbeforepointistreatedasapatternforpathnameexpansion,withanasteriskimplicitlyappended.Thispatternisusedtogeneratealist ofmatchingfilenamesforpossiblecompletions.
g l o b e x p a n d w o r d( C x* )
DisplayversioninformationaboutthecurrentinstanceofBash.
s h e l l e x p a n d l i n e( M C e )
Expandthelineastheshelldoes.Thisperformsaliasandhistoryexpansionaswellasalloftheshellwordexpansions(seeShellExpansions).
h i s t o r y e x p a n d l i n e( M ^ )
Performhistoryexpansiononthecurrentline.
m a g i c s p a c e( )
Performhistoryexpansiononthecurrentlineandinsertaspace(seeHistoryInteraction).
a l i a s e x p a n d l i n e( )
Performaliasexpansiononthecurrentline(seeAliases).
h i s t o r y a n d a l i a s e x p a n d l i n e( )
Performhistoryandaliasexpansiononthecurrentline.
i n s e r t l a s t a r g u m e n t( M .o rM _ )
Asynonymfory a n k l a s t a r g .
o p e r a t e a n d g e t n e x t( C o )
Acceptthecurrentlineforexecutionandfetchthenextlinerelativetothecurrentlinefromthehistoryforediting.Anyargumentisignored.
e d i t a n d e x e c u t e c o m m a n d( C x C e )
8.5ReadlineviMode
WhiletheReadlinelibrarydoesnothaveafullsetofv i editingfunctions,itdoescontainenoughtoallowsimpleeditingoftheline.TheReadlinev i modebehavesasspecifiedinthePOSIXstandard. Inordertoswitchinteractivelybetweene m a c s andv i editingmodes,usethes e toe m a c s ands e tov i commands(seeTheSetBuiltin).The Readlinedefaultise m a c s mode. Whenyouenteralineinv i mode,youarealreadyplacedininsertionmode,asifyouhadtypedani .PressingE S C switchesyouintocommand mode,whereyoucaneditthetextofthelinewiththestandardv i movementkeys,movetoprevioushistorylineswithk andsubsequentlineswith j ,andsoforth. Next:ProgrammableCompletionBuiltins,Previous:ReadlineviMode,Up:CommandLineEditing[Contents][Index]
8.6ProgrammableCompletion
Whenwordcompletionisattemptedforanargumenttoacommandforwhichacompletionspecification(acompspec)hasbeendefinedusingthe c o m p l e t e builtin(seeProgrammableCompletionBuiltins),theprogrammablecompletionfacilitiesareinvoked. First,thecommandnameisidentified.Ifacompspechasbeendefinedforthatcommand,thecompspecisusedtogeneratethelistofpossible completionsfortheword.Ifthecommandwordistheemptystring(completionattemptedatthebeginningofanemptyline),anycompspecdefined withtheE optiontoc o m p l e t e isused.Ifthecommandwordisafullpathname,acompspecforthefullpathnameissearchedforfirst.Ifnocompspec isfoundforthefullpathname,anattemptismadetofindacompspecfortheportionfollowingthefinalslash.Ifthosesearchesdonotresultina compspec,anycompspecdefinedwiththeD optiontoc o m p l e t e isusedasthedefault. Onceacompspechasbeenfound,itisusedtogeneratethelistofmatchingwords.Ifacompspecisnotfound,thedefaultBashcompletiondescribed above(seeCommandsForCompletion)isperformed. First,theactionsspecifiedbythecompspecareused.Onlymatcheswhichareprefixedbythewordbeingcompletedarereturned.Whenthef ord optionisusedforfilenameordirectorynamecompletion,theshellvariableF I G N O R E isusedtofilterthematches.SeeBashVariables,foradescription ofF I G N O R E . AnycompletionsspecifiedbyafilenameexpansionpatterntotheG optionaregeneratednext.Thewordsgeneratedbythepatternneednotmatchthe wordbeingcompleted.TheG L O B I G N O R E shellvariableisnotusedtofilterthematches,buttheF I G N O R E shellvariableisused. Next,thestringspecifiedastheargumenttotheW optionisconsidered.ThestringisfirstsplitusingthecharactersintheI F S specialvariableas delimiters.Shellquotingishonored.Eachwordisthenexpandedusingbraceexpansion,tildeexpansion,parameterandvariableexpansion,command substitution,andarithmeticexpansion,asdescribedabove(seeShellExpansions).Theresultsaresplitusingtherulesdescribedabove(seeWord Splitting).Theresultsoftheexpansionareprefixmatchedagainstthewordbeingcompleted,andthematchingwordsbecomethepossiblecompletions. Afterthesematcheshavebeengenerated,anyshellfunctionorcommandspecifiedwiththeF andC optionsisinvoked.Whenthecommandor functionisinvoked,theC O M P _ L I N E ,C O M P _ P O I N T ,C O M P _ K E Y ,andC O M P _ T Y P E variablesareassignedvaluesasdescribedabove(seeBashVariables).If ashellfunctionisbeinginvoked,theC O M P _ W O R D S andC O M P _ C W O R D variablesarealsoset.Whenthefunctionorcommandisinvoked,thefirstargument isthenameofthecommandwhoseargumentsarebeingcompleted,thesecondargumentisthewordbeingcompleted,andthethirdargumentisthe wordprecedingthewordbeingcompletedonthecurrentcommandline.Nofilteringofthegeneratedcompletionsagainstthewordbeingcompletedis performedthefunctionorcommandhascompletefreedomingeneratingthematches. AnyfunctionspecifiedwithF isinvokedfirst.Thefunctionmayuseanyoftheshellfacilities,includingthec o m p g e n andc o m p o p t builtinsdescribed below(seeProgrammableCompletionBuiltins),togeneratethematches.ItmustputthepossiblecompletionsintheC O M P R E P L Y arrayvariable. Next,anycommandspecifiedwiththeC optionisinvokedinanenvironmentequivalenttocommandsubstitution.Itshouldprintalistofcompletions, oneperline,tothestandardoutput.Backslashmaybeusedtoescapeanewline,ifnecessary. Afterallofthepossiblecompletionsaregenerated,anyfilterspecifiedwiththeX optionisappliedtothelist.Thefilterisapatternasusedfor pathnameexpansiona& inthepatternisreplacedwiththetextofthewordbeingcompleted.Aliteral& maybeescapedwithabackslashthe backslashisremovedbeforeattemptingamatch.Anycompletionthatmatchesthepatternwillberemovedfromthelist.Aleading! negatesthe patterninthiscaseanycompletionnotmatchingthepatternwillberemoved. Finally,anyprefixandsuffixspecifiedwiththeP andS optionsareaddedtoeachmemberofthecompletionlist,andtheresultisreturnedtothe Readlinecompletioncodeasthelistofpossiblecompletions. Ifthepreviouslyappliedactionsdonotgenerateanymatches,andtheod i r n a m e s optionwassuppliedtoc o m p l e t e whenthecompspecwas defined,directorynamecompletionisattempted.
Iftheop l u s d i r s optionwassuppliedtoc o m p l e t e whenthecompspecwasdefined,directorynamecompletionisattemptedandanymatchesare addedtotheresultsoftheotheractions. Bydefault,ifacompspecisfound,whateveritgeneratesisreturnedtothecompletioncodeasthefullsetofpossiblecompletions.ThedefaultBash completionsarenotattempted,andtheReadlinedefaultoffilenamecompletionisdisabled.Iftheob a s h d e f a u l t optionwassuppliedtoc o m p l e t e whenthecompspecwasdefined,thedefaultBashcompletionsareattemptedifthecompspecgeneratesnomatches.Iftheod e f a u l t optionwas suppliedtoc o m p l e t e whenthecompspecwasdefined,Readlinesdefaultcompletionwillbeperformedifthecompspec(and,ifattempted,thedefault Bashcompletions)generatenomatches. Whenacompspecindicatesthatdirectorynamecompletionisdesired,theprogrammablecompletionfunctionsforceReadlinetoappendaslashto completednameswhicharesymboliclinkstodirectories,subjecttothevalueofthemarkdirectoriesReadlinevariable,regardlessofthesettingofthe marksymlinkeddirectoriesReadlinevariable. Thereissomesupportfordynamicallymodifyingcompletions.ThisismostusefulwhenusedincombinationwithadefaultcompletionspecifiedwithD .Itspossibleforshellfunctionsexecutedascompletionhandlerstoindicatethatcompletionshouldberetriedbyreturninganexitstatusof124.Ifa shellfunctionreturns124,andchangesthecompspecassociatedwiththecommandonwhichcompletionisbeingattempted(suppliedasthefirst argumentwhenthefunctionisexecuted),programmablecompletionrestartsfromthebeginning,withanattempttofindanewcompspecforthat command.Thisallowsasetofcompletionstobebuiltdynamicallyascompletionisattempted,ratherthanbeingloadedallatonce. Forinstance,assumingthatthereisalibraryofcompspecs,eachkeptinafilecorrespondingtothenameofthecommand,thefollowingdefault completionfunctionwouldloadcompletionsdynamically:
_ c o m p l e t i o n _ l o a d e r ( ) { ." / e t c / b a s h _ c o m p l e t i o n . d / $ 1 . s h "> / d e v / n u l l2 > & 1& &r e t u r n1 2 4 } c o m p l e t eDF_ c o m p l e t i o n _ l o a d e r
Previous:ProgrammableCompletion,Up:CommandLineEditing[Contents][Index]
8.7ProgrammableCompletionBuiltins
Twobuiltincommandsareavailabletomanipulatetheprogrammablecompletionfacilities.
c o m p g e n c o m p g e n[ o p t i o n ][ w o r d ]
Generatepossiblecompletionmatchesforwordaccordingtotheoptions,whichmaybeanyoptionacceptedbythec o m p l e t e builtinwiththe exceptionofp andr ,andwritethematchestothestandardoutput.WhenusingtheF orC options,thevariousshellvariablessetbythe programmablecompletionfacilities,whileavailable,willnothaveusefulvalues. Thematcheswillbegeneratedinthesamewayasiftheprogrammablecompletioncodehadgeneratedthemdirectlyfromacompletion specificationwiththesameflags.Ifwordisspecified,onlythosecompletionsmatchingwordwillbedisplayed. Thereturnvalueistrueunlessaninvalidoptionissupplied,ornomatchesweregenerated.
c o m p l e t e c o m p l e t e[ a b c d e f g j k s u v ][ oc o m p o p t i o n ][ D E ][ Aa c t i o n ][ Gg l o b p a t ][ Ww o r d l i s t ] [ Ff u n c t i o n ][ Cc o m m a n d ][ Xf i l t e r p a t ] [ Pp r e f i x ][ Ss u f f i x ]n a m e[ n a m e ] c o m p l e t ep r[ D E ][ n a m e ]
Specifyhowargumentstoeachnameshouldbecompleted.Ifthep optionissupplied,orifnooptionsaresupplied,existingcompletion specificationsareprintedinawaythatallowsthemtobereusedasinput.Ther optionremovesacompletionspecificationforeachname,or,if nonamesaresupplied,allcompletionspecifications.TheD optionindicatesthattheremainingoptionsandactionsshouldapplytothedefault commandcompletionthatis,completionattemptedonacommandforwhichnocompletionhaspreviouslybeendefined.TheE option indicatesthattheremainingoptionsandactionsshouldapplytoemptycommandcompletionthatis,completionattemptedonablankline. Theprocessofapplyingthesecompletionspecificationswhenwordcompletionisattemptedisdescribedabove(seeProgrammableCompletion). TheD optiontakesprecedenceoverE . Otheroptions,ifspecified,havethefollowingmeanings.TheargumentstotheG ,W ,andX options(and,ifnecessary,theP andS options) shouldbequotedtoprotectthemfromexpansionbeforethec o m p l e t e builtinisinvoked.
oc o m p o p t i o n
Thecompoptioncontrolsseveralaspectsofthecompspecsbehaviorbeyondthesimplegenerationofcompletions.compoptionmaybe oneof:
b a s h d e f a u l t
PerformtherestofthedefaultBashcompletionsifthecompspecgeneratesnomatches.
d e f a u l t
UseReadlinesdefaultfilenamecompletionifthecompspecgeneratesnomatches.
d i r n a m e s
Performdirectorynamecompletionifthecompspecgeneratesnomatches.
f i l e n a m e s
TellReadlinenottoappendaspace(thedefault)towordscompletedattheendoftheline.
p l u s d i r s
Afteranymatchesdefinedbythecompspecaregenerated,directorynamecompletionisattemptedandanymatchesareaddedtothe resultsoftheotheractions.
Aa c t i o n
Theactionmaybeoneofthefollowingtogeneratealistofpossiblecompletions:
a l i a s
Aliasnames.Mayalsobespecifiedasa .
a r r a y v a r
Arrayvariablenames.
b i n d i n g
Readlinekeybindingnames(seeBindableReadlineCommands).
b u i l t i n
Namesofshellbuiltincommands.Mayalsobespecifiedasb .
c o m m a n d
Commandnames.Mayalsobespecifiedasc .
d i r e c t o r y
Directorynames.Mayalsobespecifiedasd .
d i s a b l e d
Namesofdisabledshellbuiltins.
e n a b l e d
Namesofenabledshellbuiltins.
e x p o r t
Namesofexportedshellvariables.Mayalsobespecifiedase .
f i l e
Filenames.Mayalsobespecifiedasf .
f u n c t i o n
Namesofshellfunctions.
g r o u p
Groupnames.Mayalsobespecifiedasg .
h e l p t o p i c
Helptopicsasacceptedbytheh e l p builtin(seeBashBuiltins).
h o s t n a m e
Hostnames,astakenfromthefilespecifiedbytheH O S T F I L E shellvariable(seeBashVariables).
j o b
Jobnames,ifjobcontrolisactive.Mayalsobespecifiedasj .
k e y w o r d
Shellreservedwords.Mayalsobespecifiedask .
r u n n i n g
Namesofrunningjobs,ifjobcontrolisactive.
s e r v i c e
Servicenames.Mayalsobespecifiedass .
s e t o p t
Shelloptionnamesasacceptedbythes h o p t builtin(seeBashBuiltins).
s i g n a l
Signalnames.
s t o p p e d
Namesofstoppedjobs,ifjobcontrolisactive.
u s e r
Usernames.Mayalsobespecifiedasu .
v a r i a b l e
Namesofallshellvariables.Mayalsobespecifiedasv .
Cc o m m a n d
commandisexecutedinasubshellenvironment,anditsoutputisusedasthepossiblecompletions.
Ff u n c t i o n
Thefilenameexpansionpatternglobpatisexpandedtogeneratethepossiblecompletions.
Pp r e f i x
prefixisaddedatthebeginningofeachpossiblecompletionafterallotheroptionshavebeenapplied.
Ss u f f i x
suffixisappendedtoeachpossiblecompletionafterallotheroptionshavebeenapplied.
Ww o r d l i s t
9UsingHistoryInteractively
ThischapterdescribeshowtousetheGNUHistoryLibraryinteractively,fromausersstandpoint.Itshouldbeconsideredausersguide.For informationonusingtheGNUHistoryLibraryinotherprograms,seetheGNUReadlineLibraryManual. BashHistoryFacilities: HowBashletsyoumanipulateyourcommandhistory. BashHistoryBuiltins: TheBashbuiltincommandsthatmanipulatethecommandhistory. HistoryInteraction: WhatitfeelslikeusingHistoryasauser. Next:BashHistoryBuiltins,Up:UsingHistoryInteractively[Contents][Index]
9.1BashHistoryFacilities
Whentheoh i s t o r y optiontothes e t builtinisenabled(seeTheSetBuiltin),theshellprovidesaccesstothecommandhistory,thelistofcommands previouslytyped.ThevalueoftheH I S T S I Z E shellvariableisusedasthenumberofcommandstosaveinahistorylist.Thetextofthelast$ H I S T S I Z E commands(default500)issaved.Theshellstoreseachcommandinthehistorylistpriortoparameterandvariableexpansionbutafterhistory expansionisperformed,subjecttothevaluesoftheshellvariablesH I S T I G N O R E andH I S T C O N T R O L . Whentheshellstartsup,thehistoryisinitializedfromthefilenamedbytheH I S T F I L E variable(default~ / . b a s h _ h i s t o r y ).Thefilenamedbythe valueofH I S T F I L E istruncated,ifnecessary,tocontainnomorethanthenumberoflinesspecifiedbythevalueoftheH I S T F I L E S I Z E variable.When aninteractiveshellexits,thelast$ H I S T S I Z E linesarecopiedfromthehistorylisttothefilenamedby$ H I S T F I L E .Iftheh i s t a p p e n d shelloptionisset (seeBashBuiltins),thelinesareappendedtothehistoryfile,otherwisethehistoryfileisoverwritten.IfH I S T F I L E isunset,orifthehistoryfileis unwritable,thehistoryisnotsaved.Aftersavingthehistory,thehistoryfileistruncatedtocontainnomorethan$ H I S T F I L E S I Z E lines.If H I S T F I L E S I Z E isnotset,notruncationisperformed. IftheH I S T T I M E F O R M A T isset,thetimestampinformationassociatedwitheachhistoryentryiswrittentothehistoryfile,markedwiththehistory commentcharacter.Whenthehistoryfileisread,linesbeginningwiththehistorycommentcharacterfollowedimmediatelybyadigitareinterpretedas timestampsfortheprevioushistoryline. Thebuiltincommandf c maybeusedtolistoreditandreexecuteaportionofthehistorylist.Theh i s t o r y builtinmaybeusedtodisplayormodify thehistorylistandmanipulatethehistoryfile.Whenusingcommandlineediting,searchcommandsareavailableineacheditingmodethatprovide accesstothehistorylist(seeCommandsForHistory). Theshellallowscontroloverwhichcommandsaresavedonthehistorylist.TheH I S T C O N T R O L andH I S T I G N O R E variablesmaybesettocausetheshell tosaveonlyasubsetofthecommandsentered.Thec m d h i s t shelloption,ifenabled,causestheshelltoattempttosaveeachlineofamultiline commandinthesamehistoryentry,addingsemicolonswherenecessarytopreservesyntacticcorrectness.Thel i t h i s t shelloptioncausestheshellto savethecommandwithembeddednewlinesinsteadofsemicolons.Thes h o p t builtinisusedtosettheseoptions.SeeBashBuiltins,foradescriptionof s h o p t . Next:HistoryInteraction,Previous:BashHistoryFacilities,Up:UsingHistoryInteractively[Contents][Index]
9.2BashHistoryBuiltins
Bashprovidestwobuiltincommandswhichmanipulatethehistorylistandhistoryfile.
f c f c[ ee n a m e ][ l n r ][ f i r s t ][ l a s t ] f cs[ p a t = r e p ][ c o m m a n d ]
FixCommand.Inthefirstform,arangeofcommandsfromfirsttolastisselectedfromthehistorylist.Bothfirstandlastmaybespecifiedasa string(tolocatethemostrecentcommandbeginningwiththatstring)orasanumber(anindexintothehistorylist,whereanegativenumberis usedasanoffsetfromthecurrentcommandnumber).Iflastisnotspecifieditissettofirst.Iffirstisnotspecifieditissettotheprevious commandforeditingand16forlisting.Ifthel flagisgiven,thecommandsarelistedonstandardoutput.Then flagsuppressesthecommand numberswhenlisting.Ther flagreversestheorderofthelisting.Otherwise,theeditorgivenbyenameisinvokedonafilecontainingthose commands.Ifenameisnotgiven,thevalueofthefollowingvariableexpansionisused:$ { F C E D I T : $ { E D I T O R : v i } } .Thissaystousethe valueoftheF C E D I T variableifset,orthevalueoftheE D I T O R variableifthatisset,orv i ifneitherisset.Wheneditingiscomplete,theedited commandsareechoedandexecuted. Inthesecondform,commandisreexecutedaftereachinstanceofpatintheselectedcommandisreplacedbyrep. Ausefulaliastousewiththef c commandisr = ' f cs ' ,sothattypingr c c runsthelastcommandbeginningwithc c andtypingr re executesthelastcommand(seeAliases).
h i s t o r y h i s t o r y[ n ] h i s t o r yc
h i s t o r ydo f f s e t h i s t o r y[ a n r w ][ f i l e n a m e ] h i s t o r yp sa r g
Clearthehistorylist.Thismaybecombinedwiththeotheroptionstoreplacethehistorylistcompletely.
do f f s e t
Deletethehistoryentryatpositionoffset.offsetshouldbespecifiedasitappearswhenthehistoryisdisplayed.
a
Appendthenewhistorylines(historylinesenteredsincethebeginningofthecurrentBashsession)tothehistoryfile.
n
Appendthehistorylinesnotalreadyreadfromthehistoryfiletothecurrenthistorylist.Thesearelinesappendedtothehistoryfilesince thebeginningofthecurrentBashsession.
r
Readthecurrenthistoryfileandappenditscontentstothehistorylist.
w
Writeoutthecurrenthistorytothehistoryfile.
p
Performhistorysubstitutionontheargsanddisplaytheresultonthestandardoutput,withoutstoringtheresultsinthehistorylist.
s
9.3HistoryExpansion
TheHistorylibraryprovidesahistoryexpansionfeaturethatissimilartothehistoryexpansionprovidedbyc s h .Thissectiondescribesthesyntaxused tomanipulatethehistoryinformation. Historyexpansionsintroducewordsfromthehistorylistintotheinputstream,makingiteasytorepeatcommands,inserttheargumentstoaprevious commandintothecurrentinputline,orfixerrorsinpreviouscommandsquickly. Historyexpansiontakesplaceintwoparts.Thefirstistodeterminewhichlinefromthehistorylistshouldbeusedduringsubstitution.Thesecondisto selectportionsofthatlineforinclusionintothecurrentone.Thelineselectedfromthehistoryiscalledtheevent,andtheportionsofthatlinethatare acteduponarecalledwords.Variousmodifiersareavailabletomanipulatetheselectedwords.Thelineisbrokenintowordsinthesamefashionthat Bashdoes,sothatseveralwordssurroundedbyquotesareconsideredoneword.Historyexpansionsareintroducedbytheappearanceofthehistory expansioncharacter,whichis! bydefault.Only\ and' maybeusedtoescapethehistoryexpansioncharacter. Severalshelloptionssettablewiththes h o p t builtin(seeBashBuiltins)maybeusedtotailorthebehaviorofhistoryexpansion.Iftheh i s t v e r i f y shell optionisenabled,andReadlineisbeingused,historysubstitutionsarenotimmediatelypassedtotheshellparser.Instead,theexpandedlineisreloaded intotheReadlineeditingbufferforfurthermodification.IfReadlineisbeingused,andtheh i s t r e e d i t shelloptionisenabled,afailedhistory expansionwillbereloadedintotheReadlineeditingbufferforcorrection.Thep optiontotheh i s t o r y builtincommandmaybeusedtoseewhata historyexpansionwilldobeforeusingit.Thes optiontotheh i s t o r y builtinmaybeusedtoaddcommandstotheendofthehistorylistwithout actuallyexecutingthem,sothattheyareavailableforsubsequentrecall.ThisismostusefulinconjunctionwithReadline. Theshellallowscontrolofthevariouscharactersusedbythehistoryexpansionmechanismwiththeh i s t c h a r s variable,asexplainedabove(seeBash Variables).Theshellusesthehistorycommentcharactertomarkhistorytimestampswhenwritingthehistoryfile. EventDesignators: Howtospecifywhichhistorylinetouse. WordDesignators: Specifyingwhichwordsareofinterest. Modifiers: Modifyingtheresultsofsubstitution. Next:WordDesignators,Up:HistoryInteraction[Contents][Index]
Refertocommandlinen.
! n
Refertothecommandnlinesback.
! !
Refertothepreviouscommand.Thisisasynonymfor! 1 .
! s t r i n g
Refertothemostrecentcommandprecedingthecurrentpositioninthehistoryliststartingwithstring.
! ? s t r i n g [ ? ]
QuickSubstitution.Repeatthelastcommand,replacingstring1withstring2.Equivalentto! ! : s / s t r i n g 1 / s t r i n g 2 / .
! #
Theentirecommandlinetypedsofar. Next:Modifiers,Previous:EventDesignators,Up:HistoryInteraction[Contents][Index] 9.3.2WordDesignators Worddesignatorsareusedtoselectdesiredwordsfromtheevent.A: separatestheeventspecificationfromtheworddesignator.Itmaybeomittedif theworddesignatorbeginswitha^ ,$ ,* ,,or% .Wordsarenumberedfromthebeginningoftheline,withthefirstwordbeingdenotedby0 (zero).Wordsareinsertedintothecurrentlineseparatedbysinglespaces. Forexample,
! !
designatestheprecedingcommand.Whenyoutypethis,theprecedingcommandisrepeatedintoto.
! ! : $
designatesthelastargumentoftheprecedingcommand.Thismaybeshortenedto! $ .
! f i : 2
designatesthesecondargumentofthemostrecentcommandstartingwiththelettersf i . Herearetheworddesignators:
0( z e r o )
The0 thword.Formanyapplications,thisisthecommandword.
n
Thenthword.
^
Thefirstargumentthatis,word1.
$
Thelastargument.
%
Thewordmatchedbythemostrecent? s t r i n g ? search.
x y
Arangeofwordsy abbreviates0 y .
*
Abbreviatesx $
x -
Removeatrailingpathnamecomponent,leavingonlythehead.
t
Removeallleadingpathnamecomponents,leavingthetail.
r
Removeatrailingsuffixoftheform. s u f f i x ,leavingthebasename.
e
Removeallbutthetrailingsuffix.
p
Printthenewcommandbutdonotexecuteit.
q
Quotethesubstitutedwords,escapingfurthersubstitutions.
x
Quotethesubstitutedwordsaswithq ,butbreakintowordsatspaces,tabs,andnewlines.
s / o l d / n e w /
Repeattheprevioussubstitution.
g a
10InstallingBash
ThischapterprovidesbasicinstructionsforinstallingBashonthevarioussupportedplatforms.ThedistributionsupportstheGNUoperatingsystems,
nearlyeveryversionofUnix,andseveralnonUnixsystemssuchasBeOSandInterix.OtherindependentportsexistforMSDOS,OS/2,andWindows platforms. BasicInstallation: Installationinstructions. CompilersandOptions: Howtosetspecialoptionsforvarioussystems. CompilingForMultipleArchitectures: HowtocompileBashformorethanonekindofsystemfromthesamesourcetree. InstallationNames: Howtosetthevariouspathsusedbytheinstallation. SpecifyingtheSystemType: HowtoconfigureBashforaparticularsystem. SharingDefaults: HowtosharedefaultconfigurationvaluesamongGNUprograms. OperationControls: Optionsrecognizedbytheconfigurationprogram. OptionalFeatures: HowtoenableanddisableoptionalfeatureswhenbuildingBash. Next:CompilersandOptions,Up:InstallingBash[Contents][Index]
10.1BasicInstallation
TheseareinstallationinstructionsforBash. ThesimplestwaytocompileBashis: 1. c d tothedirectorycontainingthesourcecodeandtype. / c o n f i g u r e toconfigureBashforyoursystem.Ifyoureusingc s h onanoldversion ofSystemV,youmightneedtotypes h. / c o n f i g u r e insteadtopreventc s h fromtryingtoexecutec o n f i g u r e itself. Runningc o n f i g u r e takessometime.Whilerunning,itprintsmessagestellingwhichfeaturesitischeckingfor. 2. Typem a k e tocompileBashandbuildtheb a s h b u g bugreportingscript. 3. Optionally,typem a k et e s t s toruntheBashtestsuite. 4. Typem a k ei n s t a l l toinstallb a s h andb a s h b u g .ThiswillalsoinstallthemanualpagesandInfofile. Thec o n f i g u r e shellscriptattemptstoguesscorrectvaluesforvarioussystemdependentvariablesusedduringcompilation.Itusesthosevaluesto createaM a k e f i l e ineachdirectoryofthepackage(thetopdirectory,theb u i l t i n s ,d o c ,ands u p p o r t directories,eachdirectoryunderl i b ,and severalothers).Italsocreatesac o n f i g . h filecontainingsystemdependentdefinitions.Finally,itcreatesashellscriptnamedc o n f i g . s t a t u s thatyou canruninthefuturetorecreatethecurrentconfiguration,afilec o n f i g . c a c h e thatsavestheresultsofitsteststospeedupreconfiguring,andafile c o n f i g . l o g containingcompileroutput(usefulmainlyfordebuggingc o n f i g u r e ).Ifatsomepointc o n f i g . c a c h e containsresultsyoudontwantto keep,youmayremoveoreditit. Tofindoutmoreabouttheoptionsandargumentsthatthec o n f i g u r e scriptunderstands,type
b a s h 2 . 0 4 $. / c o n f i g u r eh e l p
attheBashpromptinyourBashsourcedirectory. IfyouneedtodounusualthingstocompileBash,pleasetrytofigureouthowc o n f i g u r e couldcheckwhetherornottodothem,andmaildiffsor instructionstobashmaintainers@gnu.orgsotheycanbeconsideredforthenextrelease. Thefilec o n f i g u r e . i n isusedtocreatec o n f i g u r e byaprogramcalledAutoconf.Youonlyneedc o n f i g u r e . i n ifyouwanttochangeitor regeneratec o n f i g u r e usinganewerversionofAutoconf.Ifyoudothis,makesureyouareusingAutoconfversion2.50ornewer. Youcanremovetheprogrambinariesandobjectfilesfromthesourcecodedirectorybytypingm a k ec l e a n .Toalsoremovethefilesthatc o n f i g u r e created(soyoucancompileBashforadifferentkindofcomputer),typem a k ed i s t c l e a n . Next:CompilingForMultipleArchitectures,Previous:BasicInstallation,Up:InstallingBash[Contents][Index]
10.2CompilersandOptions
Somesystemsrequireunusualoptionsforcompilationorlinkingthatthec o n f i g u r e scriptdoesnotknowabout.Youcangivec o n f i g u r e initial valuesforvariablesbysettingthemintheenvironment.UsingaBournecompatibleshell,youcandothatonthecommandlinelikethis:
C C = c 8 9C F L A G S = O 2L I B S = l p o s i x. / c o n f i g u r e
Onsystemsthathavethee n v program,youcandoitlikethis:
e n vC P P F L A G S = I / u s r / l o c a l / i n c l u d eL D F L A G S = s. / c o n f i g u r e
TheconfigurationprocessusesGCCtobuildBashifitisavailable. Next:InstallationNames,Previous:CompilersandOptions,Up:InstallingBash[Contents][Index]
10.3CompilingForMultipleArchitectures
YoucancompileBashformorethanonekindofcomputeratthesametime,byplacingtheobjectfilesforeacharchitectureintheirowndirectory.To dothis,youmustuseaversionofm a k e thatsupportstheV P A T H variable,suchasGNUm a k e .c d tothedirectorywhereyouwanttheobjectfilesand executablestogoandrunthec o n f i g u r e scriptfromthesourcedirectory.Youmayneedtosupplythes r c d i r = P A T H argumenttotellc o n f i g u r e
wherethesourcefilesare.c o n f i g u r e automaticallychecksforthesourcecodeinthedirectorythatc o n f i g u r e isinandin... Ifyouhavetouseam a k e thatdoesnotsupportstheV P A T H variable,youcancompileBashforonearchitectureatatimeinthesourcecodedirectory. AfteryouhaveinstalledBashforonearchitecture,usem a k ed i s t c l e a n beforereconfiguringforanotherarchitecture. Alternatively,ifyoursystemsupportssymboliclinks,youcanusethes u p p o r t / m k c l o n e scripttocreateabuildtreewhichhassymboliclinksbackto eachfileinthesourcedirectory.Heresanexamplethatcreatesabuilddirectoryinthecurrentdirectoryfromasourcedirectory/ u s r / g n u / s r c / b a s h 2 . 0 :
b a s h/ u s r / g n u / s r c / b a s h 2 . 0 / s u p p o r t / m k c l o n es/ u s r / g n u / s r c / b a s h 2 . 0.
10.4InstallationNames
Bydefault,m a k ei n s t a l l willinstallinto/ u s r / l o c a l / b i n ,/ u s r / l o c a l / m a n ,etc.Youcanspecifyaninstallationprefixotherthan/ u s r / l o c a l by givingc o n f i g u r e theoptionp r e f i x = P A T H ,orbyspecifyingavaluefortheD E S T D I R m a k e variablewhenrunningm a k ei n s t a l l . Youcanspecifyseparateinstallationprefixesforarchitecturespecificfilesandarchitectureindependentfiles.Ifyougivec o n f i g u r e theoptione x e c p r e f i x = P A T H ,m a k ei n s t a l l willusePATHastheprefixforinstallingprogramsandlibraries.Documentationandotherdatafileswillstilluse theregularprefix. Next:SharingDefaults,Previous:InstallationNames,Up:InstallingBash[Contents][Index]
10.5SpecifyingtheSystemType
Theremaybesomefeaturesc o n f i g u r e cannotfigureoutautomatically,butneedtodeterminebythetypeofhostBashwillrunon.Usually c o n f i g u r e canfigurethatout,butifitprintsamessagesayingitcannotguessthehosttype,giveittheh o s t = T Y P E option.T Y P E caneitherbea shortnameforthesystemtype,suchass u n 4 ,oracanonicalnamewiththreefields:C P U C O M P A N Y S Y S T E M (e.g.,i 3 8 6 u n k n o w n f r e e b s d 4 . 2 ). Seethefiles u p p o r t / c o n f i g . s u b forthepossiblevaluesofeachfield. Next:OperationControls,Previous:SpecifyingtheSystemType,Up:InstallingBash[Contents][Index]
10.6SharingDefaults
Ifyouwanttosetdefaultvaluesforc o n f i g u r e scriptstoshare,youcancreateasiteshellscriptcalledc o n f i g . s i t e thatgivesdefaultvaluesfor variableslikeC C ,c a c h e _ f i l e ,andp r e f i x .c o n f i g u r e looksforP R E F I X / s h a r e / c o n f i g . s i t e ifitexists,thenP R E F I X / e t c / c o n f i g . s i t e ifit exists.Or,youcansettheC O N F I G _ S I T E environmentvariabletothelocationofthesitescript.Awarning:theBashc o n f i g u r e looksforasitescript, butnotallc o n f i g u r e scriptsdo. Next:OptionalFeatures,Previous:SharingDefaults,Up:InstallingBash[Contents][Index]
10.7OperationControls
c o n f i g u r e recognizesthefollowingoptionstocontrolhowitoperates. c a c h e f i l e = f i l e
Printasummaryoftheoptionstoc o n f i g u r e ,andexit.
q u i e t s i l e n t q
Donotprintmessagessayingwhichchecksarebeingmade.
s r c d i r = d i r
LookfortheBashsourcecodeindirectorydir.Usuallyc o n f i g u r e candeterminethatdirectoryautomatically.
v e r s i o n
PrinttheversionofAutoconfusedtogeneratethec o n f i g u r e script,andexit.
c o n f i g u r e alsoacceptssomeother,notwidelyused,boilerplateoptions.c o n f i g u r eh e l p printsthecompletelist.
Previous:OperationControls,Up:InstallingBash[Contents][Index]
10.8OptionalFeatures
TheBashc o n f i g u r e hasanumberofe n a b l e f e a t u r e options,wherefeatureindicatesanoptionalpartofBash.Therearealsoseveralw i t h p a c k a g e options,wherepackageissomethinglikeb a s h m a l l o c orp u r i f y .Toturnoffthedefaultuseofapackage,usew i t h o u t p a c k a g e .To configureBashwithoutafeaturethatisenabledbydefault,used i s a b l e f e a t u r e . Hereisacompletelistofthee n a b l e andw i t h optionsthattheBashc o n f i g u r e recognizes.
w i t h a f s
DefineifyouareusingtheAndrewFileSystemfromTransarc.
w i t h b a s h m a l l o c
UsetheBashversionofm a l l o c inthedirectoryl i b / m a l l o c .Thisisnotthesamem a l l o c thatappearsinGNUlibc,butanolderversion originallyderivedfromthe4.2BSDm a l l o c .Thism a l l o c isveryfast,butwastessomespaceoneachallocation.Thisoptionisenabledby default.TheN O T E S filecontainsalistofsystemsforwhichthisshouldbeturnedoff,andc o n f i g u r e disablesthisoptionautomaticallyfora numberofsystems.
w i t h c u r s e s
Usethecurseslibraryinsteadofthetermcaplibrary.Thisshouldbesuppliedifyoursystemhasaninadequateorincompletetermcapdatabase.
w i t h g n u m a l l o c
Asynonymforw i t h b a s h m a l l o c .
w i t h i n s t a l l e d r e a d l i n e [ = P R E F I X ]
DefinethistomakeBashlinkwithalocallyinstalledversionofReadlineratherthantheversioninl i b / r e a d l i n e .Thisworksonlywith Readline5.0andlaterversions.IfPREFIXisy e s ornotsupplied,c o n f i g u r e usesthevaluesofthemakevariablesi n c l u d e d i r andl i b d i r , whicharesubdirectoriesofp r e f i x bydefault,tofindtheinstalledversionofReadlineifitisnotinthestandardsystemincludeandlibrary directories.IfPREFIXisn o ,Bashlinkswiththeversioninl i b / r e a d l i n e .IfPREFIXissettoanyothervalue,c o n f i g u r e treatsitasa directorypathnameandlooksfortheinstalledversionofReadlineinsubdirectoriesofthatdirectory(includefilesinPREFIX/i n c l u d e andthe libraryinPREFIX/l i b ).
w i t h p u r i f y
DefinethistousethePurifymemoryallocationcheckerfromRationalSoftware.
e n a b l e m i n i m a l c o n f i g
Enablesupportforlargefilesiftheoperatingsystemrequiresspecialcompileroptionstobuildprogramswhichcanaccesslargefiles.Thisis enabledbydefault,iftheoperatingsystemprovideslargefilesupport.
e n a b l e p r o f i l i n g
ThisbuildsaBashbinarythatproducesprofilinginformationtobeprocessedbyg p r o f eachtimeitisexecuted.
e n a b l e s t a t i c l i n k
Includesupportforonedimensionalarrayshellvariables(seeArrays).
e n a b l e b a n g h i s t o r y
Includesupportforc s h likehistorysubstitution(seeHistoryInteraction).
e n a b l e b r a c e e x p a n s i o n
Includesupportforcasemodifyingwordexpansions.
e n a b l e c o m m a n d t i m i n g
Includesupportforthe[ [ conditionalcommand.(seeConditionalConstructs).
e n a b l e c o n d r e g e x p
Includesupportforcoprocessesandthec o p r o c reservedword(seePipelines).
e n a b l e d e b u g g e r
Includesupportforthebashdebugger(distributedseparately).
e n a b l e d i r e c t o r y s t a c k
Includesupportforthe( ( ) ) command(seeConditionalConstructs).
e n a b l e e x t e n d e d g l o b
IncludesupportfortheextendedpatternmatchingfeaturesdescribedaboveunderPatternMatching.
e n a b l e e x t e n d e d g l o b d e f a u l t
SetthedefaultvalueoftheextglobshelloptiondescribedaboveunderTheShoptBuiltintobeenabled.
e n a b l e h e l p b u i l t i n
Includetheh e l p builtin,whichdisplayshelponshellbuiltinsandvariables(seeBashBuiltins).
e n a b l e h i s t o r y
Thisenablesthejobcontrolfeatures(seeJobControl),iftheoperatingsystemsupportsthem.
e n a b l e m u l t i b y t e
Thisenablessupportformultibytecharactersiftheoperatingsystemprovidesthenecessarysupport.
e n a b l e n e t r e d i r e c t i o n s
Thisenablesprocesssubstitution(seeProcessSubstitution)iftheoperatingsystemprovidesthenecessarysupport.
e n a b l e p r o g c o m p
Enabletheprogrammablecompletionfacilities(seeProgrammableCompletion).IfReadlineisnotenabled,thisoptionhasnoeffect.
e n a b l e p r o m p t s t r i n g d e c o d i n g
IncludesupportforcommandlineeditingandhistorywiththeBashversionoftheReadlinelibrary(seeCommandLineEditing).
e n a b l e r e s t r i c t e d
Includethes e l e c t compoundcommand,whichallowsthegenerationofsimplemenus(seeConditionalConstructs).
e n a b l e s e p a r a t e h e l p f i l e s
Useexternalfilesforthedocumentationdisplayedbytheh e l p builtininsteadofstoringthetextinternally.
e n a b l e s i n g l e h e l p s t r i n g s
MakeBashPOSIXconformantbydefault(seeBashPOSIXMode).
e n a b l e u s g e c h o d e f a u l t
Asynonymfore n a b l e x p g e c h o d e f a u l t .
e n a b l e x p g e c h o d e f a u l t
Makethee c h o builtinexpandbackslashescapedcharactersbydefault,withoutrequiringthee option.Thissetsthedefaultvalueofthe x p g _ e c h o shelloptiontoo n ,whichmakestheBashe c h o behavemoreliketheversionspecifiedintheSingleUnixSpecification,version3.See BashBuiltins,foradescriptionoftheescapesequencesthate c h o recognizes. Thefilec o n f i g t o p . h containsCPreprocessor# d e f i n e statementsforoptionswhicharenotsettablefromc o n f i g u r e .Someofthesearenotmeant tobechangedbewareoftheconsequencesifyoudo.Readthecommentsassociatedwitheachdefinitionformoreinformationaboutitseffect. Next:MajorDifferencesFromTheBourneShell,Previous:InstallingBash,Up:Top[Contents][Index]
AppendixAReportingBugs
PleasereportallbugsyoufindinBash.Butfirst,youshouldmakesurethatitreallyisabug,andthatitappearsinthelatestversionofBash.Thelatest versionofBashisalwaysavailableforFTPfromftp://ftp.gnu.org/pub/gnu/bash/. Onceyouhavedeterminedthatabugactuallyexists,usetheb a s h b u g commandtosubmitabugreport.Ifyouhaveafix,youareencouragedtomail thataswell!Suggestionsandphilosophicalbugreportsmaybemailedtobugbash@gnu.orgorpostedtotheUsenetnewsgroupg n u . b a s h . b u g . Allbugreportsshouldinclude: TheversionnumberofBash. Thehardwareandoperatingsystem. ThecompilerusedtocompileBash. Adescriptionofthebugbehaviour. Ashortscriptorrecipewhichexercisesthebugandmaybeusedtoreproduceit.
b a s h b u g insertsthefirstthreeitemsautomaticallyintothetemplateitprovidesforfilingabugreport.
Pleasesendallreportsconcerningthismanualtochet.ramey@case.edu. Next:GNUFreeDocumentationLicense,Previous:ReportingBugs,Up:Top[Contents][Index]
AppendixBMajorDifferencesFromTheBourneShell
Bashimplementsessentiallythesamegrammar,parameterandvariableexpansion,redirection,andquotingastheBourneShell.BashusesthePOSIX standardasthespecificationofhowthesefeaturesaretobeimplemented.TherearesomedifferencesbetweenthetraditionalBourneshellandBash thissectionquicklydetailsthedifferencesofsignificance.Anumberofthesedifferencesareexplainedingreaterdepthinprevioussections.This sectionusestheversionofs h includedinSVR4.2(thelastversionofthehistoricalBourneshell)asthebaselinereference. BashisPOSIXconformant,evenwherethePOSIXspecificationdiffersfromtraditionals h behavior(seeBashPOSIXMode). Bashhasmulticharacterinvocationoptions(seeInvokingBash). Bashhascommandlineediting(seeCommandLineEditing)andtheb i n d builtin. Bashprovidesaprogrammablewordcompletionmechanism(seeProgrammableCompletion),andbuiltincommandsc o m p l e t e ,c o m p g e n ,and c o m p o p t ,tomanipulateit. Bashhascommandhistory(seeBashHistoryFacilities)andtheh i s t o r y andf c builtinstomanipulateit.TheBashhistorylistmaintains timestampinformationandusesthevalueoftheH I S T T I M E F O R M A T variabletodisplayit. Bashimplementsc s h likehistoryexpansion(seeHistoryInteraction). Bashhasonedimensionalarrayvariables(seeArrays),andtheappropriatevariableexpansionsandassignmentsyntaxtousethem.Severalof theBashbuiltinstakeoptionstoactonarrays.Bashprovidesanumberofbuiltinarrayvariables. The$ ' ' quotingsyntax,whichexpandsANSICbackslashescapedcharactersinthetextbetweenthesinglequotes,issupported(seeANSIC Quoting). Bashsupportsthe$ " " quotingsyntaxtodolocalespecifictranslationofthecharactersbetweenthedoublequotes.TheD ,d u m p s t r i n g s , andd u m p p o s t r i n g s invocationoptionslistthetranslatablestringsfoundinascript(seeLocaleTranslation). Bashimplementsthe! keywordtonegatethereturnvalueofapipeline(seePipelines).Veryusefulwhenani f statementneedstoactonlyifa testfails.TheBashop i p e f a i l optiontos e t willcauseapipelinetoreturnafailurestatusifanycommandfails. Bashhasthet i m e reservedwordandcommandtiming(seePipelines).Thedisplayofthetimingstatisticsmaybecontrolledwiththe T I M E F O R M A T variable. Bashimplementsthef o r( (e x p r 1;e x p r 2;e x p r 3) ) arithmeticforcommand,similartotheClanguage(seeLoopingConstructs). Bashincludesthes e l e c t compoundcommand,whichallowsthegenerationofsimplemenus(seeConditionalConstructs). Bashincludesthe[ [ compoundcommand,whichmakesconditionaltestingpartoftheshellgrammar(seeConditionalConstructs),including optionalregularexpressionmatching. Bashprovidesoptionalcaseinsensitivematchingforthec a s e and[ [ constructs. Bashincludesbraceexpansion(seeBraceExpansion)andtildeexpansion(seeTildeExpansion). Bashimplementscommandaliasesandthea l i a s andu n a l i a s builtins(seeAliases). Bashprovidesshellarithmetic,the( ( compoundcommand(seeConditionalConstructs),andarithmeticexpansion(seeShellArithmetic). Variablespresentintheshellsinitialenvironmentareautomaticallyexportedtochildprocesses.TheBourneshelldoesnotnormallydothis unlessthevariablesareexplicitlymarkedusingthee x p o r t command. Bashsupportsthe+ = assignmentoperator,whichappendstothevalueofthevariablenamedonthelefthandside. BashincludesthePOSIXpatternremoval% ,# ,% % and# # expansionstoremoveleadingortrailingsubstringsfromvariablevalues(seeShell ParameterExpansion). Theexpansion$ { # x x } ,whichreturnsthelengthof$ { x x } ,issupported(seeShellParameterExpansion). Theexpansion$ { v a r : offset[ : length] } ,whichexpandstothesubstringofv a r svalueoflengthlength,beginningatoffset,ispresent(seeShell ParameterExpansion). Theexpansion$ { v a r / [ / ] pattern[ / replacement] } ,whichmatchespatternandreplacesitwithreplacementinthevalueofv a r ,isavailable(see ShellParameterExpansion). Theexpansion$ { ! p r e f i x } * expansion,whichexpandstothenamesofallshellvariableswhosenamesbeginwithprefix,isavailable(seeShell ParameterExpansion). Bashhasindirectvariableexpansionusing$ { ! w o r d } (seeShellParameterExpansion). Bashcanexpandpositionalparametersbeyond$ 9 using$ { n u m } . ThePOSIX$ ( ) formofcommandsubstitutionisimplemented(seeCommandSubstitution),andpreferredtotheBourneshells` ` (whichisalso implementedforbackwardscompatibility). Bashhasprocesssubstitution(seeProcessSubstitution). Bashautomaticallyassignsvariablesthatprovideinformationaboutthecurrentuser(U I D ,E U I D ,andG R O U P S ),thecurrenthost(H O S T T Y P E , O S T Y P E ,M A C H T Y P E ,andH O S T N A M E ),andtheinstanceofBashthatisrunning(B A S H ,B A S H _ V E R S I O N ,andB A S H _ V E R S I N F O ).SeeBashVariables, fordetails. TheI F S variableisusedtosplitonlytheresultsofexpansion,notallwords(seeWordSplitting).Thisclosesalongstandingshellsecurityhole. BashimplementsthefullsetofPOSIXfilenameexpansionoperators,includingcharacterclasses,equivalenceclasses,andcollatingsymbols(see FilenameExpansion). Bashimplementsextendedpatternmatchingfeatureswhenthee x t g l o b shelloptionisenabled(seePatternMatching). Itispossibletohaveavariableandafunctionwiththesamenames h doesnotseparatethetwonamespaces. Bashfunctionsarepermittedtohavelocalvariablesusingthel o c a l builtin,andthususefulrecursivefunctionsmaybewritten(seeBash Builtins). Variableassignmentsprecedingcommandsaffectonlythatcommand,evenbuiltinsandfunctions(seeEnvironment).Ins h ,allvariable assignmentsprecedingcommandsareglobalunlessthecommandisexecutedfromthefilesystem. Bashperformsfilenameexpansiononfilenamesspecifiedasoperandstoinputandoutputredirectionoperators(seeRedirections). Bashcontainsthe< > redirectionoperator,allowingafiletobeopenedforbothreadingandwriting,andthe& > redirectionoperator,for directingstandardoutputandstandarderrortothesamefile(seeRedirections). Bashincludesthe< < < redirectionoperator,allowingastringtobeusedasthestandardinputtoacommand. Bashimplementsthe[ n ] < & w o r d and[ n ] > & w o r d redirectionoperators,whichmoveonefiledescriptortoanother. Bashtreatsanumberoffilenamesspeciallywhentheyareusedinredirectionoperators(seeRedirections). Bashcanopennetworkconnectionstoarbitrarymachinesandserviceswiththeredirectionoperators(seeRedirections). Then o c l o b b e r optionisavailabletoavoidoverwritingexistingfileswithoutputredirection(seeTheSetBuiltin).The> | redirectionoperator maybeusedtooverriden o c l o b b e r . TheBashc d andp w d builtins(seeBourneShellBuiltins)eachtakeL andP optionstoswitchbetweenlogicalandphysicalmodes. Bashallowsafunctiontooverrideabuiltinwiththesamename,andprovidesaccesstothatbuiltinsfunctionalitywithinthefunctionviathe b u i l t i n andc o m m a n d builtins(seeBashBuiltins). Thec o m m a n d builtinallowsselectivedisablingoffunctionswhencommandlookupisperformed(seeBashBuiltins).
Individualbuiltinsmaybeenabledordisabledusingthee n a b l e builtin(seeBashBuiltins). TheBashe x e c builtintakesadditionaloptionsthatallowuserstocontrolthecontentsoftheenvironmentpassedtotheexecutedcommand,and whatthezerothargumenttothecommandistobe(seeBourneShellBuiltins). Shellfunctionsmaybeexportedtochildrenviatheenvironmentusinge x p o r tf (seeShellFunctions). TheBashe x p o r t ,r e a d o n l y ,andd e c l a r e builtinscantakeaf optiontoactonshellfunctions,ap optiontodisplayvariableswithvarious attributessetinaformatthatcanbeusedasshellinput,an optiontoremovevariousvariableattributes,andn a m e = v a l u e argumentstoset variableattributesandvaluessimultaneously. TheBashh a s h builtinallowsanametobeassociatedwithanarbitraryfilename,evenwhenthatfilenamecannotbefoundbysearchingthe $ P A T H ,usingh a s hp (seeBourneShellBuiltins). Bashincludesah e l p builtinforquickreferencetoshellfacilities(seeBashBuiltins). Thep r i n t f builtinisavailabletodisplayformattedoutput(seeBashBuiltins). TheBashr e a d builtin(seeBashBuiltins)willreadalineendingin\ withther option,andwillusetheR E P L Y variableasadefaultifnonon optionargumentsaresupplied.TheBashr e a d builtinalsoacceptsapromptstringwiththep optionandwilluseReadlinetoobtaintheline whengiventhee option.Ther e a d builtinalsohasadditionaloptionstocontrolinput:thes optionwillturnoffechoingofinputcharactersas theyareread,thet optionwillallowr e a d totimeoutifinputdoesnotarrivewithinaspecifiednumberofseconds,then optionwillallow readingonlyaspecifiednumberofcharactersratherthanafullline,andthed optionwillreaduntilaparticularcharacterratherthannewline. Ther e t u r n builtinmaybeusedtoabortexecutionofscriptsexecutedwiththe. ors o u r c e builtins(seeBourneShellBuiltins). Bashincludesthes h o p t builtin,forfinercontrolofshelloptionalcapabilities(seeTheShoptBuiltin),andallowstheseoptionstobesetand unsetatshellinvocation(seeInvokingBash). Bashhasmuchmoreoptionalbehaviorcontrollablewiththes e t builtin(seeTheSetBuiltin). Thex (x t r a c e )optiondisplayscommandsotherthansimplecommandswhenperforminganexecutiontrace(seeTheSetBuiltin). Thet e s t builtin(seeBourneShellBuiltins)isslightlydifferent,asitimplementsthePOSIXalgorithm,whichspecifiesthebehaviorbasedonthe numberofarguments. Bashincludesthec a l l e r builtin,whichdisplaysthecontextofanyactivesubroutinecall(ashellfunctionorascriptexecutedwiththe. or s o u r c e builtins).Thissupportsthebashdebugger. Thet r a p builtin(seeBourneShellBuiltins)allowsaD E B U G pseudosignalspecification,similartoE X I T .CommandsspecifiedwithaD E B U G trap areexecutedbeforeeverysimplecommand,f o r command,c a s e command,s e l e c t command,everyarithmeticf o r command,andbeforethe firstcommandexecutesinashellfunction.TheD E B U G trapisnotinheritedbyshellfunctionsunlessthefunctionhasbeengiventhet r a c e attributeorthef u n c t r a c e optionhasbeenenabledusingthes h o p t builtin.Thee x t d e b u g shelloptionhasadditionaleffectsontheD E B U G trap. Thet r a p builtin(seeBourneShellBuiltins)allowsanE R R pseudosignalspecification,similartoE X I T andD E B U G .Commandsspecifiedwithan E R R trapareexecutedafterasimplecommandfails,withafewexceptions.TheE R R trapisnotinheritedbyshellfunctionsunlesstheo e r r t r a c e optiontothes e t builtinisenabled. Thet r a p builtin(seeBourneShellBuiltins)allowsaR E T U R N pseudosignalspecification,similartoE X I T andD E B U G .Commandsspecifiedwith anR E T U R N trapareexecutedbeforeexecutionresumesafterashellfunctionorashellscriptexecutedwith. ors o u r c e returns.TheR E T U R N trap isnotinheritedbyshellfunctionsunlessthefunctionhasbeengiventhet r a c e attributeorthef u n c t r a c e optionhasbeenenabledusingthe s h o p t builtin. TheBasht y p e builtinismoreextensiveandgivesmoreinformationaboutthenamesitfinds(seeBashBuiltins). TheBashu m a s k builtinpermitsap optiontocausetheoutputtobedisplayedintheformofau m a s k commandthatmaybereusedasinput(see BourneShellBuiltins). Bashimplementsac s h likedirectorystack,andprovidesthep u s h d ,p o p d ,andd i r s builtinstomanipulateit(seeTheDirectoryStack).Bash alsomakesthedirectorystackvisibleasthevalueoftheD I R S T A C K shellvariable. Bashinterpretsspecialbackslashescapedcharactersinthepromptstringswheninteractive(seePrintingaPrompt). TheBashrestrictedmodeismoreuseful(seeTheRestrictedShell)theSVR4.2shellrestrictedmodeistoolimited. Thed i s o w n builtincanremoveajobfromtheinternalshelljobtable(seeJobControlBuiltins)orsuppressthesendingofS I G H U P toajobwhen theshellexitsastheresultofaS I G H U P . Bashincludesanumberoffeaturestosupportaseparatedebuggerforshellscripts. TheSVR4.2shellhastwoprivilegerelatedbuiltins(m l d m o d e andp r i v )notpresentinBash. Bashdoesnothavethes t o p orn e w g r p builtins. BashdoesnotusetheS H A C C T variableorperformshellaccounting. TheSVR4.2s h usesaT I M E O U T variablelikeBashusesT M O U T . MorefeaturesuniquetoBashmaybefoundinBashFeatures.
B.1ImplementationDifferencesFromTheSVR4.2Shell
SinceBashisacompletelynewimplementation,itdoesnotsufferfrommanyofthelimitationsoftheSVR4.2shell.Forinstance: Bashdoesnotforkasubshellwhenredirectingintooroutofashellcontrolstructuresuchasani f orw h i l e statement. Bashdoesnotallowunbalancedquotes.TheSVR4.2shellwillsilentlyinsertaneededclosingquoteatE O F undercertaincircumstances.This canbethecauseofsomehardtofinderrors. TheSVR4.2shellusesabaroquememorymanagementschemebasedontrappingS I G S E G V .IftheshellisstartedfromaprocesswithS I G S E G V blocked(e.g.,byusingthes y s t e m ( ) Clibraryfunctioncall),itmisbehavesbadly. Inaquestionableattemptatsecurity,theSVR4.2shell,wheninvokedwithoutthep option,willalteritsrealandeffectiveUIDandGIDifthey arelessthansomemagicthresholdvalue,commonly100.Thiscanleadtounexpectedresults. TheSVR4.2shelldoesnotallowuserstotrapS I G S E G V ,S I G A L R M ,orS I G C H L D . TheSVR4.2shelldoesnotallowtheI F S ,M A I L C H E C K ,P A T H ,P S 1 ,orP S 2 variablestobeunset. TheSVR4.2shelltreats^ astheundocumentedequivalentof| . Bashallowsmultipleoptionargumentswhenitisinvoked(xv )theSVR4.2shellallowsonlyoneoptionargument(x v ).Infact,some versionsoftheshelldumpcoreifthesecondargumentbeginswitha. TheSVR4.2shellexitsascriptifanybuiltinfailsBashexitsascriptonlyifoneofthePOSIXspecialbuiltinsfails,andonlyforcertainfailures,as
AppendixCGNUFreeDocumentationLicense
Version1.3,3November2008 Copyright2000,2001,2002,2007,2008FreeSoftwareFoundation,Inc. http://fsf.org/ Everyoneispermittedtocopyanddistributeverbatimcopies ofthislicensedocument,butchangingitisnotallowed. 1. PREAMBLE ThepurposeofthisLicenseistomakeamanual,textbook,orotherfunctionalandusefuldocumentfreeinthesenseoffreedom:toassure everyonetheeffectivefreedomtocopyandredistributeit,withorwithoutmodifyingit,eithercommerciallyornoncommercially.Secondarily, thisLicensepreservesfortheauthorandpublisherawaytogetcreditfortheirwork,whilenotbeingconsideredresponsibleformodifications madebyothers. ThisLicenseisakindofcopyleft,whichmeansthatderivativeworksofthedocumentmustthemselvesbefreeinthesamesense.It complementstheGNUGeneralPublicLicense,whichisacopyleftlicensedesignedforfreesoftware. WehavedesignedthisLicenseinordertouseitformanualsforfreesoftware,becausefreesoftwareneedsfreedocumentation:afreeprogram shouldcomewithmanualsprovidingthesamefreedomsthatthesoftwaredoes.ButthisLicenseisnotlimitedtosoftwaremanualsitcanbeused foranytextualwork,regardlessofsubjectmatterorwhetheritispublishedasaprintedbook.WerecommendthisLicenseprincipallyforworks whosepurposeisinstructionorreference. 2. APPLICABILITYANDDEFINITIONS ThisLicenseappliestoanymanualorotherwork,inanymedium,thatcontainsanoticeplacedbythecopyrightholdersayingitcanbe distributedunderthetermsofthisLicense.Suchanoticegrantsaworldwide,royaltyfreelicense,unlimitedinduration,tousethatworkunder theconditionsstatedherein.TheDocument,below,referstoanysuchmanualorwork.Anymemberofthepublicisalicensee,andis addressedasyou.Youacceptthelicenseifyoucopy,modifyordistributetheworkinawayrequiringpermissionundercopyrightlaw. AModifiedVersionoftheDocumentmeansanyworkcontainingtheDocumentoraportionofit,eithercopiedverbatim,orwith modificationsand/ortranslatedintoanotherlanguage. ASecondarySectionisanamedappendixorafrontmattersectionoftheDocumentthatdealsexclusivelywiththerelationshipofthe publishersorauthorsoftheDocumenttotheDocumentsoverallsubject(ortorelatedmatters)andcontainsnothingthatcouldfalldirectlywithin thatoverallsubject.(Thus,iftheDocumentisinpartatextbookofmathematics,aSecondarySectionmaynotexplainanymathematics.)The relationshipcouldbeamatterofhistoricalconnectionwiththesubjectorwithrelatedmatters,oroflegal,commercial,philosophical,ethicalor politicalpositionregardingthem. TheInvariantSectionsarecertainSecondarySectionswhosetitlesaredesignated,asbeingthoseofInvariantSections,inthenoticethatsays thattheDocumentisreleasedunderthisLicense.IfasectiondoesnotfittheabovedefinitionofSecondarythenitisnotallowedtobedesignated asInvariant.TheDocumentmaycontainzeroInvariantSections.IftheDocumentdoesnotidentifyanyInvariantSectionsthentherearenone. TheCoverTextsarecertainshortpassagesoftextthatarelisted,asFrontCoverTextsorBackCoverTexts,inthenoticethatsaysthatthe DocumentisreleasedunderthisLicense.AFrontCoverTextmaybeatmost5words,andaBackCoverTextmaybeatmost25words. ATransparentcopyoftheDocumentmeansamachinereadablecopy,representedinaformatwhosespecificationisavailabletothegeneral public,thatissuitableforrevisingthedocumentstraightforwardlywithgenerictexteditorsor(forimagescomposedofpixels)genericpaint programsor(fordrawings)somewidelyavailabledrawingeditor,andthatissuitableforinputtotextformattersorforautomatictranslationtoa varietyofformatssuitableforinputtotextformatters.AcopymadeinanotherwiseTransparentfileformatwhosemarkup,orabsenceof markup,hasbeenarrangedtothwartordiscouragesubsequentmodificationbyreadersisnotTransparent.AnimageformatisnotTransparentif usedforanysubstantialamountoftext.AcopythatisnotTransparentiscalledOpaque. ExamplesofsuitableformatsforTransparentcopiesincludeplainASCIIwithoutmarkup,Texinfoinputformat,LaTeXinputformat,SGMLor XMLusingapubliclyavailableDTD,andstandardconformingsimpleHTML,PostScriptorPDFdesignedforhumanmodification.Examples oftransparentimageformatsincludePNG,XCFandJPG.Opaqueformatsincludeproprietaryformatsthatcanbereadandeditedonlyby proprietarywordprocessors,SGMLorXMLforwhichtheDTDand/orprocessingtoolsarenotgenerallyavailable,andthemachinegenerated HTML,PostScriptorPDFproducedbysomewordprocessorsforoutputpurposesonly. TheTitlePagemeans,foraprintedbook,thetitlepageitself,plussuchfollowingpagesasareneededtohold,legibly,thematerialthisLicense requirestoappearinthetitlepage.Forworksinformatswhichdonothaveanytitlepageassuch,TitlePagemeansthetextnearthemost prominentappearanceoftheworkstitle,precedingthebeginningofthebodyofthetext. ThepublishermeansanypersonorentitythatdistributescopiesoftheDocumenttothepublic. AsectionEntitledXYZmeansanamedsubunitoftheDocumentwhosetitleeitherispreciselyXYZorcontainsXYZinparentheses followingtextthattranslatesXYZinanotherlanguage.(HereXYZstandsforaspecificsectionnamementionedbelow,suchas
Acknowledgements,Dedications,Endorsements,orHistory.)ToPreservetheTitleofsuchasectionwhenyoumodifytheDocument meansthatitremainsasectionEntitledXYZaccordingtothisdefinition. TheDocumentmayincludeWarrantyDisclaimersnexttothenoticewhichstatesthatthisLicenseappliestotheDocument.TheseWarranty DisclaimersareconsideredtobeincludedbyreferenceinthisLicense,butonlyasregardsdisclaimingwarranties:anyotherimplicationthatthese WarrantyDisclaimersmayhaveisvoidandhasnoeffectonthemeaningofthisLicense. 3. VERBATIMCOPYING YoumaycopyanddistributetheDocumentinanymedium,eithercommerciallyornoncommercially,providedthatthisLicense,thecopyright notices,andthelicensenoticesayingthisLicenseappliestotheDocumentarereproducedinallcopies,andthatyouaddnootherconditions whatsoevertothoseofthisLicense.Youmaynotusetechnicalmeasurestoobstructorcontrolthereadingorfurthercopyingofthecopiesyou makeordistribute.However,youmayacceptcompensationinexchangeforcopies.Ifyoudistributealargeenoughnumberofcopiesyoumust alsofollowtheconditionsinsection3. Youmayalsolendcopies,underthesameconditionsstatedabove,andyoumaypubliclydisplaycopies. 4. COPYINGINQUANTITY Ifyoupublishprintedcopies(orcopiesinmediathatcommonlyhaveprintedcovers)oftheDocument,numberingmorethan100,andthe DocumentslicensenoticerequiresCoverTexts,youmustenclosethecopiesincoversthatcarry,clearlyandlegibly,alltheseCoverTexts: FrontCoverTextsonthefrontcover,andBackCoverTextsonthebackcover.Bothcoversmustalsoclearlyandlegiblyidentifyyouasthe publisherofthesecopies.Thefrontcovermustpresentthefulltitlewithallwordsofthetitleequallyprominentandvisible.Youmayaddother materialonthecoversinaddition.Copyingwithchangeslimitedtothecovers,aslongastheypreservethetitleoftheDocumentandsatisfythese conditions,canbetreatedasverbatimcopyinginotherrespects. Iftherequiredtextsforeithercoveraretoovoluminoustofitlegibly,youshouldputthefirstoneslisted(asmanyasfitreasonably)ontheactual cover,andcontinuetherestontoadjacentpages. IfyoupublishordistributeOpaquecopiesoftheDocumentnumberingmorethan100,youmusteitherincludeamachinereadableTransparent copyalongwitheachOpaquecopy,orstateinorwitheachOpaquecopyacomputernetworklocationfromwhichthegeneralnetworkusing publichasaccesstodownloadusingpublicstandardnetworkprotocolsacompleteTransparentcopyoftheDocument,freeofaddedmaterial.If youusethelatteroption,youmusttakereasonablyprudentsteps,whenyoubegindistributionofOpaquecopiesinquantity,toensurethatthis TransparentcopywillremainthusaccessibleatthestatedlocationuntilatleastoneyearafterthelasttimeyoudistributeanOpaquecopy (directlyorthroughyouragentsorretailers)ofthateditiontothepublic. Itisrequested,butnotrequired,thatyoucontacttheauthorsoftheDocumentwellbeforeredistributinganylargenumberofcopies,togivethem achancetoprovideyouwithanupdatedversionoftheDocument. 5. MODIFICATIONS YoumaycopyanddistributeaModifiedVersionoftheDocumentundertheconditionsofsections2and3above,providedthatyoureleasethe ModifiedVersionunderpreciselythisLicense,withtheModifiedVersionfillingtheroleoftheDocument,thuslicensingdistributionand modificationoftheModifiedVersiontowhoeverpossessesacopyofit.Inaddition,youmustdothesethingsintheModifiedVersion: 1. UseintheTitlePage(andonthecovers,ifany)atitledistinctfromthatoftheDocument,andfromthoseofpreviousversions(which should,iftherewereany,belistedintheHistorysectionoftheDocument).Youmayusethesametitleasapreviousversioniftheoriginal publisherofthatversiongivespermission. 2. ListontheTitlePage,asauthors,oneormorepersonsorentitiesresponsibleforauthorshipofthemodificationsintheModifiedVersion, togetherwithatleastfiveoftheprincipalauthorsoftheDocument(allofitsprincipalauthors,ifithasfewerthanfive),unlesstheyrelease youfromthisrequirement. 3. StateontheTitlepagethenameofthepublisheroftheModifiedVersion,asthepublisher. 4. PreserveallthecopyrightnoticesoftheDocument. 5. Addanappropriatecopyrightnoticeforyourmodificationsadjacenttotheothercopyrightnotices. 6. Include,immediatelyafterthecopyrightnotices,alicensenoticegivingthepublicpermissiontousetheModifiedVersionundertheterms ofthisLicense,intheformshownintheAddendumbelow. 7. PreserveinthatlicensenoticethefulllistsofInvariantSectionsandrequiredCoverTextsgivenintheDocumentslicensenotice. 8. IncludeanunalteredcopyofthisLicense. 9. PreservethesectionEntitledHistory,PreserveitsTitle,andaddtoitanitemstatingatleastthetitle,year,newauthors,andpublisherof theModifiedVersionasgivenontheTitlePage.IfthereisnosectionEntitledHistoryintheDocument,createonestatingthetitle,year, authors,andpublisheroftheDocumentasgivenonitsTitlePage,thenaddanitemdescribingtheModifiedVersionasstatedinthe previoussentence. 10. Preservethenetworklocation,ifany,givenintheDocumentforpublicaccesstoaTransparentcopyoftheDocument,andlikewisethe networklocationsgivenintheDocumentforpreviousversionsitwasbasedon.ThesemaybeplacedintheHistorysection.Youmay omitanetworklocationforaworkthatwaspublishedatleastfouryearsbeforetheDocumentitself,oriftheoriginalpublisherofthe versionitreferstogivespermission. 11. ForanysectionEntitledAcknowledgementsorDedications,PreservetheTitleofthesection,andpreserveinthesectionallthe substanceandtoneofeachofthecontributoracknowledgementsand/ordedicationsgiventherein. 12. PreservealltheInvariantSectionsoftheDocument,unalteredintheirtextandintheirtitles.Sectionnumbersortheequivalentarenot consideredpartofthesectiontitles. 13. DeleteanysectionEntitledEndorsements.SuchasectionmaynotbeincludedintheModifiedVersion. 14. DonotretitleanyexistingsectiontobeEntitledEndorsementsortoconflictintitlewithanyInvariantSection. 15. PreserveanyWarrantyDisclaimers. IftheModifiedVersionincludesnewfrontmattersectionsorappendicesthatqualifyasSecondarySectionsandcontainnomaterialcopiedfrom
theDocument,youmayatyouroptiondesignatesomeorallofthesesectionsasinvariant.Todothis,addtheirtitlestothelistofInvariant SectionsintheModifiedVersionslicensenotice.Thesetitlesmustbedistinctfromanyothersectiontitles. YoumayaddasectionEntitledEndorsements,provideditcontainsnothingbutendorsementsofyourModifiedVersionbyvariousparties forexample,statementsofpeerrevieworthatthetexthasbeenapprovedbyanorganizationastheauthoritativedefinitionofastandard. YoumayaddapassageofuptofivewordsasaFrontCoverText,andapassageofupto25wordsasaBackCoverText,totheendofthelist ofCoverTextsintheModifiedVersion.OnlyonepassageofFrontCoverTextandoneofBackCoverTextmaybeaddedby(orthrough arrangementsmadeby)anyoneentity.IftheDocumentalreadyincludesacovertextforthesamecover,previouslyaddedbyyouorby arrangementmadebythesameentityyouareactingonbehalfof,youmaynotaddanotherbutyoumayreplacetheoldone,onexplicit permissionfromthepreviouspublisherthataddedtheoldone. Theauthor(s)andpublisher(s)oftheDocumentdonotbythisLicensegivepermissiontousetheirnamesforpublicityforortoassertorimply endorsementofanyModifiedVersion. 6. COMBININGDOCUMENTS YoumaycombinetheDocumentwithotherdocumentsreleasedunderthisLicense,underthetermsdefinedinsection4aboveformodified versions,providedthatyouincludeinthecombinationalloftheInvariantSectionsofalloftheoriginaldocuments,unmodified,andlistthemall asInvariantSectionsofyourcombinedworkinitslicensenotice,andthatyoupreservealltheirWarrantyDisclaimers. ThecombinedworkneedonlycontainonecopyofthisLicense,andmultipleidenticalInvariantSectionsmaybereplacedwithasinglecopy.If therearemultipleInvariantSectionswiththesamenamebutdifferentcontents,makethetitleofeachsuchsectionuniquebyaddingattheendof it,inparentheses,thenameoftheoriginalauthororpublisherofthatsectionifknown,orelseauniquenumber.Makethesameadjustmenttothe sectiontitlesinthelistofInvariantSectionsinthelicensenoticeofthecombinedwork. Inthecombination,youmustcombineanysectionsEntitledHistoryinthevariousoriginaldocuments,formingonesectionEntitledHistory likewisecombineanysectionsEntitledAcknowledgements,andanysectionsEntitledDedications.YoumustdeleteallsectionsEntitled Endorsements. 7. COLLECTIONSOFDOCUMENTS YoumaymakeacollectionconsistingoftheDocumentandotherdocumentsreleasedunderthisLicense,andreplacetheindividualcopiesof thisLicenseinthevariousdocumentswithasinglecopythatisincludedinthecollection,providedthatyoufollowtherulesofthisLicensefor verbatimcopyingofeachofthedocumentsinallotherrespects. Youmayextractasingledocumentfromsuchacollection,anddistributeitindividuallyunderthisLicense,providedyouinsertacopyofthis Licenseintotheextracteddocument,andfollowthisLicenseinallotherrespectsregardingverbatimcopyingofthatdocument. 8. AGGREGATIONWITHINDEPENDENTWORKS AcompilationoftheDocumentoritsderivativeswithotherseparateandindependentdocumentsorworks,inoronavolumeofastorageor distributionmedium,iscalledanaggregateifthecopyrightresultingfromthecompilationisnotusedtolimitthelegalrightsofthe compilationsusersbeyondwhattheindividualworkspermit.WhentheDocumentisincludedinanaggregate,thisLicensedoesnotapplytothe otherworksintheaggregatewhicharenotthemselvesderivativeworksoftheDocument. IftheCoverTextrequirementofsection3isapplicabletothesecopiesoftheDocument,theniftheDocumentislessthanonehalfoftheentire aggregate,theDocumentsCoverTextsmaybeplacedoncoversthatbrackettheDocumentwithintheaggregate,ortheelectronicequivalentof coversiftheDocumentisinelectronicform.Otherwisetheymustappearonprintedcoversthatbracketthewholeaggregate. 9. TRANSLATION Translationisconsideredakindofmodification,soyoumaydistributetranslationsoftheDocumentunderthetermsofsection4.Replacing InvariantSectionswithtranslationsrequiresspecialpermissionfromtheircopyrightholders,butyoumayincludetranslationsofsomeorall InvariantSectionsinadditiontotheoriginalversionsoftheseInvariantSections.YoumayincludeatranslationofthisLicense,andallthelicense noticesintheDocument,andanyWarrantyDisclaimers,providedthatyoualsoincludetheoriginalEnglishversionofthisLicenseandthe originalversionsofthosenoticesanddisclaimers.IncaseofadisagreementbetweenthetranslationandtheoriginalversionofthisLicenseora noticeordisclaimer,theoriginalversionwillprevail. IfasectionintheDocumentisEntitledAcknowledgements,Dedications,orHistory,therequirement(section4)toPreserveitsTitle (section1)willtypicallyrequirechangingtheactualtitle. 10. TERMINATION Youmaynotcopy,modify,sublicense,ordistributetheDocumentexceptasexpresslyprovidedunderthisLicense.Anyattemptotherwiseto copy,modify,sublicense,ordistributeitisvoid,andwillautomaticallyterminateyourrightsunderthisLicense. However,ifyouceaseallviolationofthisLicense,thenyourlicensefromaparticularcopyrightholderisreinstated(a)provisionally,unlessand untilthecopyrightholderexplicitlyandfinallyterminatesyourlicense,and(b)permanently,ifthecopyrightholderfailstonotifyyouofthe violationbysomereasonablemeanspriorto60daysafterthecessation. Moreover,yourlicensefromaparticularcopyrightholderisreinstatedpermanentlyifthecopyrightholdernotifiesyouoftheviolationbysome reasonablemeans,thisisthefirsttimeyouhavereceivednoticeofviolationofthisLicense(foranywork)fromthatcopyrightholder,andyou curetheviolationpriorto30daysafteryourreceiptofthenotice. Terminationofyourrightsunderthissectiondoesnotterminatethelicensesofpartieswhohavereceivedcopiesorrightsfromyouunderthis
License.Ifyourrightshavebeenterminatedandnotpermanentlyreinstated,receiptofacopyofsomeorallofthesamematerialdoesnotgive youanyrightstouseit. 11. FUTUREREVISIONSOFTHISLICENSE TheFreeSoftwareFoundationmaypublishnew,revisedversionsoftheGNUFreeDocumentationLicensefromtimetotime.Suchnew versionswillbesimilarinspirittothepresentversion,butmaydifferindetailtoaddressnewproblemsorconcerns.See http://www.gnu.org/copyleft/. EachversionoftheLicenseisgivenadistinguishingversionnumber.IftheDocumentspecifiesthataparticularnumberedversionofthis Licenseoranylaterversionappliestoit,youhavetheoptionoffollowingthetermsandconditionseitherofthatspecifiedversionorofany laterversionthathasbeenpublished(notasadraft)bytheFreeSoftwareFoundation.IftheDocumentdoesnotspecifyaversionnumberofthis License,youmaychooseanyversioneverpublished(notasadraft)bytheFreeSoftwareFoundation.IftheDocumentspecifiesthataproxycan decidewhichfutureversionsofthisLicensecanbeused,thatproxyspublicstatementofacceptanceofaversionpermanentlyauthorizesyouto choosethatversionfortheDocument. 12. RELICENSING MassiveMultiauthorCollaborationSite(orMMCSite)meansanyWorldWideWebserverthatpublishescopyrightableworksandalso providesprominentfacilitiesforanybodytoeditthoseworks.Apublicwikithatanybodycaneditisanexampleofsuchaserver.AMassive MultiauthorCollaboration(orMMC)containedinthesitemeansanysetofcopyrightableworksthuspublishedontheMMCsite. CCBYSAmeanstheCreativeCommonsAttributionShareAlike3.0licensepublishedbyCreativeCommonsCorporation,anotforprofit corporationwithaprincipalplaceofbusinessinSanFrancisco,California,aswellasfuturecopyleftversionsofthatlicensepublishedbythat sameorganization. IncorporatemeanstopublishorrepublishaDocument,inwholeorinpart,aspartofanotherDocument. AnMMCiseligibleforrelicensingifitislicensedunderthisLicense,andifallworksthatwerefirstpublishedunderthisLicensesomewhere otherthanthisMMC,andsubsequentlyincorporatedinwholeorinpartintotheMMC,(1)hadnocovertextsorinvariantsections,and(2)were thusincorporatedpriortoNovember1,2008. TheoperatorofanMMCSitemayrepublishanMMCcontainedinthesiteunderCCBYSAonthesamesiteatanytimebeforeAugust1, 2009,providedtheMMCiseligibleforrelicensing.
ADDENDUM:HowtousethisLicenseforyourdocuments
TousethisLicenseinadocumentyouhavewritten,includeacopyoftheLicenseinthedocumentandputthefollowingcopyrightandlicensenotices justafterthetitlepage:
C o p y r i g h t( C ) y e a r y o u rn a m e . P e r m i s s i o ni sg r a n t e dt oc o p y ,d i s t r i b u t ea n d / o rm o d i f yt h i sd o c u m e n t u n d e rt h et e r m so ft h eG N UF r e eD o c u m e n t a t i o nL i c e n s e ,V e r s i o n1 . 3 o ra n yl a t e rv e r s i o np u b l i s h e db yt h eF r e eS o f t w a r eF o u n d a t i o n ; w i t hn oI n v a r i a n tS e c t i o n s ,n oF r o n t C o v e rT e x t s ,a n dn oB a c k C o v e r T e x t s . Ac o p yo ft h el i c e n s ei si n c l u d e di nt h es e c t i o ne n t i t l e d` ` G N U F r e eD o c u m e n t a t i o nL i c e n s e ' ' .
IfyouhaveInvariantSections,FrontCoverTextsandBackCoverTexts,replacethewithTexts.linewiththis:
w i t ht h eI n v a r i a n tS e c t i o n sb e i n gl i s tt h e i rt i t l e s ,w i t h t h eF r o n t C o v e rT e x t sb e i n gl i s t ,a n dw i t ht h eB a c k C o v e rT e x t s b e i n gl i s t .
AppendixDIndexes
BuiltinIndex: IndexofBashbuiltincommands. ReservedWordIndex: IndexofBashreservedwords. VariableIndex: Quickreferencehelpsyoufindthevariableyouwant. FunctionIndex: IndexofbindableReadlinefunctions. ConceptIndex: Generalindexforconceptsdescribedinthismanual. Next:ReservedWordIndex,Up:Indexes[Contents][Index]
D.1IndexofShellBuiltinCommands
Jumpto: .:[ ABCDEFGHJKLMPRSTUW
IndexEntry Section .
. :
BourneShellBuiltins
:
: :
BourneShellBuiltins
[
[ :
BourneShellBuiltins
A
a l i a s :
BashBuiltins
B
b g : b i n d : b r e a k : b u i l t i n :
C
c a l l e r : c d : c o m m a n d : c o m p g e n : c o m p l e t e : c o m p o p t : c o n t i n u e :
D
d e c l a r e : d i r s : d i s o w n :
E
e c h o : e n a b l e : e v a l : e x e c : e x i t : e x p o r t :
F
f c : f g :
BashHistoryBuiltins JobControlBuiltins
G
g e t o p t s :
BourneShellBuiltins
H
h a s h : h e l p : h i s t o r y :
J
j o b s :
JobControlBuiltins
K
k i l l :
JobControlBuiltins
l e t : l o c a l : l o g o u t :
M
m a p f i l e :
BashBuiltins
P
p o p d : p r i n t f : p u s h d : p w d :
R
r e a d : r e a d a r r a y : r e a d o n l y : r e t u r n :
S
s e t : s h i f t : s h o p t : s o u r c e : s u s p e n d :
T
t e s t : t i m e s : t r a p : t y p e : t y p e s e t :
U
u l i m i t : u m a s k : u n a l i a s : u n s e t :
W
w a i t :
JobControlBuiltins
D.2IndexofShellReservedWords
Jumpto: ![]{} CDEFISTUW IndexEntry Section !
! :
Pipelines
[
[ [ :
ConditionalConstructs
]
] ] :
ConditionalConstructs
{
{ :
CommandGrouping
}
} :
CommandGrouping
C
c a s e :
ConditionalConstructs
D
d o : d o n e :
LoopingConstructs LoopingConstructs
E
e l i f : e l s e : e s a c :
F
f i : f o r : f u n c t i o n :
I
i f : i n :
ConditionalConstructs ConditionalConstructs
S
s e l e c t :
ConditionalConstructs
T
t h e n : t i m e :
ConditionalConstructs Pipelines
U
u n t i l :
LoopingConstructs
W
w h i l e :
LoopingConstructs
D.3ParameterandVariableIndex
Jumpto: !#$*0?@_ ABCDEFGHIKLMOPRSTUV IndexEntry !
! :
Section
SpecialParameters
#
# :
SpecialParameters
$
$ :
SpecialParameters
*
* :
SpecialParameters
SpecialParameters
0
0 :
SpecialParameters
?
? :
SpecialParameters
@
@ :
SpecialParameters
_
_ :
SpecialParameters
A
a u t o _ r e s u m e :
JobControlVariables
B
B A S H : B A S H O P T S : B A S H P I D : B A S H _ A L I A S E S : B A S H _ A R G C : B A S H _ A R G V : B A S H _ C M D S : B A S H _ C O M M A N D : B A S H _ E N V : B A S H _ E X E C U T I O N _ S T R I N G : B A S H _ L I N E N O : B A S H _ R E M A T C H : B A S H _ S O U R C E : B A S H _ S U B S H E L L : B A S H _ V E R S I N F O : B A S H _ V E R S I O N : B A S H _ X T R A C E F D : b e l l s t y l e : b i n d t t y s p e c i a l c h a r s :
BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables ReadlineInitFileSyntax ReadlineInitFileSyntax
C
C D P A T H :
BourneShellVariables BashVariables c o m m e n t b e g i n : ReadlineInitFileSyntax c o m p l e t i o n d i s p l a y w i d t h : ReadlineInitFileSyntax c o m p l e t i o n i g n o r e c a s e : ReadlineInitFileSyntax c o m p l e t i o n m a p c a s e : ReadlineInitFileSyntax c o m p l e t i o n p r e f i x d i s p l a y l e n g t h : ReadlineInitFileSyntax c o m p l e t i o n q u e r y i t e m s : ReadlineInitFileSyntax C O M P R E P L Y : BashVariables C O M P _ C W O R D : BashVariables C O M P _ K E Y : BashVariables C O M P _ L I N E : BashVariables C O M P _ P O I N T : BashVariables C O M P _ T Y P E : BashVariables C O M P _ W O R D B R E A K S : BashVariables C O M P _ W O R D S : BashVariables c o n v e r t m e t a : ReadlineInitFileSyntax C O P R O C : BashVariables
C O L U M N S :
D
D I R S T A C K : d i s a b l e c o m p l e t i o n :
BashVariables ReadlineInitFileSyntax
E
e d i t i n g m o d e : E M A C S : e n a b l e k e y p a d : E N V : E U I D : e x p a n d t i l d e :
F
F C E D I T : F I G N O R E : F U N C N A M E : F U N C N E S T :
G
G L O B I G N O R E : G R O U P S :
BashVariables BashVariables
H
h i s t c h a r s : H I S T C M D : H I S T C O N T R O L : H I S T F I L E : H I S T F I L E S I Z E : H I S T I G N O R E : h i s t o r y p r e s e r v e p o i n t : h i s t o r y s i z e : H I S T S I Z E : H I S T T I M E F O R M A T : H O M E : h o r i z o n t a l s c r o l l m o d e : H O S T F I L E : H O S T N A M E : H O S T T Y P E :
BashVariables BashVariables BashVariables BashVariables BashVariables BashVariables ReadlineInitFileSyntax ReadlineInitFileSyntax BashVariables BashVariables BourneShellVariables ReadlineInitFileSyntax BashVariables BashVariables BashVariables
I
I F S : I G N O R E E O F : i n p u t m e t a : I N P U T R C : i s e a r c h t e r m i n a t o r s :
K
k e y m a p :
ReadlineInitFileSyntax
L
L A N G : L C _ A L L : L C _ C O L L A T E : L C _ C T Y P E : L C _ M E S S A G E S : L C _ M E S S A G E S : L C _ N U M E R I C : L I N E N O : L I N E S :
M
M A C H T Y P E : M A I L : M A I L C H E C K : M A I L P A T H : M A P F I L E : m a r k m o d i f i e d l i n e s : m a r k s y m l i n k e d d i r e c t o r i e s : m a t c h h i d d e n f i l e s : m e n u c o m p l e t e d i s p l a y p r e f i x : m e t a f l a g :
BashVariables BourneShellVariables BashVariables BourneShellVariables BashVariables ReadlineInitFileSyntax ReadlineInitFileSyntax ReadlineInitFileSyntax ReadlineInitFileSyntax ReadlineInitFileSyntax
O
O L D P W D : O P T A R G : O P T E R R : O P T I N D : O S T Y P E : o u t p u t m e t a :
P
p a g e c o m p l e t i o n s : P A T H : P I P E S T A T U S : P O S I X L Y _ C O R R E C T : P P I D : P R O M P T _ C O M M A N D : P R O M P T _ D I R T R I M : P S 1 : P S 2 : P S 3 : P S 4 : P W D :
ReadlineInitFileSyntax BourneShellVariables BashVariables BashVariables BashVariables BashVariables BashVariables BourneShellVariables BourneShellVariables BashVariables BashVariables BashVariables
R
R A N D O M : R E A D L I N E _ L I N E : R E A D L I N E _ P O I N T : R E P L Y : r e v e r t a l l a t n e w l i n e :
S
S E C O N D S : S H E L L : S H E L L O P T S : S H L V L : s h o w a l l i f a m b i g u o u s : s h o w a l l i f u n m o d i f i e d : s k i p c o m p l e t e d t e x t :
T
T E X T D O M A I N : T E X T D O M A I N D I R : T I M E F O R M A T : T M O U T : T M P D I R :
U
U I D :
BashVariables
V
v i s i b l e s t a t s :
ReadlineInitFileSyntax
D.4FunctionIndex
Jumpto: ABCDEFGHIKMNOPQRSTUY IndexEntry A
a b o r t( C g ) : a c c e p t l i n e( N e w l i n eo rR e t u r n ) : a l i a s e x p a n d l i n e( ) :
Section
B
b a c k w a r d c h a r( C b ) : b a c k w a r d d e l e t e c h a r( R u b o u t ) : b a c k w a r d k i l l l i n e( C xR u b o u t ) : b a c k w a r d k i l l w o r d( M D E L ) : b a c k w a r d w o r d( M b ) : b e g i n n i n g o f h i s t o r y( M < ) : b e g i n n i n g o f l i n e( C a ) :
C
c a l l l a s t k b d m a c r o( C xe ) : c a p i t a l i z e w o r d( M c ) : c h a r a c t e r s e a r c h( C ] ) : c h a r a c t e r s e a r c h b a c k w a r d( M C ] ) : c l e a r s c r e e n( C l ) : c o m p l e t e( T A B ) : c o m p l e t e c o m m a n d( M ! ) : c o m p l e t e f i l e n a m e( M / ) : c o m p l e t e h o s t n a m e( M @ ) : c o m p l e t e i n t o b r a c e s( M { ) : c o m p l e t e u s e r n a m e( M ~ ) : c o m p l e t e v a r i a b l e( M $ ) : c o p y b a c k w a r d w o r d( ) : c o p y f o r w a r d w o r d( ) : c o p y r e g i o n a s k i l l( ) :
KeyboardMacros CommandsForText MiscellaneousCommands MiscellaneousCommands CommandsForMoving CommandsForCompletion CommandsForCompletion CommandsForCompletion CommandsForCompletion CommandsForCompletion CommandsForCompletion CommandsForCompletion CommandsForKilling CommandsForKilling CommandsForKilling
D
d a b b r e v e x p a n d( ) : d e l e t e c h a r( C d ) : d e l e t e c h a r o r l i s t( ) : d e l e t e h o r i z o n t a l s p a c e( ) : d i g i t a r g u m e n t( M 0 ,M 1 ,M ) : d i s p l a y s h e l l v e r s i o n( C xC v ) : d o u p p e r c a s e v e r s i o n( M a ,M b ,M x , ) : d o w n c a s e w o r d( M l ) : d u m p f u n c t i o n s( ) : d u m p m a c r o s( ) : d u m p v a r i a b l e s( ) : d y n a m i c c o m p l e t e h i s t o r y( M T A B ) :
CommandsForCompletion CommandsForText CommandsForCompletion CommandsForKilling NumericArguments MiscellaneousCommands MiscellaneousCommands CommandsForText MiscellaneousCommands MiscellaneousCommands MiscellaneousCommands CommandsForCompletion
E
e d i t a n d e x e c u t e c o m m a n d( C x C e ) :
MiscellaneousCommands
e n d k b d m a c r o( C x) ) : e n d o f h i s t o r y( M > ) : e n d o f l i n e( C e ) : e x c h a n g e p o i n t a n d m a r k( C xC x ) :
F
f o r w a r d b a c k w a r d d e l e t e c h a r( ) : f o r w a r d c h a r( C f ) : f o r w a r d s e a r c h h i s t o r y( C s ) : f o r w a r d w o r d( M f ) :
G
g l o b c o m p l e t e w o r d( M g ) : g l o b e x p a n d w o r d( C x* ) : g l o b l i s t e x p a n s i o n s( C xg ) :
H
h i s t o r y a n d a l i a s e x p a n d l i n e( ) : h i s t o r y e x p a n d l i n e( M ^ ) : h i s t o r y s e a r c h b a c k w a r d( ) : h i s t o r y s e a r c h f o r w a r d( ) :
I
i n s e r t c o m m e n t( M # ) : i n s e r t c o m p l e t i o n s( M * ) : i n s e r t l a s t a r g u m e n t( M .o rM _ ) :
K
k i l l l i n e( C k ) : k i l l r e g i o n( ) : k i l l w h o l e l i n e( ) : k i l l w o r d( M d ) :
M
m a g i c s p a c e( ) : m e n u c o m p l e t e( ) : m e n u c o m p l e t e b a c k w a r d( ) :
N
n e x t h i s t o r y( C n ) :
O
o p e r a t e a n d g e t n e x t( C o ) : o v e r w r i t e m o d e( ) :
MiscellaneousCommands CommandsForText
P
p o s s i b l e c o m m a n d c o m p l e t i o n s( C x! ) : p o s s i b l e c o m p l e t i o n s( M ? ) : p o s s i b l e f i l e n a m e c o m p l e t i o n s( C x/ ) : p o s s i b l e h o s t n a m e c o m p l e t i o n s( C x@ ) : p o s s i b l e u s e r n a m e c o m p l e t i o n s( C x~ ) : p o s s i b l e v a r i a b l e c o m p l e t i o n s( C x$ ) : p r e f i x m e t a( E S C ) : p r e v i o u s h i s t o r y( C p ) :
Q
q u o t e d i n s e r t( C qo rC v ) :
CommandsForText
r e r e a d i n i t f i l e( C xC r ) : r e d r a w c u r r e n t l i n e( ) : r e v e r s e s e a r c h h i s t o r y( C r ) : r e v e r t l i n e( M r ) :
S
s e l f i n s e r t( a ,b ,A ,1 ,! , ) : s e t m a r k( C @ ) : s h e l l b a c k w a r d k i l l w o r d( ) : s h e l l b a c k w a r d w o r d( ) : s h e l l e x p a n d l i n e( M C e ) : s h e l l f o r w a r d w o r d( ) : s h e l l k i l l w o r d( ) : s k i p c s i s e q u e n c e( ) : s t a r t k b d m a c r o( C x( ) :
T
t i l d e e x p a n d( M & ) : t r a n s p o s e c h a r s( C t ) : t r a n s p o s e w o r d s( M t ) :
U
u n d o( C _o rC xC u ) : u n i v e r s a l a r g u m e n t( ) : u n i x f i l e n a m e r u b o u t( ) : u n i x l i n e d i s c a r d( C u ) : u n i x w o r d r u b o u t( C w ) : u p c a s e w o r d( M u ) :
Y
y a n k( C y ) : y a n k l a s t a r g( M .o rM _ ) : y a n k n t h a r g( M C y ) : y a n k p o p( M y ) :
D.5ConceptIndex
Jumpto: ABCDEFHIJKLMNOPQRSTVWY IndexEntry A aliasexpansion: arithmeticevaluation: arithmeticexpansion: arithmetic,shell: arrays: B background: Bashconfiguration: Bashinstallation: Bourneshell: braceexpansion: builtin: C JobControlBasics BasicInstallation BasicInstallation BasicShellFeatures BraceExpansion Definitions Aliases ShellArithmetic ArithmeticExpansion ShellArithmetic Arrays Section
commandediting: commandexecution: commandexpansion: commandhistory: commandsearch: commandsubstitution: commandtiming: commands,compound: commands,conditional: commands,grouping: commands,lists: commands,looping: commands,pipelines: commands,shell: commands,simple: comments,shell: completionbuiltins: configuration: controloperator: coprocess: D directorystack: E editingcommandlines: environment: evaluation,arithmetic: eventdesignators: executionenvironment: exitstatus: exitstatus: expansion: expansion,arithmetic: expansion,brace: expansion,filename: expansion,parameter: expansion,pathname: expansion,tilde: expressions,arithmetic: expressions,conditional: F field: filename: filenameexpansion: foreground: functions,shell: H historybuiltins: historyevents: historyexpansion: historylist: History,howtouse: I identifier: initializationfile,readline: installation:
ReadlineBareEssentials CommandSearchandExecution SimpleCommandExpansion BashHistoryFacilities CommandSearchandExecution CommandSubstitution Pipelines CompoundCommands ConditionalConstructs CommandGrouping Lists LoopingConstructs Pipelines ShellCommands SimpleCommands Comments ProgrammableCompletionBuiltins BasicInstallation Definitions Coprocesses
TheDirectoryStack
ReadlineBareEssentials Environment ShellArithmetic EventDesignators CommandExecutionEnvironment Definitions ExitStatus ShellExpansions ArithmeticExpansion BraceExpansion FilenameExpansion ShellParameterExpansion FilenameExpansion TildeExpansion ShellArithmetic BashConditionalExpressions
interaction,readline: interactiveshell: interactiveshell: internationalization: J job: jobcontrol: jobcontrol: K killring: killingtext: L localization: loginshell: M matching,pattern: metacharacter: N name: nativelanguages: notation,readline: O operator,shell: P parameterexpansion: parameters: parameters,positional: parameters,special: pathnameexpansion: patternmatching: pipeline: POSIX: POSIXMode: processgroup: processgroupID: processsubstitution: programmablecompletion: prompting: Q quoting: quoting,ANSI: R Readline,howtouse: redirection: reservedword: restrictedshell: returnstatus: S shellarithmetic: shellfunction:
ReadlineKillingCommands ReadlineKillingCommands
LocaleTranslation InvokingBash
PatternMatching Definitions
Definitions
ShellParameterExpansion ShellParameters PositionalParameters SpecialParameters FilenameExpansion PatternMatching Pipelines Definitions BashPOSIXMode Definitions Definitions ProcessSubstitution ProgrammableCompletion PrintingaPrompt
Quoting ANSICQuoting
ShellArithmetic ShellFunctions
tildeexpansion: TildeExpansion token: Definitions translation,nativelanguages: LocaleTranslation V variable,shell: variables,readline: W word: wordsplitting: Y yankingtext: ReadlineKillingCommands Definitions WordSplitting ShellParameters ReadlineInitFileSyntax
Jumpto: ABCDEFHIJKLMNOPQRSTVWY