Learning the bash Shell — Unix Shell Programming


Чтобы посмотреть этот PDF файл с форматированием и разметкой, скачайте его и откройте на своем компьютере.
LearningthebashShell,
O'Reilly Media, Inc.
13
1
LearningthebashShell,
Chapter12.bashfor
Thefirst10chaptersofthisbooklookedatnearlyall
aspectsof
,fromnavigatingthefilesystemand
editingthecommand-linetowritingshellscriptsand
functionsusinglesser-knownfeaturesoftheshell.Thisis
allverywellandgood,butwhatifyouhaveanold
versionof
andwantthenewfeaturesshowninthis
;otherwise,you'llhaveto
homepageislocatedat
software/bash/bash.html
andyoucanfindtheverylatest
Thisbookisrelevanttoallversionsof
,although
olderversionslacksomeofthefeaturesofthemost
recentversion.
1]Youcaneasilyfindoutwhichversion
youareusingbytyping
echo$BASH_VERSION
.The
earliestpublicversionof
was1.0,andthemost
recentis3.0(releasedinJuly2004).Ifyouhaveanolder
version,youmightliketoupgradetothelatestone.
1]Throughoutthisbookwehaveclearlymarkedwith
footnotesthefeaturesthatarenotpresentintheearlier
Summaryofbash
isabackward-compatibleevolutionarysuccessorto
theBourneshellthatincludesmostoftheCshell'smajor
advantagesaswellasfeaturesfromtheKornshellanda
fewnewfeaturesofitsown.Featuresappropriatedfrom
theC shell include:
¥Directorymanipulation,withthe
¥Jobcontrol,includingthe
¥Brace expansion, for generating arbitrary strings.
¥Tildeexpansion,ashorthandwaytoreferto
¥Aliases,whichallowyoutodefineshorthand
Chapter1.bash Basics
Sincetheearly1970s,whenitwasfirstcreated,the
UNIXoperatingsystemhasbecomemoreandmore
popular.Duringthistimeithasbranchedoutinto
differentversions,andtakenonsuchnamesasUltrix,
AIX,Xenix,SunOS,andLinux.Startingon
minicomputersandmainframes,ithasmovedonto
desktopworkstationsandevenpersonalcomputersused
atworkandhome.Nolongerasystemusedonlyby
academicsandcomputingwizardsatuniversitiesand
researchcenters,UNIXisusedinmanybusinesses,
schools,andhomes.Astimegoeson,morepeoplewill
YoumayhaveusedUNIXatyourschool,office,orhome
torunyourapplications,printdocuments,andreadyour
electronicmail.Buthaveyoueverthoughtaboutthe
processthathappenswhenyoutypeacommandandhit
ThisbookisdesignedtoaddresscasualUNIXandLinux
userswhoarejustabovethe"rawbeginner"level.You
shouldbefamiliarwiththeprocessofloggingin,entering
commands,anddoingsimplethingswithfiles.Although
Chapter1
reviewsconceptssuchasthetree-likefileand
directoryscheme,youmayfindthatitmovestooquickly
makeyouamoreproductive
userÑfrommajor
Chapter4.BasicShell
Ifyouhavebecomefamiliarwiththecustomization
techniqueswepresentedinthepreviouschapter,you
haveprobablyrunintovariousmodificationstoyour
Thisbookisfullofexamplesofshellcommandsand
programsdesignedtobeusefulinyoureverydaylifeasa
user,notjusttoillustratethefeaturebeingexplained.In
Chapter4
andonwards,weincludevariousprogramming
problems,whichwecall
,thatillustrateparticular
shellprogrammingconcepts.Sometaskshavesolutions
thatarerefinedinsubsequentchapters.Thelaterchapters
alsoincludeprogrammingexercises,manyofwhichbuild
Feelfreetouseanycodeyouseeinthisbookandtopass
italongtofriendsandcolleagues.Weespecially
Ifyouwanttotryexamplesbutyoudon'tuse
yourloginshell,youmustputthefollowinglineatthe
isn'tinstalledasthefile
/bin/bash
,substituteits
Chapter2.Command-Line
It'salwayspossibletomakemistakeswhenyoutypeata
computerkeyboard,butperhapsevenmoresowhenyou
areusingaUNIXshell.UNIXshellsyntaxispowerful,
Chapter3.Customizing
isacollectionofconceptsthatexpress
Ifyouwanttoinvestigatespecifictopicsratherthanread
theentirebookthrough,hereisachapter-by-chapter
Chapter1
andtellsyouhowtoinstallit
asyourloginshell.Thenitsurveysthebasicsof
interactiveshelluse,includingoverviewsoftheUNIX
fileanddirectoryscheme,standardI/O,andbackground
Chapter2
discussestheshell'scommandhistory
mechanism(includingthe
-and
-editingmodes),
historysubstitutionandthe
historycommand,andkey
Chapter3
coverswaystocustomizeyourshell
environmentwithoutprogrammingbyusingthestartup
andenvironmentfiles.Aliases,options,andshell
Chapter4
isanintroductiontoshellprogramming.It
explainsthebasicsofshellscriptsandfunctions,and
discussesseveralimportant"nuts-and-bolts"
programmingfeatures:stringmanipulationoperators,
braceexpansion,command-linearguments(positional
ConventionsUsedin
Weleaveitasunderstoodthatwhenyouenterashell
We'dLiketoHearfrom
Pleaseaddresscommentsandquestionsconcerningthis
Wehaveawebpageforthisbook,wherewelisterrata,
examples,andanyadditionalinformation.Youcan
Tocommentorasktechnicalquestionsaboutthisbook,
Formoreinformationaboutourbooks,conferences,
Using Code Examples
Safari Enabled
WhenyouseeaSafari¨Enabledicononthecoverof
yourfavoritetechnologybook,thatmeansthebookis
Acknowledgmentsfor
Thisprojecthasbeenaninterestingexperienceand
wouldn'thavebeenpossiblewithoutthehelpofanumber
Acknowledgmentsfor
ThankstoallthepeopleatO'Reilly.GigiEstabrookwas
theeditorforthesecondedition.NicoleGipsonArigo
wastheproductioneditorandprojectmanager.Nancy
WolfeKotaryandEllieFountainMadenperformed
Acknowledgmentsfor
ThankstotheproductionpeopleatO'Reillyandtothe
Preface
bash Versions
Summary of bash Features
1. bash Basics
3
Theshell'sjob,then,istotranslatetheuser'scommand
linesintooperatingsysteminstructions.Forexample,
Thismeans,"Sortlinesinthefile
innumerical
order,andputtheresultinthefile
1.Breaksupthelineintothepieces
,and
.Thesepieces
Chapter6.Command-Line
OptionsandTyped
Youshouldhaveahealthygraspofshellprogramming
techniquesnowthatyouhavegonethroughtheprevious
chapters.Whatyouhavelearneduptothispointenables
youtowritemanynon-trivial,usefulshellscriptsand
Still,youmayhavenoticedsomeremaininggapsinthe
knowledgeyouneedtowriteshellcodethatbehaveslike
theUNIXcommandsyouareusedto.Inparticular,ifyou
areanexperiencedUNIXuser,itmighthaveoccurredto
youthatnoneoftheexamplescriptsshownsofarhave
theabilitytohandle
precededbyadash(
)onthe
commandline.Andifyouprograminaconventional
languagelikeCorPascal,youwillhavenoticedthatthe
onlytypeofdatathatwehaveseeninshellvariablesis
Chapter7.Input/Output
andCommand-Line
Chapter8.Process
TheUNIXoperatingsystembuiltitsreputationona
Chapter9.Debugging
Wehopethatwehaveconvincedyouthat
canbe
usedasaseriousUNIXprogrammingenvironment.It
developcodewith,say,the
editorandthe
Butwhataboutprogrammingsupporttoolsfor
?Of
course,youcanuseanyeditoryoulike,including
Inthisbookyouwilllearnabout
,whichisoneof
themostrecentandpowerfulofthemajorUNIXshells.
Therearetwowaystouse
:asauserinterfaceandas
Thischapterandthenextcoverinteractiveuse.Thesetwo
chaptersshouldgiveyouenoughbackgroundtousethe
shellconfidentlyandproductivelyformostofyour
Afteryouhavebeenusingtheshellforawhile,youwill
undoubtedlyfindcertaincharacteristicsofyour
environment(theshell's"lookandfeel")thatyouwould
liketochange,andtasksthatyouwouldliketoautomate.
Chapter3
alsopreparesyouforshellprogramming,the
bulkofwhichiscoveredin
Chapter4
Chapter6
Youneednothaveanyprogrammingexperienceto
understandthesechaptersandlearnshellprogramming.
Chapter7
Chapter8
TheindependenceoftheshellfromtheUNIXoperating
perse
hasledtothedevelopmentofdozensof
shellsthroughoutUNIXhistoryÑalthoughonlyafew
ThefirstmajorshellwastheBourneshell(namedafterits
inventor,StevenBourne);itwasincludedinthefirst
popularversionofUNIX,Version7,startingin1979.
TheBourneshellisknownonthesystemas
.Although
UNIXhasgonethroughmany,manychanges,theBourne
shellisstillpopularandessentiallyunchanged.Several
ThefirstwidelyusedalternativeshellwastheCshell,or
.ThiswaswrittenbyBillJoyattheUniversityof
CaliforniaatBerkeleyaspartoftheBerkeleySoftware
Distribution(BSD)versionofUNIXthatcameouta
AppendixA.Related
importantfeatures(e.g.,aliases;see
Chapter3
)thatmake
Inrecentyearsanumberofothershellshavebecome
popular.ThemostnotableoftheseistheKornshell.This
shellisacommercialproductthatincorporatesthebest
featuresoftheBourneandCshells,plusmanyfeaturesof
itsown.
1]TheKornshellissimilarto
inmost
respects;bothhaveanabundanceoffeaturesthatmake
themeasytoworkwith.Theadvantageof
isthatit
isfree.ForfurtherinformationontheKornshellsee
TheBourneAgainshell(namedinpunningtributeto
SteveBourne'sshell)wascreatedforuseintheGNU
2]TheGNUprojectwasstartedbyRichard
StallmanoftheFreeSoftwareFoundation(FSF)forthe
purposeofcreatingaUNIX-compatibleoperatingsystem
andreplacingallofthecommercialUNIXutilitieswith
freelydistributableones.GNUembodiesnotonlynew
softwareutilities,butanewdistributionconcept:the
.Copyleftedsoftwaremaybefreelydistributedso
longasnorestrictionsareplacedonfurtherdistribution
(forexample,thesourcecodemustbemadefreely
,intendedtobethestandardshellfortheGNU
system,wasofficially"born"onSunday,January10,
AlthoughtheBourneshellisstillknownasthe"standard"
isbecomingincreasinglypopular.Inaddition
toitsBourneshellcompatibility,itincludesthebest
featuresoftheCandKornshellsaswellasseveral
'scommand-lineeditingmodesarethefeaturesthat
tendtoattractpeopletoitfirst.Withcommand-line
editing,it'smucheasiertogobackandfixmistakesor
modifypreviouscommandsthanitiswiththeCshell's
Chapter11.Shell
Forthemajorityofthisbook,we'velookedatthevarious
elementsthatmakeup
andhowyoucanusethemin
writingshellscripts.Ifyou'veusedotherprogramming
languagesyouwillknowthatthereisadifference
of
bash
45
Whenyouusetheshellinteractively,youengageina
loginsessionthatbeginswhenyouloginandendswhen
youtype
orpressCTRL-D.
5]Duringa
loginsession,youtypein
commandlines
totheshell;
Althoughargumentstocommandsaren'talwaysfiles,
filesarethemostimportanttypesof"things"onany
UNIXsystem.Afilecancontainanykindofinformation,
andindeedtherearedifferenttypesoffiles.Threetypes
Alsocalledtextfiles;thesecontainreadable
characters.Forexample,thisbookwascreatedfrom
severalregularfilesthatcontainthetextofthebook
plushuman-readableformattinginstructionstothe
Alsocalledprograms;theseareinvokedas
commands.Somecan'tbereadbyhumans;
othersÑtheshellscriptsthatwe'llexamineinthis
bookÑarejustspecialtextfiles.Theshellitselfisa
Thesearelikefoldersthatcontainother
filesÑpossiblyotherdirectories(called
Directories
Figure1-2.A tree of directories and files
Filenames,Wildcards,and
Aconceptcloselyrelatedtopathnameexpansionisbrace
expansion.Whereaspathnameexpansionwildcardswill
expandtofilesanddirectoriesthatexist,braceexpansion
expandstoanarbitrarystringofagivenform:anoptional
ThesoftwarefieldÑreally,anyscientificfieldÑtendsto
advancemostquicklyandimpressivelyonthosefew
occasionswhensomeone(i.e.,notacommittee)comesup
I/O Redirection
cat
Itisalsopossibletoredirecttheoutputofacommand
intothestandardinputofanothercommandinsteadofa
file.Theconstructthatdoesthisiscalledthepipe,notated
.Acommandlinethatincludestwoormore
Pipesareveryoftenusedwiththe
command,which
worksjustlike
exceptthatitprintsitsoutputscreen
byscreen,pausingfortheusertotypeSPACE(next
Pipesareactuallyaspecialcaseofamoregeneral
feature:doingmorethanonethingatatime.Thisisa
capabilitythatmanyothercommercialoperatingsystems
don'thave,becauseoftherigidlimitsthattheytendto
imposeuponusers.UNIX,ontheotherhand,was
developedinaresearchlabandmeantforinternaluse,so
itdoesrelativelylittletoimposelimitsontheresources
availabletousersonacomputerÑasusual,leaning
towardsunclutteredsimplicityratherthan
"Doingmorethanonethingatatime"meansrunning
morethanoneprogramatthesametime.Youdothis
whenyouinvokeapipeline;youcanalsodoitbylogging
ontoaUNIXsystemasmanytimessimultaneouslyas
youwish.(IfyoutrythatonanIBM'sVM/CMSsystem,
Youcancheckonbackgroundjobswiththecommand
.Foreachbackgroundjob,
printsalinesimilar
Whenthejobfinishes,youwillseeamessagelikethis
Themessagechangesifyourbackgroundjobterminated
BackgroundJobsand
Backgroundjobscansaveyoualotofthumb-twiddling
time.Justrememberthatsuchjobseatuplotsofsystem
resourceslikememoryandtheprocessor(CPU).Just
becauseyou'rerunningseveraljobsatoncedoesn'tmean
thattheywillrunfasterthantheywouldifrun
sequentiallyÑinfact,performanceisusuallyslightly
Everyjobonthesystemisassigneda
,anumber
thattellstheoperatingsystemhowmuchprioritytogive
thejobwhenitdolesoutresources(thehigherthe
number,thelowerthepriority).Commandsthatyouenter
SpecialCharactersand
Thecharacters
,and
arefourexamplesof
thathaveparticularmeaningstotheshell.The
wildcardswesawearlierinthischapter(
,and
...])are also special characters.Table1-6
givesthemeaningsofallspecialcharacters
withinshellcommandlinesonly.Othercharactershave
specialmeaningsinspecificsituations,suchasthe
regularexpressionsandstring-handlingoperatorsthat
Table1-6.Special characters
CharacterMeaning
Commandsubstitution
Chapter5.Flow Control
Ifyouareaprogrammer,youmayhavereadthelast
CharacterMeaning
Anotherwaytochangethemeaningofacharacteristo
precedeitwithabackslash(\).Thisiscalled
thecharacter.Inmostcases,when
youbackslash-escapeacharacter,youquoteit.For
willproducethesameresultsasifyousurroundedthe
stringwithsinglequotes.Tousealiteralbackslash,just
surrounditwithquotes('
Youcanalsouseabackslashtoincludedoublequotes
However,thiswon'tworkwithsinglequotesinside
quotedexpressions.Forexample,
`Hatter\'stea
party'willnotgiveyou
Hatter'steaparty
Arelatedissueishowtocontinuethetextofacommand
beyondasinglelineonyourterminalorworkstation
window.Theanswerisconceptuallysimple:justquote
ControlkeysÑthosethatyoutypebyholdingdownthe
CONTROL(orCTRL)keyandhittinganotherkeyÑare
anothertypeofspecialcharacter.Thesenormallydon't
printanythingonyourscreen,buttheoperatingsystem
1.1. What Is a Shell?
1.2. Scope of This Book
1.3.1. The Bourne Again Shell
Afeaturein
thatnoothershellhasisanonlinehelp
system.The
commandgivesinformationon
commandsin
.Ifyoutype
Chapter10.bash
Therearetwoareasinwhichsystemadministratorsuse
initiallystartsinteractivelywithemacs-modeasthe
default(unlessyouhavestarted
withthe
2]seeChapter10
).Therearetwowaystoenter
eithereditingmodewhileintheshell.First,youcanuse
Allof
'scommandhistoryfacilitiesdependonalist
thatrecordscommandsasyoutypethemintotheshell.
Wheneveryouloginorstartanotherinteractiveshell,
readsaninitialhistorylistfromthefile
inyourhomedirectory.Fromthatpointon,
interactivesessionmaintainsitsownlistof
commands.Whenyouexitfromashell,itsavesthelistin
.Youcancallthisfilewhateveryoulikeby
Ifyouarean
user,youwillfinditmostusefulto
thinkof
editingmodeasasimplified
witha
single,one-linewindow.Allofthebasiccommandsare
-modeusescontrolkeysforthemostbasicediting
functions.Ifyouaren'tfamiliarwith
,youcanthink
oftheseasextensionsoftherudimentary"erase"
character(usuallyBACKSPACEorDEL)thatUNIX
providesthroughitsinterfacetousers'terminals.Forthe
sakeofconsistency,we'llassumeyourerasecharacteris
Word Commands
Therearestillmoreefficientwaysofmovingarounda
commandlineinemacs-mode.Afewcommandsdeal
with the entire line; they areshown in
Table2-3.emacs-mode line commands
CommandDescription
CTRL-AMove to beginning of line
CTRL-EMove to end of line
CTRL-KKill forward to end of line
UsingCTRL-A,CTRL-E,andCTRL-Kshouldbe
straightforward.RememberthatCTRL-Ywillalways
MovingAroundinthe
Miscellaneous Commands
Likeemacs-mode,vi-modeessentiallycreatesaone-line
editingwindowintothehistorylist.vi-modeispopular
isthemoststandardUNIXeditor.Butthe
functionforwhich
wasdesigned,writingCprograms,
hasdifferenteditingrequirementsfromthoseof
SimpleControlMode
Afullrangeof
editingcommandsareavailabletoyou
incontrolmode.Thesimplestofthesemoveyouaround
thecommandlineandaresummarizedin
Table2-8
vi-modecontainstwo"word"concepts.Thesimplestis
anysequenceofnon-blankcharacters;we'llcallthisa
non-blankword
.Theotherisanysequenceofonly
Nowthatyouknowhowtoentercontrolmodeandmove
aroundonthecommandline,youneedtoknowhowto
MovingAroundinthe
Thenextgroupof
controlmodecommandswecover
allowsyoutomovearoundinandsearchyourcommand
Therearesomeadditionalmotioncommandsinvi-mode,
althoughtheyarelessusefulthantheoneswesawearlier
inthechapter.Thesecommandsallowyoutomovetothe
positionofaparticularcharacterintheline.Theyare
summarizedin
Table2-13
,inwhich
denotesany
Allofthesecommandscanbeprecededbyarepeat
Table2-13.vi-mode character-finding commands
CommandDescription
fxMove right to next occurrence of x
FxMove left to previous occurrence of x
and,originally,intheTOPS-20operatingsystem
Severalmiscellaneouscommandsroundoutvi-mode;
someofthemarequiteesoteric.Theyarelistedin
Table2-14.Miscellaneous vi-mode commands
CommandDescription
Invert(twiddle)caseofcurrent
Appendlastwordofpreviouscommand,
Clearthescreenandredrawthecurrent
lineonit;goodforwhenyourscreen
(commentcharacter)totheline
andsendittothehistorylist;usefulfor
The fc Command
fc
IfyouareaCshelluser,youmaybefamiliarwiththe
historyexpansionmechanismthatitprovides.
'scommand-lineeditinginterfaceis
.Itis
actuallyalibraryofsoftwaredevelopedfortheGNU
projectthatcanbeusedbyapplicationsrequiringa
text-basedinterface.Itprovideseditingand
text-manipulationfeaturestomakeiteasierfortheuserto
enterandedittext.Justasimportantly,itallows
standardization,intermsofbothkeystrokesand
Thedefaultstartupfileiscalled
andmustexistin
yourhomedirectoryifyouwishtocustomize
Ifyouwanttotryoutkeybindingsoryouwanttosee
Inthischapterwehaveseenthat
command-lineeditingwithtwomodes:
Youmaybewonderingwhythesetwoeditorswere
chosen.Theprimaryreasonisbecause
themostwidelyusededitorsforUNIX.Peoplewhohave
Ifyouarenotfamiliarwitheitheroftheseeditors,you
shouldseriouslyconsideradoptingemacs-modekeyboard
habits.Becauseitisbasedoncontrolkeysanddoesn't
requireyoutothinkintermsofa"commandmode"and
"insertmode,"youwillfindemacs-modeeasierto
assimilate.Althoughthefull
isanextremely
powerfuleditor,itscommandstructurelendsitselfvery
1.10. Help
2. Command-Line Editing
2.1. Enabling Command-Line Editing
2.2. The History List
2.3.1. Basic Commands
behavioraccordingtothevaluesstoredinthe
Althoughthesefeaturesarenottheonlyonesavailable,
theyformthebasisfordoingmoreadvanced
customization.Theyarealsothefeaturesthatare
commontothevariousshellsavailableonUNIX.Later
chapterswillcovermoreadvancedshellfeatures,suchas
The.bash_profile,
.bash_logout,and
Threefilesinyourhomedirectoryhaveaspecial
meaningto
IfyouhaveusedUNIXforanylengthoftimeyouwill
havenoticedthattherearemanycommandsavailableand
Options
AppendixB.Reference
TableB-1
TableB-2
listtheoptionsyoucanuse
wheninvokingcurrentversionsof
andtheolder1.
version,respectively.
1]Themulticharacteroptionsmust
appearonthecommandlinebeforethesingle-character
options.Inadditiontothese,any
Thereareseveralotheroptions(21inall;
AppendixB
liststhem).Tocheckthestatusofanoption,justtype
Thereareseveralcharacteristicsofyourenvironmentthat
youmaywanttocustomizebutthatcannotbeexpressed
asanon/offchoice.Characteristicsofthistypeare
specifiedinshellvariables.Shellvariablescanspecify
everythingfromyourpromptstringtohowoftentheshell
Likeanalias,ashellvariableisanamethathasavalue
associatedwithit.
keepstrackofseveralbuilt-in
shellvariables;shellprogrammerscanaddtheirown.By
convention,built-invariablesshouldhavenamesinall
Noticethatweuseddoublequotesaroundvariables(and
stringscontainingthem)inthese
examples.In
Chapter1
,wesaidthatsomespecialcharactersinside
Aswithoptions,somebuilt-inshellvariablesare
meaningfultogeneralUNIXusers,whileothersare
arcanaforhackers.We'lllookatthemoregenerally
usefuloneshere,andwe'llsavesomeofthemoreobscure
onesforlaterchapters.Again,
AppendixB
containsa
Customizationand
Someofthevariablesdiscussedaboveareusedby
commandsyoumayrunÑasopposedtotheshell
oraninteractiveshell.Ifthesubprocessisa
program,thenit'spossibletopropagatenearlyeverytype
ofthingwe'veseeninthischapterÑoptionsand
Bydefault,onlyonekindofthingisknowntoallkindsof
subprocesses:aspecialclassofshellvariablescalled
environmentvariables
.Someofthebuilt-invariableswe
haveseenareactuallyenvironmentvariables:
Itshouldbeclearwhytheseandothervariablesneedto
beknownbysubprocesses.Forexample,texteditorslike
needtoknowwhatkindofterminalyouare
using;theenvironmentvariable
istheirwayof
Althoughenvironmentvariableswillalwaysbeknownto
subprocesses,theshellmustbeexplicitlytoldwhich
othervariables,options,aliases,andsoon,aretobe
communicatedtosubprocesses.Thewaytodothisisto
putallsuchdefinitionsintothe
environmentfile
defaultenvironmentfileisthe
filethatwe
Remember,ifyoutakeyourdefinitionsoutof
andputthemin
,youwillhaveto
havetheline
source.bashrc
attheendofyour
sothatthedefinitionsbecomeavailableto
TheideaoftheenvironmentfilecomesfromtheCshell's
file.Thisisreflectedinthechoiceofthename
.The
suffixforinitializationfilesispractically
24]Asageneralrule,youshouldputasfewdefinitionsas
possiblein
andasmanyaspossibleinyour
environmentfile.Becausedefinitionsaddtoratherthan
takeawayfromanenvironment,thereislittlechancethat
Youshouldfeelfreetotryanyofthetechniques
presentedinthischapter.Thebeststrategyistotest
3.1.The.bash_profile,.bash_logout,and.bashrc
occasionalprogrammingproblems,called
,whose
ShellScriptsand
(afilethatcontainsshellcommands)isashell
program.Your
andenvironmentfiles,
Youcancreateascriptusingthetexteditorofyour
choice.Onceyouhavecreatedone,therearetwowaysto
runit.One,whichwehavealreadycovered,istotype
.Thiscausesthecommandsinthe
Thesecondwaytorunascriptissimplytotypeitsname
respectively.Fornow,justbearinmindthatascript
featureisanexpandedversionofasimilar
facilityintheSystemVBourneshellandafewother
shells.Afunctionissortofascript-within-a-script;you
useittodefinesomeshellcodebynameandstoreitin
Functionsimprovetheshell'sprogrammability
significantly,fortwomainreasons.First,whenyou
invokeafunction,itisalreadyintheshell'smemory;
thereforeafunctionrunsfaster.Moderncomputershave
plentyofmemory,sothereisnoneedtoworryaboutthe
amountofspaceatypicalfunctiontakesup.Forthis
reason,mostpeopledefineasmanycommonlyused
functionsaspossibleratherthankeeplotsofscripts
Theotheradvantageoffunctionsisthattheyareidealfor
organizinglongshellscriptsintomodular"chunks"of
codethatareeasiertodevelopandmaintain.Ifyouaren't
aprogrammer,askonewhatlifewouldbelikewithout
functions(alsocalled
inother
derivesmuchofitsprogrammingfunctionalityfrom
shellvariables.We'vealreadyseenthebasicsof
variables.Torecapbriefly:theyarenamedplacestostore
data,usuallyintheformofcharacterstrings,andtheir
valuescanbeobtainedbyprecedingtheirnameswith
dollarsigns($).Certainvariables,called
"isasinglestringthatconsistsofallofthepositional
statementinsideafunctiondefinitionmakesthe
variablesinvolvedallbecome
tothatfunction.The
abilitytodefinevariablesthatarelocalto"subprogram"
Quoting with [email protected] and $*
Beforeweshowthemanythingsyoucandowithshell
variables,wehavetopointoutasimplificationwehave
beenmaking:thesyntaxof
fortakingthevalue
ofavariableisactuallythesimpleformofthemore
Whytwosyntaxes?Foronething,themoregeneral
syntaxisnecessaryifyourcodereferstomorethannine
String Operators
PatternsandPattern
We'llcontinuerefiningoursolutiontoTask4-1laterin
thischapter.Thenexttypeofstringoperatorisusedto
matchportionsofavariable'sstringvalueagainst
.Patterns,aswesawin
Chapter1
,arestringsthat
cancontainwildcardcharacters(
,and
forcharacter
Thereisoneremainingoperatoronvariables.Itis
Extended Pattern Matching
Fromthediscussionsofar,we'veseentwowaysof
AdvancedExamples:
Wewillconcludethischapterwithacoupleoffunctions
thatarealreadybuiltinto
butareusefulin
demonstratingsomeoftheconceptswehavecoveredin
14]Task 4-8Thefunctions
implementa
directoriesthatenableyoutomovetoanotherdirectory
temporarilyandhavetheshellrememberwhereyou
Inaddition,
providesanewtypeofflow-control
Allowtheusertoselectoneofalistofpossibilities
Thesimplestform(withoutthe
parts,or
)executesthe
onlyifthe
true.Ifyouaddan
CombinationsofExit
Oneofthemoreobscurepartsof
syntaxallowsyou
tocombineexitstatuseslogically,sothatyoucantest
Thesyntax
means,"execute
,andifitsexitstatusis0,execute
Thesyntax
istheconverse:it
means,"execute
,andifitsexitstatusis
."Atfirst,theselooklike"if/then"and
"ifnot/then"constructs,respectively.Buttheyarereally
intendedforusewithinconditionsof
constructsÑasC
It'smuchmoreusefultothinkoftheseconstructsas"and"
Inthiscase,
Exitstatusesaretheonlythingsan
constructcantest.
Integer Conditionals
Themostobviousenhancementtomaketheprevious
scriptistheabilitytoreportonmultiplefilesinsteadof
justone.Testslike
takeonlysinglearguments,
soweneedawayofcallingthecodeonceforeachfile
ThewaytodothisÑindeed,thewaytodomanythings
iswithaloopingconstruct.Thesimplestand
mostwidelyapplicableoftheshell'sloopingconstructsis
loopallowsyoutorepeatasectionofcodea
fixednumberoftimes.Duringeachtimethroughthecode
(knownasan
),aspecialvariablecalleda
Thenextflow-controlconstructwewillcoveris
Whilethe
statementinPascalandthesimilar
statementinJavaandCcanbeusedtotestsimplevalues
likeintegersandcharacters,
Alloftheflow-controlconstructswehaveseensofarare
alsoavailableintheBourneshell,andtheCshellhas
equivalentswithdifferentsyntax.Ournextconstruct,
,isavailableonlyintheKornshelland
11]moreover,ithasnoanalogyinconventionalprogramming
allowsyoutogeneratesimplemenuseasily.Ithas
concisesyntax,butitdoesquitealotofwork.Thesyntax
list]dostatements that can use$name...doneThisisthesamesyntaxas
exceptforthekeyword
.Andlike
,youcanomitthe
anditwill
defaultto"
",i.e.,thelistofquotedcommand-line
1.Generatesamenuofeachiteminlist,formatted
2.Prompts the user for a number
Theremainingtwoflowcontrolconstructs
.Thesearesimilar;theybothallowa
4.1. Shell Scripts and Functions
4.1.1. Functions
4.2. Shell Variables
Wehavealreadyseenmanyexamplesofthe
thatthiskindofcodeimposeslimitationsonhowmany
argumentsthescriptcanhandleÑwhichisveryunwise.
Furthermore,ifthiscommandhadseveralpossible
Weneedtoaddonemoreingredienttomakeoption
processingreallyuseful.Recallthatmanycommands
haveoptionsthattaketheir
arguments.Forexample,
command,onwhichwereliedheavilyin
,acceptstheoption
Sofarwe'veseenhow
variablescanbeassigned
textualvalues.Variablescanalsohaveotherattributes,
IntegerVariablesand
quotes,unlessitcontainstildesoranyexpression
involvingadollarsign,inwhichcaseyoushoulduse
Forexample,the
commandonmodernversionsof
UNIXacceptsargumentsthattellithowtoformatits
output.Theargument
tellsittoprintthedayofthe
year,i.e.,thenumberofdayssinceDecember31stofthe
Wecanuse
toprintalittleholidayanticipation
Theshellalsosupportsbase
numbers,where
canbe
from2to36.Thenotation
means"
".Of
functionsuseastringvariableto
holdalistofdirectoriesandmanipulatethelistwiththe
stringpattern-matchingoperators.Althoughthisisquite
withthe
Chapter1
,youlearnedabouttheshell'sbasicI/O
,and
Aswesawin
Chapter1
withoutanargumentuses
standardinputasitsinput.Thisallowsyoutotypethe
inputandenditwithCTRL-Donitsownline.The
linewillbeappendedtothefile
ifitalready
Recallfrom
Chapter3
,thatyoucanpreventtheshell
fromoverwritingafilewith
bytyping
Thenextfewredirectorsin
Table7-1
dependonthe
notionofa
filedescriptor
.Likethedevicefilesusedwith
,thisisalow-levelUNIXI/Oconceptthatisof
interestonlytosystemsprogrammersÑandthenonly
Nowwe'llzoombackintothestringI/Oleveland
examinethe
statements,whichgivethe
shellI/Ocapabilitiesthataremoreanalogoustothoseof
Aswe'veseencountlesstimesinthisbook,
printsitsargumentstostandardoutput.Nowwe'llexplore
commandisquitepowerfulandformost
casesentirelyadequate.However,thereareoccasions
whereamorepowerfulandflexibleapproachisneeded
forprintinginformation,especiallywhentheinformation
needstobeformatted.
providesthisbygivingaccess
toapowerfulsystem-levelprintinglibraryknownas
4]Theprintfcommandcanoutputastringsimilartothe
Unlikethe
doesnotautomatically
provideanewline.Ifwewanttomakeitdotheexactly
sameasastandard
thenwemustprovideoneby
Theotherhalfoftheshell'sstringI/Ofacilitiesisthe
command,whichallowsyoutoreadvalues
Thisstatementtakesalinefromthestandardinputand
breaksitdownintowordsdelimitedbyanyofthe
charactersinthevalueoftheenvironmentvariable
Chapter4
;theseareusuallyaspace,aTAB,and
NEWLINE).Thewordsareassignedtovariables
We'veseenhowtheshelluses
toprocessinputlines:
itdealswithsinglequotes(`'),doublequotes(""),and
backslashes(
);itseparateslinesintowords,accordingto
delimitersintheenvironmentvariable
;anditassigns
thewordstoshellvariables.Wecanthinkofthisprocess
isrunwiththeoption
Althoughthislistofstepsisfairlystraightforward,itis
notthewholestory.Therearestillfivewaysto
theprocess:quoting;using
,or
command,builtin,and
Beforemovingontothelastpartofthecommand-line
processingcycle,we'lltakealookatthecommand
lookuporderthatwetouchedonin
Chapter4
andhowit
Thedefaultorderforcommandlookupisfunctions,
followedbybuilt-ins,withscriptsandexecutableslast.
Therearethreebuilt-insthatyoucanusetooverridethis
removesaliasandfunctionlookup.
9]Onlybuilt-insandcommandsfoundinthesearchpathare
executed.Thisisusefulifyouwanttocreatefunctions
thathavethesamenameasashellbuilt-inoracommand
inthesearchpathandyouneedtocalltheoriginal
commandfromthefunction.Forinstance,wemightwant
tocreateafunctioncalled
thatreplacesthestandard
commandwithonethatdoessomefancythingsandthen
eval
6.1. Command-Line Options
6.1.1. shift
6.1.2. Options with Arguments
WhyshouldyoucareaboutprocessIDsorjobnumbers?
Justasyoucanputbackgroundjobsintotheforeground
,youcanalsoputaforegroundjobintothe
background.Thisinvolvessuspendingajob,sothatthe
Tosuspendajob,typeCTRL-Zwhileitisrunning.
6]ThisisanalogoustotypingCTRL-C(orwhateveryour
interruptkeyis),exceptthatyoucanresumethejobafter
youhavestoppedit.WhenyoutypeCTRL-Z,theshell
commandThenitgivesyouyourpromptback.Toresumea
suspendedjobsothatitcontinuestoruninthe
foreground,justtype
.If,forsomereason,youput
otherjobsinthebackgroundafteryoutypedCTRL-Z,
$hatter &[2] 145$ fg %alicealice resumes in the foreground...Theabilitytosuspendjobsandresumetheminthe
foregroundcomesinveryhandywhenyouhavea
conventionalterminal(asopposedtoawindowing
WementionedearlierthattypingCTRL-Ztosuspenda
jobissimilartotypingCTRL-Ctostopajob,exceptthat
youcanresumethejoblater.Theyareactuallysimilarin
adeeperway:bothareparticularcasesoftheactof
Asignalisamessagethatoneprocesssendstoanother
whensomeabnormaleventtakesplaceorwhenitwants
processcancommunicatewithanotherthroughanI/O
pipeline;thinkofasignalasanotherwayforprocessesto
communicatewitheachother.(Infact,anytextbookon
operatingsystemswilltellyouthatbothareexamplesof
thegeneralconceptof
interprocesscommunication
,or
8])DependingontheversionofUNIX,therearetwoorthree
dozentypesofsignals,includingafewthatcanbeused
forwhateverpurposeaprogrammerwishes.Signalshave
numbers(from1tothenumberofsignalsthesystem
WhenyoutypeCTRL-C,youtelltheshelltosendthe
INT(for"interrupt")signaltothecurrentjob;CTRL-Z
sendsTSTP(onmostsystems,for"terminalstop").You
canalsosendthecurrentjobaQUITsignalbytyping
CTRL-\(control-backslash);thisissortoflikea
"stronger"versionofCTRL-C.
9]Youwouldnormally
useCTRL-\when(and
when)CTRL-Cdoesn't
Aswe'llseesoon,thereisalsoa"panic"signalcalled
KILLthatyoucansendtoaprocesswhenevenCTRL-\
doesn'twork.Butitisn'tattachedtoanycontrolkey,
whichmeansthatyoucan'tuseittostopthecurrently
runningprocess.INT,TSTP,andQUITaretheonly
10]Youcancustomizethecontrolkeysusedtosendsignals
withoptionsofthe
command.Thesevaryfrom
systemtosystemÑconsultyourmanpageforthe
commandÑbuttheusualsyntaxis
signamechar
isanameforthesignalthat,unfortunately,is
oftennotthesameasthenamesweusehere.
Table1-7
Chapter1
namesforsignalsfoundonall
versionsofUNIX.
isthecontrolcharacter,which
youcangiveusingtheconventionthat^(circumflex)
We'vebeendiscussinghowsignalsaffectthecasualuser;
Youcanusethebuilt-inshellcommand
tosenda
signaltoanyprocessyoucreatedÑnotjustthecurrently
runningjob.
takesasanargumenttheprocessID,job
number,orcommandnameoftheprocesstowhichyou
wanttosendthesignal.Bydefault,
sendstheTERM
("terminate")signal,whichusuallyhasthesameeffectas
theINTsignalyousendwithCTRL-C.Butyoucan
specifyadifferentsignalbyusingthesignalname(or
issonamedbecauseofthenatureofthedefault
TERMsignal,butthereisanotherreason,whichhastodo
withthewayUNIXhandlessignalsingeneral.Thefull
Thisisprobablytheonlysituationinwhichacasualuser
wouldneedtoknowtheIDofaprocess.Thecommand
givesyouthisinformation;however,itcangiveyou
isacomplexcommand.Ittakesseveraloptions,some
ofwhichdifferfromoneversionofUNIXtoanother.To
addtotheconfusion,youmayneeddifferentoptionson
Nowrepeattheprocess:runitinthebackgroundandtype
kill%loop
.Asbefore,youwillseethemessageandthe
processwillkeeponrunning.Type
kill-KILL%loop
Noticethatthemessageisn'treallyappropriatewhenyou
ProcessIDVariablesand
Theonlythingnewaboutthisscriptis
inthefilename
expression.Thisisaspecialshellvariablewhosevalueis
Toseehow
works,type
andnotetheprocessIDof
yourshellprocess(
).Thentype
";theshell
willrespondwiththatsamenumber.Nowtype
Ignoring Signals
AnotherwaytoignoretheHUPsignaliswiththe
14]disowntakesasanargumentajob
specification,suchastheprocessIDorjobID,and
removestheprocessfromthelistofjobs.Theprocessis
effectively"disowned"bytheshellfromthatpointon,
i.e.,youcanonlyrefertoitbyitsprocessIDsinceitisno
optionperformsthesamefunctionas
itspecifiesthattheshellshouldstopthehangupsignal
fromreachingtheprocessundercertaincircumstances.
,itisuptoyoutospecifywheretheoutput
alsoprovidestwooptionswhichcanbeofuse.-
withnootherargumentsappliestheoperationtoalljobs
ownedbytheshell.The-
optionwithdoesthesamebut
We'vespentthelastseveralpagesonalmostmicroscopic
youdon'twantthistohappen,andifitdoes,youmay
Infact,youmaybewonderingwhyyouwouldeverneed
toprogramcoroutinesthatdon'tcommunicatewitheach
other.Forexample,whynotjustrun
theusualway?Whatadvantageisthereinrunningthe
Evenifyouarerunningonacomputerwithonlyone
processor(CPU),thentheremaybeaperformance
Roughlyspeaking,youcancharacterizeaprocessin
termsofhowitusessystemresourcesinthreeways:
IfyouhaveacomputerwithmultipleCPUsyoushould
belessconcernedaboutthrashing.Furthermore,
coroutinescanprovidedramaticincreasesinspeedonthis
typeofmachine,whichisoftencalleda
computer;analogously,breakingupaprocessinto
error.Nevertheless,it'sworthwhiletoknowhowto
Toconcludethischapter,wewilllookatasimpletypeof
interprocessrelationship:thatofasubshellwithitsparent
shell.Wesawin
Chapter3
thatwheneveryourunashell
script,youactuallyinvokeanothercopyoftheshellthat
isasubprocessofthemain,or
,shellprocess.Now
Subshellsneednotbeinseparatescripts;youcanalso
startasubshellwithinthesamescript(orfunction)asthe
parent.Youdothisinamannerverysimilartothe
commandblockswesawinthelastchapter.Justsurround
someshellcodewithparentheses(insteadofcurly
Auniquebutrarelyusedfeatureof
8.4.2.ProcessIDVariablesandTemporary
chapter,we'llshowstepbystephowtobuildadebugger
.Thedebugger,called
old-timeprogrammersdebuggedtheirFORTRANcode
byinserting
cardsintotheirdecks.Youcan
debugbyputtinglotsof
statementsinyourcode
(andremovingthemlater),butyouwillhavetospendlots
oftimenarrowingdownnotonly
exactinformation
youwantbutalso
youneedtoseeit.Youwillalso
probablyhavetowadethroughlotsandlotsofoutputto
Fakesignals
3.0addedsomeusefulenvironmentvariablestoaid
inwritingadebugger.TheseincludeBASH_SOURCE,
whichcontainsanarrayoffilenamesthatcorrespondto
whatiscurrentlyexecuting;BASH_LINENO,whichis
anarrayoflinenumbersthatcorrespondtofunctioncalls
thathavebeenmade;BASH_ARGCandBASH_ARGV
arrayvariables,thefirstholdingthenumberof
Inthissectionwe'lldevelopaverybasicdebuggerfor
10]Mostdebuggershavenumeroussophisticated
featuresthathelpaprogrammerindissectingaprogram,
butjustaboutallofthemincludetheabilitytostep
througharunningprogram,stopitatselectedplaces,and
examinethevaluesofvariables.Thesesimplefeatures
arewhatwewillconcentrateonprovidinginour
¥Specifyplacesintheprogramatwhichtostop
¥Executeaspecifiednumberofstatementsinthe
¥Examineandchangethestateoftheprogram
duringitsexecution.Thisincludesbeingableto
printoutthevaluesofvariablesandchangethem
whentheprogramisstoppedatabreakpointor
¥Printoutthesourcecodewearedebuggingalong
withindicationsofwherebreakpointsareand
whatlineintheprogramwearecurrently
¥Providethedebuggingcapabilitywithouthaving
tochangetheoriginalsourcecodeoftheprogram
Asyouwillsee,thecapabilitytodoallofthesethings
(andmore)iseasilyprovidedbytheconstructsand
The Preamble
Thefunction
istheentrypointintothe
debugger;itisdefinedinthefile
.Hereis
Nowwe'llshowatranscriptofanactualsessionwith
,inwhichtheguineapigisthesolutiontoTask
6-1,thescript
.Hereisthetranscriptofthedebugging
We'llconcludethischapterwithsomesuggested
Ifyourunthisscript,youwillprobablyfindseveral
occurrencesof
hasseveralcommand-lineoptionsthatchangethe
behaviorofandpassinformationtotheshell.Theoptions
LiketheBourneshell,
usesthefile
commandwasoriginallyusedtospecifythe
limitonfilecreationsize.But
'sversionhasoptions
TypesofGlobal
Thebestpossibleapproachtogloballyavailable
customizationwouldbeasystem-wideenvironmentfile
thatisseparatefromeachuser'senvironmentfileÑjust
Thevariable
isusefulwhenyoursystem
SystemSecurity
Beforeweexplaintheothersecurityfeatures,hereis
somebackgroundinformationonsystemsecuritythat
ManyproblemswithUNIXsecurityhingeonaUNIXfile
attributecalledthe
TheonewaytoprotectagainstTrojanhorsesis
9.1. Basic Debugging Aids
helpreadability.It'simportanttomakeyourcodeas
Thefirstruleofshellscriptingisto
commentyourcode
Youshoulddothisrightfromthestart,evenifthescript
isonlyacoupleoflineslong.Shellscriptshaveahabitof
growingfromacoupleoflinestomanyhundredsoflines
Headersandcommentsarejustonewaytodocument
yourcode.Anotherisbytheuseofdescriptivevariable
names.Goodvariablenamesshouldgiveanindicationof
whatthevariablerepresents.Nameslike"x","resn"or
"procd"willonlyhavemeaningatthetimethatyouwrite
thescript.Sixmonthsdownthetrackandtheywillbea
Goodnamesshouldbeshortbutdescriptive.Thethree
examplesabovemighthavebeenmoremeaningfully
writtenas"file_limit","resolution",and"was_processed".
Don'tmakethenamestoolong;thename
"horizontal_resolution_of_the_picture"justcluttersa
scriptandtakesawayanyadvantageinmakingthename
Constantsshouldbeinuppercaseandshouldnormallybe
Youshouldalwaysavoid"magicnumbers"sprinkled
Chapter6
wetalkedaboutusing
optionsandargumentspassedintoashellscript.This
commandmakesiteasyforthescriptprogrammerto
processwhattheuserhasprovided,butwhataboutthe
otherhalfofthedeal?Theprogrammermustmakean
efforttomakelifeaseasyfortheuseraspossible.
Nothingmakesausermoreiratethanascriptthatdoesn't
takestandardarguments,doesn'tprovideausage
message,doesn'tprocesstheargumentsintheexpected
way,andforcestheuserintoawayofthinkingthatthe
programmerthinksistherightway.Havingtoexamine
thesourcecodeforascripttofindoutwhatisan
Herearesomeusefulthingstowatchoutforwhen
writingshellscripts.Beingawareofthemwillnotonly
saveyoutimeintrackingdownbugsbutwillalsomake
yourscriptsmorerobust,morereadable,andaboveall,
¥Don'tcreatemassivescriptsorfunctionsthattry
todoeverything.Splitfunctionalityupinto
smallerunitsandplacetheminfunctions.This
notonlymakesthecodeeasiertoreadbutmakes
¥Alwaysplacetheshellexecutiondirective(e.g.,
#!/bin/bash
)atthetopofyourscriptstoensure
¥Don'tusereservedwordsforvariablenames.
Don't Use bash
Havingobtainedthearchivefilebyoneoftheabove
isavailablefrom
archivecontainsamaindirectory(
Theotherfilesanddirectoriesinthearchivearemostly
thingsthatareneededduringthebuild.Unlessyouare
goingtogohackingintotheinternalworkingsofthe
directorycontainsafewarticlesthatareworth
reading.Indeed,itwouldbewellworthprintingoutthe
manualentryfor
soyoucanuseitinconjunction
withthisbook.The
filegivesashortsummary
Thedocumentyou'llmostoftenuseisthemanualpage
entry(
).Thefileisin
formatÑthatusedby
themanualpages.Youcanreaditbyprocessingitwith
thetext-formatter
andpipingtheoutputtoapager
nroff-manbash.1|more
shoulddothetrick.
Youcanalsoprintitoffbypipingittothelineprinter
).Thissummarizesallofthefacilitiesyourversionof
ConfiguringandBuilding
Tocompile
"straightoutofthebox"iseasy;
2]youjusttype
andthen
!The
bashconfigure
scriptattemptstoworkoutifyouhavevariousutilities
andClibraryfunctions,andwhereaboutstheyresideon
yoursystem.Itthenstorestherelevantinformationinthe
.Italsocreatesafilecalled
isascriptyoucanruntorecreatethecurrent
configurationinformation.Whilethe
running,itprintsoutinformationonwhatitissearching
Bugreportsshouldbesentto
,and
includetheversionof
andtheoperatingsystemitis
runningon,thecompilerusedtocompile
,a
descriptionoftheproblem,adescriptionofhowthe
problemwasproduced,and,ifpossible,afixforthe
problem.Thebestwaytodothisiswiththe
Beforeyourun
Thereareaseriesofteststhatcanberunonyournewly
builtversionof
toseeifitisrunningcorrectly.The
testsarescriptsthatarederivedfromproblemsreported
inearlierversionsoftheshell.Runningthesetestsonthe
Torunthetestsjusttype
maketests
inthemain
directory.Thenameofeachtestisdisplayed,alongwith
somewarningmessages,andthenitisrun.Successful
testsproducenooutput(unlessotherwisenotedinthe
Ifanyofthetestsfail,you'llseealistofthingsthat
hasbeeninstalledonalargenumberof
differentmachinesandoperatingsystems,thereare
occasionallyproblems.Usuallytheproblemsaren't
seriousandabitofinvestigationcanresultinaquick
didn'tcompile,thefirstthingtodoischeckthat
guessedyourmachineandoperatingsystem
correctly.Thencheckthefile
,whichcontains
someinformationonspecificUNIXsystems.Alsolook
foradditionalinformationonhowtogive
InstallingbashasaLogin
Havinginstalled
andmadesureitisworking
correctly,thenextthingtodoistomakeityourlogin
Individualuserscanusethe
(changeshell)command
aftertheylogintotheiraccounts.
asksfortheir
passwordanddisplaysalistofshellstochoosefrom.
Onceashellischosen,
changestheappropriateentry
archivealsoincludesanexamplesdirectory.
Thisdirectorycontainssomesubdirectoriesforscripts,
Thestartupfilesinthe
directoryprovide
manyexamplesofwhatyoucanputinyourownstartup
files.Inparticular,
givesmanyuseful
aliases.Bearinmindthatifyoucopythesefiles
wholesale,you'llhavetoeditthemforyoursystem
becausemanyofthepathswillbedifferent.Referto
Chapter3
forfurtherinformationonchangingthesefiles
directorycontainsabout50fileswith
functiondefinitionsthatyoumightfinduseful.Among
Who Do I Turn to?
11.1. What's That Do?
11.1.1. Comments
11.1.2. Variables and Constants
11.2. Starting Up
12. bash for Your System
12.1. Obtaining bash
12.3.1. Documentation
12.4. Who Do I Turn to?
12.4.1. Asking Questions
A. Related Shells
11
Thereforewefeltitnecessarytoincludeinformationon
shellssimilarto
.Thisappendixsummarizesthe
TheIEEE1003.2POSIX
TherehavebeenmanyattemptstostandardizeUNIX.
Oneofthefirstmajoralternativestothe"traditional"
shells,BourneandC,wastheKornshell,publicly
releasedin1986aspartofAT&T's"Experimental
Toolchest."TheKornshellwaswrittenbyDavidKornat
AT&T.Thefirstversionwasunsupported,buteventually
UNIXSystemLaboratories(USL)decidedtogiveit
supportwhentheyreleaseditwiththeirversionofUNIX
(SystemVRelease4)in1989.TheNovember1988Korn
The1988releaseisnotfullyPOSIX-compliantÑlessso
.Thelatestrelease(1993)hasbroughttheKorn
(PublicDomainKornshell)isaversionofthe
Kornshellthatisafreealternativeto
isapowerfulinteractiveshellandscriptinglanguage
withmanyfeaturesfoundin
,and
,aswell
wasoriginallywrittenbyPaulFalstedintheearly
Itisfreelyavailableandshouldcompileandrunonjust
aboutanymodernversionofUnix.Portsforother
operatingsystemsarealsoavailable.The
homepage
ShellClonesand
Theproliferationofshellshasnotstoppedatthe
boundariesofUNIX-dom.Manyprogrammerswhogot
theirinitialexperienceonUNIXsystemsand
subsequentlycrossedoverintothePCworldwishedfora
niceUNIX-likeenvironment.It'snotsurprisingthenthat
severalUNIXshell-styleinterfacestosmall-computer
operatingsystemshaveappeared,Bourneshell
Inthepastseveralyears,notonlyshellcloneshave
appeared,butentireUnix"environments."Twoofthem
useshellsthatwe'vealreadydiscussed.Twoothers
providetheirownshellreimplementations.Providinglists
ofmajorandminordifferencesiscounterproductive.
Instead,thissectiondescribeseachenvironmentinturn
TheDJGPPsuiteprovides32-bitGNUtoolsforthe
PerhapsthemostestablishedUnixenvironmentforthe
PCworldistheMKSToolkitfromMorticeKern
TheUWINpackageisaprojectbyDavidKornandhis
colleaguestomakeaUnixenvironmentavailableunder
MicrosoftWindows.Itissimilarinstructureto
discussedearlier.Asharedlibrary,
,provides
emulationoftheUnixsystemcallAPIs.Thesystemcall
TableB-3
showsasummaryoftheprompt
customizationsthatareavailable.Thecustomizations\[
and\]arenotavailablein
versionspriorto1.14.\a,
\e,\H,\T,\@,\v,and\Varenotavailableinversions
priorto2.0.\A,\D,\j,\l,and\rareonlyavailableinlater
TableB-3.Prompt string customizations
CommandMeaning
\aThe ASCII bell character (007)
Thecurrenttimein24-hourHH:MM
\dThe date in "Weekday Month Day" format
Built-InCommandsand
TableB-4
showsasummaryofallbuilt-incommandsand
TableB-5
TableB-6
liststheoperatorsthatareusedwith
...]and[[...]]constructs.Theycanbelogically
combinedwith
("and")and
("or")andgroupedwith
escapedparenthesis(
\(...\)
).Thestringcomparisons
andthe
...]]constructarenotavailableinversions
TableB-6.Test operators
OperatorTrue if...
filefile
filefile
filefile
filefile
filefile
shopt Options
The
shopt
TableB-9
TableB-10
viControlMode
TableB-11
AppendixC.Loadable
2.0introducedanewfeaturethatincreasedthe
flexibilityoftheshell:dynamicallyloadablebuilt-ins.On
systemsthatsupportdynamicloading,youcanwriteyour
ownbuilt-insinC,compilethemintosharedobjects,and
loadthematanytimefromwithintheshellwiththe
built-in(see
Chapter7
AppendixD.Programmable
A.1. The Bourne Shell
A.2. The IEEE 1003.2 POSIX Shell Standard
A.6.1. Cygwin
B. Reference Lists
B.1. Invocation
ThefirstthingusersoftheUNIXorLinuxoperating
systemscomefacetofacewithisthe
."Shell"isthe
¥Command-lineediting,allowingyoutouse
-or
-styleeditingcommandsonyourcommand
commandsduringaloginsession)andshell
programming.Weseeshellprogrammingasanatural,
Accordingly,eachchapterdependsonthosepreviousto
it,andalthoughthefirstthreechaptersareoriented
towardinteractiveuseonly,subsequentchaptersdescribe
interactive,user-orientedfeaturesinadditionto
Thisbookaimstoshowyouthatwritingusefulshell
programsdoesn'trequireacomputingdegree.Evenifyou
Chapter5
continuesthediscussionofshellprogramming
bydescribingcommandexitstatus,conditional
expressions,andtheshell'sflow-controlstructures:
Chapter6
Chapter11
discusseswaystomake
scriptsmore
Chapter12
Usedfor
built-incommands,aliases,variables,
andoptions,aswellascommandlineswhentheyare
withinregulartext.
isusedforallelements
ConstantWidth
Usedinexamplestoshowthecontentsoffilesorthe
WeuseUNIXasashorthandfor"UNIXandLinux."
PuristswillcorrectlyinsistthatLinuxisnot
UNIXÑbutasfarasthisbookisconcerned,they
Reynolds,BillRosenblatt,andNormWalshfortaking
Figure1-1
Figure1-1.Theshellisalayeraroundthe
Therearevarioustypesofuserinterfaces.
belongsto
themostcommoncategory,knownascharacter-based
userinterfaces.Theseinterfacesacceptlinesoftextual
commandsthattheusertypesin;theyusuallyproduce
text-basedoutput.Othertypesofinterfacesincludethe
increasinglycommon
graphicaluserinterfaces
whichaddtheabilitytodisplayarbitrarygraphics(not
justtypewritercharacters)andtoacceptinputfroma
mouseorotherpointingdevice,touch-screeninterfaces
Ofcourse,eachofthesestepsreallyinvolvesseveral
substeps,eachofwhichincludesaparticularinstruction
RememberthattheshellitselfisnotUNIXÑjusttheuser
interfacetoit.UNIXisoneofthefirstoperatingsystems
tomaketheuserinterfaceindependentoftheoperating
systemworksingeneral.It'spossibletobecomea
virtuososhellprogrammerwithoutanyprevious
programmingexperience.Atthesametime,we've
1988.BrianFoxwrotetheoriginalversionsof
andcontinuedtoimprovetheshellupuntil1993.
1]TheKornshellcanbedownloadedforfreebutit
comeswithalicensethatwillrequirepaymentiftheshell
2]GNUisarecursiveacronym,standingfor"GNU'sNot
Onceyouknowyouhave
onyoursystem,youcan
invokeitfromwhateverothershellyouusebytyping
inyourpassword,thenlogoutandlogbackinagainto
3]Makesureyouusethecorrectquotationmarkinthis
4]Forsystemsecurityreasons,onlycertainprogramsare
asthenameofafiletoprint.Arguments
areoftennamesoffiles,butnotnecessarily:inthe
commandline
mailcam
,the
programtreats
isaspecialtypeofargumentthatgivesthe
commandspecificinformationonwhatitissupposedto
Thetopofthetreeisadirectorycalled
thathasno
nameonthesystem.
6]Allfilescanbenamedby
expressingtheirlocationonthesystemrelativeto
suchnamesarebuiltbylistingallofthedirectorynames
(inorderfrom
),separatedbyslashes(
),followedby
thefile'sname.Thiswayofnamingfilesiscalleda
Forexample,saythereisafilecalled
thatisinthe
,whichisinthedirectory
,whichisin
thedirectory
,whichisintherootdirectory.This
Ofcourse,it'sannoyingtohavetousefullpathnames
wheneveryouneedtospecifyafile.Sothereisalsothe
sameastheirloginname,andallhomedirectoriesare
Forexample,
/home/cam
isatypicalhomedirectory.If
thisisyourworkingdirectoryandyougivethecommand
lpmemo
,thenthesystemlooksforthefile
/home/cam
.Ifyouhaveadirectorycalled
inyour
homedirectory,anditcontainsthefile
,thenyou
Asyoucanwellimagine,homedirectoriesoccuroftenin
pathnames.Althoughmanysystemsareorganizedsothat
allhomedirectorieshaveacommonparent(suchas
),youshouldnotrelyonthatbeingthe
case,norshouldyouevenhavetoknowtheabsolute
hasawayofabbreviatinghome
directories:justprecedethenameoftheuserwithatilde
).Forexample,youcouldrefertothefile
inuser
'shomedirectoryas
~alice/story
.Thisisanabsolute
pathname,soitdoesn'tmatterwhatyourworking
directoryiswhenyouuseit.If
'shomedirectoryhas
asubdirectorycalled
andthefileisinthere
Evenmoreconvenient,atildebyitselfreferstoyourown
homedirectory.Youcanrefertoafilecalled
yourhomedirectoryas
(notethedifference
Ifyouwanttochangeyourworkingdirectory,usethe
.Ifyoudon'trememberyourworking
directory,the command
takesasanargumentthenameofthedirectoryyou
wanttobecomeyourworkingdirectory.Itcanberelative
toyourcurrentdirectory,itcancontainatilde,oritcan
beabsolute(startingwithaslash).Ifyouomitthe
changestoyourhomedirectory(i.e.,it'sthe
Table1-1
givessomesample
commands.Each
commandassumesthatyourworkingdirectoryis
justbeforethecommandisexecuted,andthatyour
Table1-1.Sample cd commands
Thefirstfourarestraightforward.Thenexttwousea
specialdirectorycalled
.(twodots),whichmeans"parent
ofthisdirectory."Everydirectoryhasoneofthese;it'sa
withoutanargumenttogotoyourhome
filenameswithouthavingtoknowallofthenames
themselves.Youcanusespecialcharacters,called
,infilenamestoturnthemintopatterns.
Table1-2.Basic wildcards
WildcardMatches
paragraph;texteditoruserscanusetheexpression
8]Table1-3
shouldhelpdemonstratehowtheasterisk
works.Assumethatyouhavethefiles
Table1-3.Using the * wildcard
ExpressionYields
fr*frank fred
eded fred
b*bob
ExpressionYields
edarlene dave
g*g*
Noticethat
canstandfornothing:both
.Alsonoticethatthelastexampleshowswhat
theshelldoesifitcan'tmatchanything:itjustleavesthe
Theremainingwildcardisthe
ExpressionMatches
[.,;]Period, comma, or semicolon
[-_]Dash or underscore
[a-c]a, b, or c
Intheoriginalwildcardexample,
andprogram.[a-z]bothmatch
,but
However,it'simportanttobeawarethatthecommands
thatyourunonlyseetheresultsofwildcardexpansion.
Thatis,theyjustseealistofarguments,andtheyhaveno
knowledgeofhowthoseargumentscameintobeing.For
example,ifyoutype
lsfr*
andyourfilesareasonthe
previouspage,thentheshellexpandsthecommandline
lsfredfrank
andinvokesthecommand
.Ifyoutype
lsg*
,then
(becausethereisnomatch)
willbegiventheliteral
andwillcomplainwiththeerrormessage,
10]Hereisanexamplethatshouldhelpmakethingsclearer.
SupposeyouareaCprogrammer.Thismeansthatyou
dealwithfileswhosenamesendin
(programs,also
knownassourcefiles),
(headerfilesforprograms),and
(objectcodefilesthataren'thuman-readable),aswell
pathname.Forexample,ifyouwantedtolistallofthe
filesinthedirectories
,youcouldtype
.Ifyouwereonlyinterestedinthefilesbeginning
6]MostUNIXtutorialssaythat
hasthename
.We
standbythisalternativeexplanationbecauseitismore
logicallyconsistentwiththerestoftheUNIXfilename
7]Eachdirectoryalsohasthespecialdirectory.(single
dot),whichjustmeans"thisdirectory."Thus,
effectivelydoesnothing.Both.and
.areactuallyspecial
hiddenfilesineachdirectorythatpointtothedirectory
itselfandtoitsparentdirectory,respectively.
isits
8]MS-DOSandVAX/VMSusersshouldnotethatthere
nothingspecial
aboutthedot(.)inUNIXfilenames
(asidefromtheleadingdot,which"hides"thefile);it's
justanothercharacter.Forexample,
ls*
listsallfilesin
thecurrentdirectory;youdon'tneed
asyoudoon
othersystems.Indeed,
ls*.*
won'tlistallthefilesÑonly
9]Specifically,rangesdependonthecharacterencoding
schemeyourcomputeruses(normallyASCII,butIBM
11]Thisformofbraceexpansionisnotavailablein
12]ThisdiffersslightlyfromCshellbraceexpansion.
requiresatleastoneunquotedcommatoperforman
expansion;otherwise,thewordisleftunchanged,e.g.,
wayofproducingerrormessagescalled
standarderror
,usuallyshortenedto
standarderror
.Ofcourse,a
programcanhaveotherinputandoutputsourcesaswell,
StandardI/Owasthefirstschemeofitskindthatwas
designedspecificallyforinteractiveusersatterminals,
ratherthantheolderbatchstyleofusethatusually
involveddecksofpunch-cards.SincetheUNIXshell
providestheuserinterface,itshouldcomeasnosurprise
thatstandardI/Owasdesignedtofitinveryneatlywith
AllshellshandlestandardI/Oinbasicallythesameway.
EachprogramthatyouinvokehasallthreestandardI/O
UtilityPurpose
Translatecharactersintheinputtoother
Youmayhaveusedsomeofthesebeforeandnoticedthat
theytakenamesofinputfilesasargumentsandproduce
outputonstandardoutput.Youmaynotknow,however,
thatallofthem(andmostotherUNIXutilities)accept
13]Forexample,themostbasicutilityis
,whichsimply
copiesitsinputtoitsoutput.Ifyoutype
witha
filenameargument,itwillprintoutthecontentsofthat
fileonyourscreen.Butifyouinvokeitwithno
arguments,itwillexpectstandardinputandcopyitto
standardoutput.Tryit:
willwaitforyoutotypealine
This is another line of text.
This is another line of text.
^D
$
73
ifforsomereasonitdidn'texistorwasbroken,youcould
lineistheloginname;fieldsareseparatedbycolons(:).
temporaryfilestostorecommandoutputbeforeitisfed
Forexample,todothesamesortofthingastheabove
commandlineonotheroperatingsystems(assumingthat
equivalentutilitiesareavailable...),youneedthree
commands.OnDEC'sVAX/VMSsystem,theymight
thecommandisrunning,putanampersand(&)afterthe
Thisiscalledrunningthecommandinthebackground,
andacommandthatrunsinthiswayiscalleda
backgroundjob;bycontrast,ajobrunthenormalwayis
calledaforegroundjob.Whenyoustartabackground
outputfromthetwojobswillberandomly(andoften
Ifyouwanttorunajobinthebackgroundthatexpects
standardinputorproducesstandardoutput,youusually
wanttoredirecttheI/Osothatitcomesfromorgoestoa
file.Programsthatproducesmall,one-linemessages
thenthedifferenceswillbesavedinthefile
foryou
Speakingofgoodcitizenship,thereisalsoaUNIX
CharacterMeaning
CharacterMeaning
Whatifwewanttoprintthestring
2*3�5isavalid
command-lineprocessing.Fornow,though,youshould
Youcanusewildcardsinthestring,butyoumustquote
them,sothatthe
commanditselfcanmatchthem
againstnamesoffilesineachdirectoryitsearches.The
find.-name`*.c
'willmatchallfileswhose
namesendin
anywhereinyourcurrentdirectory,
havenotroubleresolvingtheotherbewilderingissues
$
echo The Caterpillar and Alice looked at each other for some \

time in silence: at last Caterpillar took the hookah out of its \

mouth, and addressed her in a languid, sleepy voice.
Or you can do it this way:
$
echo 'The Caterpillar and Alice looked at each other for some

time in silence: at last Caterpillar took the hookah out of its

mouth, and addressed her in a languid, sleepy voice.'
97
Table1-7.Control keys
CTRL-CintrStop current command
CTRL-DeofEnd of input
CTRL-\quit
Stopcurrentcommandif
CTRL-SstopHalt output to screen
DELor
eraseErase last character
CTRL-UkillErase entire command line
CTRL-Zsusp
Suspendcurrentcommand(see
notationstandsforCTRL-
.IfyourUNIX
versionderivesfromSystemIIIorSystemV(this
includesAIX,HP/UX,SCO,Linux,andXenix),type
Thecontrolkeyyouwillprobablyusemostoftenis
TypeCTRL-Qtorestarttheoutput;anykeysyoumay
thelastexampleisequivalentto
`re*',and
commandssimilartothoseofthetwomostpopular
UNIXeditors,
.Italsoprovidesa
much-extendedanalogtotheCshellhistorymechanism
(forfixcommand)that,amongotherthings,
allowsyoutouseyourfavoriteeditordirectlyforediting
yourcommandlines.Toroundthingsout,
Inthischapter,wewilldiscussthefeaturesthatare
commontoallof
'scommand-historyfacilities;after
[
CommandDescription
Movebackwardonecharacter(without
thatitrepeats.Thecursorwillmovetotheleftuntilitis
Nowthecursorisonthe
,andpointisatthebeginning
oftheline,justbeforethe
.IfyoutypeDEL,nothing
willhappenbecausetherearenocharacterstotheleftof
CommandDescription
ESC-FMove one word forward
ESC-DELKill one word backward
ESC-CTRL-HKill one word backward
ESC-DKill one word forward
IfwetypeESC-Bagain,weendupatthebeginningof
Why?Rememberthatawordisdefinedasasequenceof
alphanumericcharactersonly.Therefore
isnotaword;
thenextwordinthebackwarddirectionis
.We
CommandDescription
�ESC-Move to last line of history list
CTRL-PandCTRL-Nmoveyouthroughthecommand
history.Ifyouhavecursormotionkeys(arrowkeys)you
canusetheminstead.Theup-arrowisthesameas
CTRL-Pandthedown-arrowisthesameasCTRL-N.For
therestofthisdiscussion,we'llsticktousingthecontrol
CTRL-PisbyfartheoneyouwillusemostoftenÑit's
AfterCTRL-A,ESC-F,twoCTRL-Fs,andCTRL-D,you
Youdecidetotry
insteadof
,soyoutype
andhit
run.Second,thislinewillbeenteredintothehistorylist
attheend,andyour"currentline"willbeattheendas
well.Youwillnolongerbesomewhereelseinthe
Anotherhandytricktosavetypingifyouhavealready
doneasearchistotypeCTRL-Rtwiceinarow.This
3]CTRL-P,CTRL-N,andCTRL-Rareclearlythemost
importantemacs-modecommandsthatdealwiththe
commandhistory.Theothersarelessusefulbutare
it,followedbyaspaceincaseyouwanttotype
inmorecommandarguments.Commandname
ArelatedcommandisESC-
,whichexpandstheprefix
toallpossiblechoices,listingthemtostandardoutput.Be
CommandDescription
CommandDescription
Transposetwocharactersoneithersideof
CTRL-UKills the line from the beginning to point
CTRL-VQuoted insert
CTRL-[Same as ESC (most keyboards)
ESC-CCapitalize word after point
Changewordafterpointtoallcapital
CommandDescription
ESC-_Same as ESC-.
BSD-derivedsystemsuseCTRL-VandCTRL-Was
CTRL-Vwillcausethenextcharacteryoutypetoappear
inthecommandlineasis;i.e.,ifitisaneditingcommand
(oranotherwisespecialcharacterlikeCTRL-D),itwill
Ifitseemsliketherearetoomanysynonymsfor
4]emacsuserswillrecognizethisasminibuffer
CommandDescription
Erasepreviousword(i.e.,eraseuntila
CTRL-VQuote the next character
ESCEnter control mode (see below)
NotethatatleastsomeoftheseÑdependingonwhich
versionofUNIXyouhaveÑarethesameastheediting
commandsprovidedbyUNIXthroughitsterminal
5]vi-modewilluseyour"erase"characteras
CommandDescription
bMove left one word
WMove to beginning of next non-blank word
Movetobeginningofprecedingnon-blank
eMove to end of current word
EMove to end of current non-blank word
0Move to beginning of line
^Move to first non-blank character in line
$Move to end of line
Allofthesecommandsexceptthelastthreecanbe
precededbyanumberthatactsasarepeatcount.
Wheneveryoutypeanumberfortherepeatcount,the
numberreplacesthecommandpromptforthedurationof
therepeatcommand.Ifyourkeyboardhascursormotion
keys("arrow"keys),youcanusetheleftandrightarrows
Ifyoutype
again,thenextwordistheslash(it'sa
"sequence"ofnon-alphanumericcharacters),sothe
However,ifyoutyped
insteadof
,thenon-blankword
wouldbetheentirepathname,andthecursorwouldend
Youwouldhavehadtotype
fourtimesÑorjust
Ontheotherhand,
CommandDescription
AText inserted at end of line
RText overwrites existing text
Mostlikely,youwilluseeither
consistently,and
youmayuse
areabbreviations
respectively.Toillustratethedifference
,type
instead,andthentype
Inotherwords,youwillbe
)insteadof
Whycapital
insteadoflowercase
?Thelatterisa
slightlydifferentcommand,whichreplacesonlyone
characteranddoesnotenterinputmode.With
,thenext
singlecharacteroverwritesthecharacterunderthecursor.
Soifwestartwiththeoriginalcommandlineandtype
CommandDescription
CommandDescription
DEquivalent to
mayfinditdifficulttomakesurethemoreesoteric
144
CommandDescription
?stringSearch forward for string
Repeatsearchinsamedirectionas
Repeatsearchinoppositedirectionof
Thefirsttwocanalsobeaccomplishedwiththeupand
downcursormovementkeysifyourkeyboardhasthem.
Thefirstthreecanbeprecededbyrepeatcounts(e.g.,
Ifyouaren'tfamiliarwith
anditsculturalhistory,you
maybewonderingatthewisdomofchoosingsuch
seeminglypoormnemonicsas
,and
forbackward
character,forwardline,backwardline,andforward
character,respectively.Well,thereactuallyisarationale
firstpopularmodelswithaddressablecursors(meaning
thataprogramcouldsendanADM-3acommandtomove
thecursortoaspecifiedlocationonthescreen).The
,and
keyshadlittlearrowsonthem,so
Joydecidedtousethosekeysforappropriatecommands
.Another(partial)rationaleforthecommandchoices
isthatCTRL-Histhetraditionalbackspacekey,and
Type
w
CommandDescription
Moverighttonextoccurrenceofx,then
Movelefttopreviousoccurrenceofx,then
;Redo last character-finding command
Redolastcharacter-findingcommandin
somewheretotherightof
,thefastestwayto
movetothe
wouldbetotype
insteadof
Asanexampleofhowtherepeatcountcanbeusedwith
whosenumberisgivenbyanumericprefixargument.
Columncountsstartat1;countonlyyourinput,notthe
spacetakenupbythepromptstring.Thedefaultrepeat
countis1,ofcourse,whichmeansthattyping
byitselfis
Itisalsopossibletoexpandotherenvironmententities,as
wesawinemacs-mode.Ifthetextbeingexpandedis
precededbyadollarsign($),theshellwillattemptto
expandthenametothatofashellvariable.Ifthetextis
precededbyatilde(
),expansiontoausernameis
CommandDescription
savingacommandtobeexecutedlater
6]Neitherofthesedefinitionsisthesameasthe
7]Fansof
andsearchutilitieslike
shouldnote
¥Ifyouspecifynoarguments,youwillseethelast
16commandsyouentered.bashalsohasa
built-incommandfordisplayingthehistory:
thepathnameofyourfavoriteeditorandeditcommands
fromyourhistorylist;thenwhenyouhavemadethe
¥Withtwoargumentsto
,theargumentsspecify
thebeginningandendofarangeofcommands,
Rememberthat
actuallyrunsthecommand(s)afteryou
editthem.Therefore,thelast-namedchoicecanbe
willattempttoexecuteallcommandsin
therangeyouspecifywhenyouexityoureditor.Ifyou
havetypedinanymulti-lineconstructs(likethosewewill
coverin
Chapter5
),theresultscouldbeevenmore
dangerous.Althoughthesemightseemlikevalidwaysof
9]SeeChapter3
forinformationonthe
startupfile
CommandDescription
Referstothemostrecentcommand
Referstothemostrecentcommand
;theending?is
Repeatthelastcommand,replacing
Byfarthemostusefulcommandis
.Typing
onthe
commandlinere-executesthelastcommand.Ifyouknow
thecommandnumberofaspecificcommand,youcanuse
the!
form,where
isthecommandnumber.Command
Insteadofmovingbacktothelineandchanging
,youcouldjusttype
.Thiswillchange
thestring
andthenexecutetheresulting
It'salsopossibletorefertocertainwordsinaprevious
commandbytheuseofa
worddesignator
Table2-16
listsavailabledesignators.Notethatwhencounting
(likemostUNIXprograms)startscounting
Table2-16.Word designators
DesignatorDescription
0The zeroth (first) word in a line
^The first argument (the second word)
$The last argument in a line
DesignatorDescription
Thewordmatchedbythemostrecent
Arangeofwordsfrom
.-
Allwordsbutthezeroth(first);
synonymouswith1-$.;ifthereisonlyone
wordontheline,anemptystringis
Eventdesignatorsmayalsobefollowedby
Themodifiersfollowtheworddesignator,ifthereisone.
Table2-17.Modifiers
ModifierDescription
Removesatrailingpathnamecomponent,
rRemoves a trailing suffix of the form .
eRemoves all but the trailing suffix
Removesallleadingpathnamecomponents,
Printstheresultingcommandbutdoesn't
Quotesthesubstitutedwords,escaping
ModifierDescription
Quotesthesubstitutedwords,breaking
/Substitutes
Morethanonemodifiermaybeusedwithanevent
Historyexpansionisfineforre-executingacommand
quickly,butithasbeensupersededbythecommand-line
editingfacilitiesthatwelookedatearlierinthischapter.
manualpage).Allofthe
editingmode
commandsthatwelookedatinthischapterhave
associatedfunctions.Thisallowsyoutocustomizethe
SequenceDescription
Likewise,totestforaterminaltype,youcanusetheform
.Youmustprovidethefullterminalnameonthe
right-handsideofthetest.Thisisusefulwhenyouneeda
terminal-specifickeybinding.Youmay,forinstance,
wanttobindthefunctionkeysofaparticularterminal
Ifyouhaveotherapplicationsthatuse
,you
mightliketokeepyour
-specificbindingsseparate.
Youcandothiswiththelastoftheconditionals.Each
applicationthatuses
Variable
Description
bell-style
prependinganescape
Variable
Description
alsoaffectsthe
Variable
Description
show-all-if-ambiguous
Youcanalsounbindafunctionbyusing
bind-u
withthenameofthefunction;allkeysforthatfunction
willthenbeunbound.Unbindingakeysequencecanbe
bind-x
isusefulifyouwanttobindashellcommandtoa
keysequence.Forexample,
bind-x`"\C-l":ls
'binds
CTRL-Ltothe
command.HittingCTRL-Lwouldthen
Anotheroptionyoumightfindusefulis
.Thisprints
outthebindingstostandardoutputinaformatthatcanbe
re-readby
,orusedasa
file.So,tocreatea
includejustafewofthem.Ifyouuseemacs-modeand
youaren'tfamiliarwiththefull
Afterafewhoursspentlearningthesekeystrokes,you
willwonderhowyouevergotalongwithout
UNIXitselfgivesyoutoolstoworkwiththese,suchas
filemanipulationcommands,texteditors,andprint
queues.YourUNIXenvironment'slookandfeelis
Themostimportant
,isreadand
thecommandsinitexecutedby
everytimeyoulog
intothesystem.Ifyouexamineyour
Theselinesdefinethebasicenvironmentforyourlogin
account.Forthemoment,itisprobablybesttoleave
theselinesaloneuntilyouunderstandwhattheydo.
Wheneditingyour
,justaddyournewlines
Notethatwhateveryouaddtoyour
takeeffectuntilthefileisre-readbyloggingoutandthen
logginginagain.Alternatively,youcanalsousethe
1]For example:source .bash_profilesourceexecutesthecommandsinthespecifiedfile,in
thiscase
,includinganycommandsthatyou
allowstwosynonymsfor
derivedfromtheCshell'sfilenamed
,and
derivedfromtheBourneshellandKornshellfilesnamed
.Onlyoneofthesethreeisreadwhenyoulogin.
doesn'texistinyourhomedirectory,then
willlookfor
.Ifthatdoesn'texistitwill
Oneadvantageof
'sabilitytolookforeither
Thefile
isreadandexecutedeverytimea
loginshellexits.Itisprovidedtoroundoutthe
capabilitiesforcustomizingyourenvironment.Ifyou
wantedtoexecutesomecommandsthatremove
temporaryfilesfromyouraccountorrecordhowmuch
timeyouhavespentloggedintothesystemthenyou
wouldplacethecommandsin
.Thisfile
doesn'thavetoexistinyouraccountÑifitisn'tthere
,theUNIXfile-searchingutility,wasnamedasan
Noticethequotesaroundthefull
command;theseare
necessaryifthestringbeingaliasedconsistsofmorethan
4]Asanotherexample,ausefuloptiontothe
commandis
:itputsaslash(
)afterdirectoryfilesandanasterisk
)afterexecutablefiles.Sincetypingadashfollowedby
Withrecursivealiasingavailableitwouldseempossible
ensuresthatthisloopcannothappen,becauseonly
thefirstwordofthereplacementtextischeckedfor
furtheraliasing;ifthatwordisidenticaltothealiasbeing
expanded,itisnotexpandedasecondtime.Theabove
commandwillworkasexpected(typing
producesa
Tomakethevalueofanaliasendinablank,youneedto
surround it withquotes.
Hereishowyouwouldusethiscapabilitytoallowaliases
fordirectorynames,atleastforusewiththe
Thiscauses
tosearchforanaliasforthedirectory
nameargumentto
,whichinthepreviousexample
Anotherwaytodefineadirectoryvariableforusewith
commandistousetheenvironmentvariable
Finally,thereareafewusefuladjunctstothebasic
command.Ifyoutype
withoutanequalsign
)andvalue,theshellwillprintthealias'svalueor
notfound
ifitisundefined.Ifyoutype
forbiddingplace,fulloftersenessanddevoidofgood
Chapter4
showstheorderofprecedence
when,forexample,analiasandafunctionhavethesame
2]Cshellusersshouldnotethatthe
aliasfeature
doesnotsupportargumentsinaliasexpansions,asCshell
aliasesdo.Thisfunctionalityisprovidedby
3]Anothertheoryhasitthat
standsforthe
command"g/re/p",intheold
texteditor,whichdoes
4]ThiscontrastswithCshellaliases,inwhichthequotes
5]Animportantcorollary:wildcardsandotherspecial
characterscannotbeusedinthenamesofaliases,i.e.,on
Table3-1.Basic shell options
OptionDescription
emacsEnters
Doesn'tallowuseofasingleCTRL-Dto
logoff;usethe
commandtologoff
immediately(thishasthesameeffectas
OptionMeaning
OptionMeaning
OptionMeaning
encountersanundefinedvariable,thenyoumaybe
itprocessescommandlines.Thedoublequotes
circumventthispartoftheprocess(bymakingtheshell
quotes"rulein
Chapter1
byadding,"...unlessastring
containsavariable,inwhichcaseyoushouldusedouble
Alistofpatterns,separatedby
colons(:),whichcanhavethe
followingvalues.
linesbeginningwithaspaceare
notenteredintothehistorylist.
:linesmatchingthe
lasthistorylinearenotentered.
:allpreviouslines
matchingthecurrentlineare
removedfromthehistorylist
beforethelineissaved.
:enablesboth
8]HISTIGNOREAlistofpatterns,separatedby
colons(:),usedtodecidewhich
commandlinestosaveinthe
historylist.Patternsare
consideredtostartatthe
beginningofthecommandline
andmustfullyspecifytheline,
i.e.,nowildcard(
)isimplicitly
appended.Thepatternsare
checkedagainstthelineafter
isapplied.
Anampersand(
)matchesthe
previousline.Anexplicit
maybegeneratedbyescapingit
9]HISTFILENameofhistoryfileinwhich
thecommandhistoryissaved.
Themaximumnumberoflines
tostoreinthehistoryfile.The
defaultis500.Whenthis
variableisassignedavalue,the
historyfileistruncated,if
necessary,tothegivennumber
Themaximumnumberof
commandstorememberinthe
commandhistory.Thedefaultis
Variable
Meaning
HISTTIMEFORMAT
10]Thisvariableisnotavailableinversionsof
Inthepreviouschapter,wesawhow
commands.Tofindoutthecurrentcommandnumberin
aninteractiveshell,youcanusethe
.Note
exitaninteractiveshell,
willbethemaximum
numberoflinessavedinyourhistoryfile.Ifyouhave
Anotherusefulvariableis
,which
prependsatimestamptoeachhistoryentryshowing
FormatReplaced by
Thelocale'sappropriatedateandtime
Thecenturynumber(theyeardividedby100
andtruncatedtoaninteger)asadecimal
%dThedayofthemonthasadecimalnumber
%DThedateinAmericanformat;thesamevalue
Thedayofthemonthasadecimalnumber
%hThe same as %b
Thehour(24-hourclock)asadecimal
FormatReplaced by
Thehour(12-hourclock)asadecimal
%jThedayoftheyearasadecimalnumber
%mThe month as a decimal number [01-12]
%MThe minute as a decimal number [00-59]
%nA newline character
%pThe locale's equivalent of either a.m. or p.m
Thetimeina.m.andp.m.notation;inthe
POSIXlocalethisisequivalentto
%RThe time in 24-hour notation (%H:%M)
FormatReplaced by
%SThe second as a decimal number [00-61]
%tA tab character
%TThe time (%H:%M:%S)
Theweekdayasadecimalnumber[1-7],with
Theweeknumberoftheyear(Sundayasthe
firstdayoftheweek)asadecimalnumber
%VTheweeknumberoftheyear(Mondayasthe
firstdayoftheweek)asadecimalnumber
[01-53];iftheweekcontaining1Januaryhas
fourormoredaysinthenewyear,thenitis
consideredweek1Ñotherwise,itisthelast
weekofthepreviousyear,andthenextweek
FormatReplaced by
Theweekdayasadecimalnumber[0-6],with
Theweeknumberoftheyear(Mondayasthe
firstdayoftheweek)asadecimalnumber
[00-53];alldaysinanewyearprecedingthe
%xThe locale's appropriate date representation
%XThe locale's appropriate time representation
Theyearwithoutcenturyasadecimalnumber
%YThe year with century as a decimal number
Thetimezonenameorabbreviation,orby
FormatReplaced by
%%%
Ifyouwantedtohavethedateandtimewitheachhistory
thentheoutputofthe
commandwouldlook
Sincethe
programisnotrunningallthetime,there
Underthesimplestscenario,youusethestandardUNIX
mailprogram,andyourmailfileis
/usr/mail/yourname
IfyouhaveseenenoughexperiencedUNIXusersat
work,youmayalreadyhaverealizedthattheshell's
promptisnotengravedinstone.Manyoftheseusers
haveallkindsofthingsencodedintheirprompts.Itis
possibletoputusefulinformationintotheprompt,
includingthedateandthecurrentdirectory.We'llgive
yousomeoftheinformationyouneedtomodifyyour
Actually,
usesfourpromptstrings.Theyarestored
inthevariables
,and
.Thefirstof
theseiscalledtheprimarypromptstring;itisyourusual
shellprompt,anditsdefaultvalueis"
thenyourpromptswillbelike
alice�1Ñ
alice�2Ñ
CommandMeaning
Theformatispassedtostrftime(3)andthe
resultisinsertedintothepromptstring;an
emptyformatresultsinalocale-specific
\eThe ASCII escape character (033)
\HThe hostname
\hThe hostname up to the first "."
Thenumberofjobscurrentlymanagedby
Thebasenameoftheshell'sterminal
CommandMeaning
CommandMeaning
\wThe current working directory
Thebasenameofthecurrentworking
Thecommandnumberofthecurrent
Thehistorynumberofthecurrent
IftheeffectiveUIDis0,printa#,
\nnnCharacter code in octal
\\Print a backslash
CommandMeaning
Beginasequenceofnon-printing
characters,suchasterminalcontrol
\]End a sequence of non-printing characters
iscalledthesecondarypromptstring;itsdefault
valueis
Anotherimportantvariableis
,whichhelpsthe
Asyouprobablyknow,everycommandyouuseis
actuallyafilethatcontainscodeforyourmachineto
14]Thesefilesarecalledexecutablefilesorjust
executablesforshort.Theyarestoredinvarious
directories.Somedirectories,like
/usr/bin
,are
standardonallUNIXsystems;somedependonthe
particularversionofUNIXyouareusing;someare
uniquetoyourmachine;ifyouareaprogrammer,some
mayevenbeyourown.Inanycase,thereisnoreason
whyyoushouldhavetoknowwhereacommand's
Thatiswhere
comesin.Itsvalueisalistof
directoriesthattheshellsearcheseverytimeyouentera
15]thedirectorynamesareseparatedby
Forexample,ifyoutype
echo$PATH
,youwillsee
Youmaybethinkingthathavingtogoandfinda
commandinalargelistofpossibleplaceswouldtakea
longtime,andyou'dberight.Tospeedthingsup,
Everytimetheshellgoesandfindsacommandinthe
searchpath,itentersitinthehashtable.Ifyouthenuse
thecommandagain,
firstchecksthehashtableto
seeifthecommandislisted.Ifitis,itusesthepathgiven
inthetableandexecutesthecommand;otherwise,itjust
Youcanseewhatiscurrentlyinthehashtablewiththe
Thisnotonlyshowsthehashedcommands,buthow
manytimestheyhavebeenexecuted(the
)duringthe
Supplyingacommandnameto
forcestheshellto
lookupthecommandinthesearchpathandenteritinthe
hashtable.Youcanalsomake
Directorysearchpathand
isavariablewhosevalue,likethatof
isalistofdirectoriesseparatedbycolons.Itspurposeis
Bydefault,
Wehavecoveredtheshellvariablesthatareimportant
fromthestandpointofcustomization.Therearealso
severalthatserveasstatusindicatorsandforvarious
othermiscellaneouspurposes.Theirmeaningsare
relativelystraightforward;themorebasiconesare
Table3-8.Status variables
Nameofyourhome(login)
Numberofsecondssincetheshell
Pathnameofthisinstanceofthe
Theversionnumberoftheshell
Anarrayofversioninformation
Previousdirectorybeforethelast
7]Versionspriorto2.0havemanymorelowercase
19]Inversionsof
priorto2.0,
isa
canbealistofvariablenamesseparatedby
blanks).Youcancombinevariableassignmentandthe
Itisalsopossibletodefinevariablestobeinthe
environmentofaparticularsubprocess(command)only,
byprecedingthecommandwiththevariableassignment,
Youcanputasmanyassignmentsbeforethecommandas
youwant.
21]Forexample,assumethatyou'reusingthe
variables;thesamplebuilt-in
earlierinthis
Youcanfindoutwhichvariablesareenvironment
variablesandwhattheirvaluesarebytyping
withoutargumentsorbyusingthe
optiontothe
Someenvironmentvariablenameshavebeenusedbyso
manyapplicationsthattheyhavebecomestandardacross
manyshellenvironments.Thesevariablesarenotbuilt
,althoughsomeshells,suchastheKornshell,
havethemasbuilt-ins.
Table3-9
liststheonesyouare
Table3-9.Standard variables
VariableMeaning
Thenumberofcolumnsyourdisplay
VariableMeaning
EDITORPathname of your text editor
LINESThe number of lines your display has
SHELLPathname of the shell you are running
TERMThe type of terminal that you are using
22]Notethat
Thevariable
isvitallyimportantforanyprogram
thatusesyourentirescreenorwindow,likeatexteditor.
Suchprogramsincludeallscreeneditors(suchas
Becauseusersarespendingmoreandmoretimewithin
programs,andlessandlessusingtheshellitself,itis
extremelyimportantthatyour
windowundertheXWindowSystemhasadescriptionin
Ifyouaren'tsuccessful,
willprintanerrormessage,and
youwillhavetomakeanotherguessandtryagain.Ifyou
findthat
containsnothingthatresemblesyour
terminal,allisnotlost.Consultyourterminal'smanualto
seeiftheterminalcanemulateamorepopularmodel;
mayhaveseveralentriesthatrelate
Someprograms,suchas
,needtoknowwhattypeof
editoryouwouldliketouse.Inmostcasestheywill
defaulttoacommoneditorlike
Theonlythingsthatreallyneedtobein
environmentvariablesandtheirexportsandcommands
thataren'tdefinitionsbutactuallyrunorproduceoutput
whenyoulogin.Optionandaliasdefinitionsshouldgo
intotheenvironmentfile.Infact,therearemany
Althoughthisisasmall
,thisuser's
environment file could behuge.
20]Unlessautomaticexportinghasbeenturnedonby
Youcanrunascriptbytypingitsnameonlyifthe
directorywherethescriptislocatedisinyourcommand
searchpath,or.(thecurrentdirectory)ispartofyour
commandsearchpath,i.e.,thescript'sdirectorypath(as
discussedin
Chapter3
).Ifthesearen'tinyourpath,you
musttype
,whichisreallythesamethingas
Beforeyoucaninvoketheshellscriptbyname,youmust
alsogiveit"execute"permission.Ifyouarefamiliarwith
theUNIXfilesystem,youknowthatfileshavethreetypes
ofpermissions(read,write,andexecute)andthatthose
permissionsapplytothreecategoriesofuser(thefile's
owner,a
ofusers,andeveryoneelse).Normally,
Figure4-1.Ways to run a shell script
Therearemanyramificationstousingsubshells.An
importantoneisthatthe
edenvironmentvariables
thatwesawinthelastchapter(e.g.,
)areknowninsubshells,whereasothershell
variables(suchasanythatyoudefineinyour
Otherissuesinvolvingsubshellsaretoocomplextogo
intonow;see
Chapter7
Chapter8
function
functname
{
shell commands
or:
functname
{
shell commands
}
Apartfromtheadvantages,therearetwoimportant
oneyouwanttoexecute.We'llexaminethisprocessin
The-
optionforcestypetolookforexecutablefilesor
whichisaspace,TAB,andNEWLINEbydefault.Onthe
otherhand,"
"isequalto"
""
.."
",where
assumethatyouhaveashellscriptcalled
Ifyouinvokethisscriptbytyping
ascriptarg1arg2
,you
Inotherwords,thefunction
changesthevalueof
thevariable
from"outsidefunction"to"in
function,"andthatchangeisknownoutsidethefunction,
havedifferentvaluesinthefunctionand
themainscript.Noticethat
changebecausethe
functionexecutesintheenvironmentoftheshellscript
takesthenameofthescript.
Figure4-2
showsthe
scope of each variablegraphically.
Figure4-2.Functionshavetheirown
Figure4-3
showsthescopeofeachvariableinournew
script.Notethat
nowhasitsown,localcopyof
,althoughtheoriginal
wouldstillbeusedby
Figure4-3.Functionscanhavelocal
wanttocallafunctionwithinyourscriptwiththe
3]Unlesstheoption
Anyargumentthattheoperatormayneedisinsertedto
Thefirstgroupofstring-handlingoperatorstestsforthe
existenceofvariablesandallowssubstitutionsofdefault
valuesundercertainconditions.Thesearelistedin
4]Table4-1.Substitution operators
existsandisn'tnull,
value.Positionalandspecial
"count:undefined!"andexitsif
existsandisn'tnull,
of$
.If
[email protected],the
isthe
Youhavealargealbumcollection,andyouwantto
writesomesoftwaretokeeptrackofit.Assumethatyou
haveafileofdataonhowmanyalbumsyouhaveby
Writeaprogramthatprintsthe
highestlines,i.e.,the
artistsbywhomyouhavethemostalbums.The
defaultfor
shouldbe10.Theprogramshouldtakeone
argumentforthenameoftheinputfileandanoptional
Byfarthebestapproachtothistypeofscriptistouse
built-inUNIXutilities,combiningthemwithI/O
redirectorsandpipes.Thisistheclassic"building-block"
philosophyofUNIXthatisanotherreasonforitsgreat
popularitywithprogrammers.Thebuilding-block
tellsittoreversethecomparisons,soastosortin
Theoutputof
ispipedintothe
utility,which,
whengiventheargument
,printsthefirst
linesofits
inputonthestandardoutput.Theexpression
evaluatestoadash(
)followedbythesecondargumentif
itisgiven,orto-10ifit'snot;noticethatthevariablein
thisexpressionis
,whichisthesecondpositional
minimum,thescriptshouldstartwithafewcomment
linesthatindicatewhatthescriptdoesandwhat
argumentsitaccepts.Second,wecanimprovethe
variablenamesbyassigningthevaluesofthepositional
Asithappens,if
iscalledwithoutafilename
argument,itexpectsinputtocomefromstandardinput,
e.g.,apipe(|)orauser'sterminal.Sinceitdoesn'thave
thepipe,itwillexpecttheterminal.Thismeansthatthe
scriptwillappeartohang!Althoughyoucouldalwayshit
(Makesureyouunderstandwhy.)Ofcourse,thereare
waysofprintingwhatevermessageisdesired;we'llfind
Beforewemoveon,we'lllookmorecloselyatthethree
remainingoperatorsin
Table4-1
andseehowwecan
incorporatethemintoourtasksolution.The
doesroughlythesamethingas
,exceptthatithasthe
Theoperator
substitutesavalueifthegivenvariable
existsandisn'tnull.Hereishowwecanuseitinour
assignlinesofthesortedlist,oneatatime,tothevariable
.Ifwewanttoprintoutjustthealbumname
andignorethenumberofalbums,wecanusesubstring
Thisprintseverythingfromcharacterposition8,whichis
Ifwejustwanttoprintthenumbersandnotthealbum
names,wecandosobysupplyingthelengthofthe
Althoughthisexamplemayseemratheruseless,itshould
giveyouafeelforhowtousesubstrings.When
combinedwithsomeoftheprogrammingfeatures
discussedlaterinthebook,substringscanbeextremely
OperatorMeaning
OperatorMeaning
,theoperationis
appliedtoeachpositional
Thetwopatternsusedhereare
,whichmatches
Graphicsfileconversionutilitiesarequitecommon
Youareimplementingafilterthatpreparesatextfile
forprinteroutput.Youwanttoputthefile's
nameÑwithoutanydirectoryprefixÑonthe"banner"
page.Assumethat,inyourscript,youhavethe
pathnameofthefiletobeprintedstoredinthevariable
Clearly,theobjectiveistoremovethedirectoryprefix
Thissolutionissimilartothefirstlineintheexamples
shownbefore.If
werejustafilename,the
(anythingfollowedbyaslash)wouldnotmatch
andthevalueoftheexpressionwouldbe
untouched.If
theshortestinstanceof"anythingfollowedbyaslash"at
Theconstruct
isactuallyequivalentto
theUNIXutility
takesapathname
Eachoccurrenceofthecolonisreplacedby\n.Aswe
sawearlier,the
optionallows
OperatorMeaning
Matchesexactlyoneofthegiven
Matchesanythingexceptoneofthe
wouldmatchzeroormore
occurrencesof
,and
.Soit
wouldmatchthenullstring,
Thevaluesprovidedcancontainshellwildcardstoo.So,
forexample,
)matchesanumberofoneormore
digits.Thepatternscanalsobenested,soyoucould
removeallfilesexceptthosebeginningwith
by a number bydoing
)).[4]Thecolon(:)inallbutthelastoftheseoperatorsis
actuallyoptional.Ifthecolonisomitted,thenchange
"existsandisn'tnull"to"exists"ineachdefinition,i.e.,
7]PCXisapopulargraphicsfileformatunderMicrosoft
Windows.JPEG(JointPhotographicExpertGroup)isa
¥Thevalueof
$(alice)
isthecontentsofthefile
stringcontainsvariablesorcommandsubstitutions,in
Commandsubstitutionhelpsuswiththesolutiontothe
nextprogrammingtask,whichrelatestothealbum
ThefileusedinTask4-1isactuallyareportderived
fromabiggertableofdataaboutalbums.Thistable
consistsofseveralcolumns,or
,towhichauser
Hereishowwewoulduse
toextractthefourth(year)
argumentisusedtospecifythecharacterusedas
fielddelimiter(TABisthedefault).Theverticalbarmust
bebackslash-escapedsothattheshelldoesn'ttryto
Sendamailmessagetoeveryonewhoiscurrently
Thecommand
tellsyouwhoisloggedin(aswellas
whichterminalthey'reonandwhentheyloggedin).Its
Thefieldsareseparatedbyspaces,notTABs.Sincewe
Thecommand
mailrootmichaelcamkilrath
willrun
Task4-7isanothertaskthatshowshowusefulcommand
commandgivesyoupattern-matchingcapability
withwildcards,butitdoesn'tallowyoutoselectfilesby
modificationdate
Weusethe
searchutilitytomatchthedategivenas
argument(intheform
MonDD
,e.g.,
Jan15
Oct6
,the
latterhavingtwospaces)totheoutputof
ls-l
.Thisgives
usalonglistingofonlythosefileswhosedatesmatchthe
argument.The
optionto
allowsyoutouseall
9]BourneandCshellusersshouldnotethatthe
commandsubstitutionsyntaxofthoseshells,
(withbackwardquotes,orgraveaccents),is
alsosupportedby
forbackwardcompatibility
reasons.However,itishardertoreadandlessconducive
10]Not available in versions ofbashprior to 2.02.[11]SomeolderBSD-derivedsystemsdon'thave
,but
youcanuse
instead.Wheneveryouseeacommand
oftheform:
cut-f
Cfilename
,usethis
12]Forexample,
ls-l
onSunOS4.1.xhasdatesstarting
13]SomeolderBSD-derivedversionsofUNIX(without
SystemVextensions)donotsupportthe
Forthisexample,use42periodsinarowinsteadof
scienceparlanceas
Forexample,considertheseriesofeventsin
Table4-4
Assumethatyouhavejustloggedin,andthatyouarein
Table4-4.pushd/popd example
CommandStack contents
/home/you/lizard/home/
Yourdirectorystackshouldbeinitializedtothenull
stringwhenyoulogin.Todothis,putthisinyour
putthisinyourenvironmentfileifyouhaveone.
statementguaranteesthatDIR_STACKis
knowntoallsubprocesses;youwanttoinitializeitonly
once.Ifyouputthiscodeinanenvironmentfile,itwill
.Thefirstlinemerelysavesthefirstargumentin
Thesecondlineofthefunctionpushesthenewdirectory
ontothestack.Theexpression
evaluatesto
ifitisnon-nullor
(thecurrentdirectoryandaspace)ifitisnull.The
expressionwithindoublequotes,then,consistsofthe
argumentgiven,followedbyasinglespace,followedby
DIR_STACKorthecurrentdirectoryandaspace.The
trailingspaceonthecurrentdirectoryisrequiredfor
patternmatchinginthe
function;eachdirectoryin
Thedoublequotesintheassignmentensurethatallofthis
ispackagedintoasinglestringforassignmentbackto
DIR_STACK.Thus,thislineofcodehandlesthespecial
initialcase(whenthestackisempty)aswellasthemore
Thethirdline'smainpurposeistochangetothenew
directory.Weusethe
operatortohandletheerrorwhen
theargumentismissing:iftheargumentisgiven,thenthe
missingdirectoryname
evaluatesto
,butifitisnotgiven,theshellwill
printthemessage
pushd:dirname:missingdirectory
Thelastlinemerelyprintsthecontentsofthestack,with
theimplicationthattheleftmostdirectoryisboththe
currentdirectoryandatthetopofthestack.(Thisiswhy
wechosespacestoseparatedirectories,ratherthanthe
exiteverythingifnoargumentisgiven;
alwaysexitsfromnon-interactiveshells.It
won't,however,exitaninteractiveshellfromwhichthe
functioniscalled.Thethirddeficiencyisthatit
implementsonlysomeofthefunctionalityof
commandsÑalbeitthemostusefulparts.
Inthenextchapter,wewillseehowtoovercomeallof
Thefourthproblemwiththecodeisthatitwillnotwork
if,forsomereason,adirectorynamecontainsaspace.
Thecodewilltreatthespaceasaseparatorcharacter.
We'llacceptthisdeficiencyfornow,butyoumightlike
tothinkabouthowtoovercomeitinthenextfew
14]Yourcopyof
maynothave
15]Thinkof
cd-
asasynonymfor
cd$OLDPWD
;see
16]bashalsomaintainsadirectorystackforthe
built-ins,accessiblethroughtheenvironment
.Unlikeourversion,however,itis
implementedasan
Chapter6
statement.Ifthestatusis0,theconditionevaluatesto
true;ifitisanythingelse,theconditionisconsidered
false.Thesameistrueforeachconditionattachedtoan
Morespecifically,wecannowimproveonthe
Thisfunctionrequiresavaliddirectoryasitsargument.
directoryyouwerein.Thisisalsoappropriate.Butthe
secondlineofcodehaspushedthebaddirectoryontothe
stackanyway,andthelastlineprintsamessagethatleads
youtobelievethatthepushwassuccessful.Evenplacing
beforethestackassignmentwon'thelpbecauseit
Weneedtopreventthebaddirectoryfrombeingpushed
Thecallto
isnowinsidean
construct.If
Youcanusuallyrelyonbuilt-incommandsandstandard
Exitstatusesaren'tveryusefulforanythingotherthan
theirintendedpurpose.Inparticular,youmaybetempted
non-zeroexitstatus),then
doesn'tevenrun;
thelaststatementthatactuallyranwas
,which
failedÑsothe
clausedoesn'trun,either.Takenall
String comparisons
OperatorTrue if...
str1str1
4]Notethatthereisonlyoneequalsign(
).Thisisa
Wecanuseoneoftheseoperatorstoimproveour
function,whichreactsbadlyifyoutrytopopandthe
Ifthestackisempty,then
isthenull
string,asistheexpression
${DIR_STACK%%}
.This
meansthatyouwillchangetoyourhomedirectory;
instead,wewant
toprintanerrormessageanddo
Toaccomplishthis,weneedtotestforanemptystack,
DIR_STACK=${DIR_STACK#* }cd ${DIR_STACK%% *}echo "$PWD"elseecho "stack empty, still in $PWD."fi}Inthecondition,wehaveplacedthe
doublequotes,sothatwhenitisexpandeditistreatedas
asingleword.Ifyoudon'tdothis,theshellwillexpand
toindividualwordsandthetestwill
Thereisanotherreasonforplacing
doublequotes,whichwillbecomeimportantlateron:
Whilewe'recleaningupcodewewroteinthelast
if [ -z "$1" ]; then
echo 'usage: highest filename [-N]'
exit 1
fi
filename=$1
howmany=${2:--10}
The
exit
utilitytakesafilenameasanargumentandsendsthe
resultsoftheconversiontostandardoutput.Toreducethe
numberofconversionprogramsnecessarytoconvert
�giftopnm $filename $pnmfileelseecho "procfile: $filename is an unknown graphics file."exit 1fi�pnmtojpeg $pnmfile $outfilerm $pnmfileRecallfromthepreviouschapterthattheexpression
Theotherkindofoperatorthatcanbeusedinconditional
expressionschecksafileforcertainproperties.Thereare
24suchoperators.Wewillcoverthoseofmostgeneral
interesthere;therestrefertoarcanalikestickybits,
OperatorTrue if...
filefile
Youhaveexecutepermissionon
,or
directorysearchpermissionifitisa
filefile
'sgroupIDmatchesyours(oroneof
OperatorTrue if...
6]Specifically,the
operatorscompare
topreventtheshellfromtreatingthemspecially),andby
missing(
isnull)first;ifitis,therestofthe
conditionis
executed.Thisisimportantbecause,if
\(\)\(\)\\( -x "$dirname" \) ]; thenthesecondcondition,ifnull,wouldcause
Hereisamorecomprehensiveexampleoftheuseoffile
Writeascriptthatprintsessentiallythesame
Althoughthecodeforthistasklooksatfirstsightquite
complicated,itisastraightforwardapplicationofmany
echo "$1 is a regular file."elseecho "$1 is a special type of file."fiif [ -O "$1" ]; thenecho 'you own the file.'elseecho 'you do not own the file.'fiif [ -r "$1" ]; thenecho 'you have read permission on the file.'fiif [ -w "$1" ]; thenecho 'you have write permission on the file.'fiif [ -x "$1" -a ! -d "$1" ]; thenecho 'you have execute permission on the file.'fiWe'll call this scriptfileinfo. Here's how it works:¥Thefirstconditionaltestsifthefilegivenas
argumentdoesnotexist(theexclamationpointis
the"not"operator;thespacesarounditare
required).Ifthefiledoesnotexist,thescript
printsanerrormessageandexitswitherror
¥Thesecondconditionaltestsifthefileisa
directory.Ifso,thefirstechoprintspartofa
message;rememberthatthe
optiontellsecho
nottoprintaLINEFEEDattheend.Theinner
conditionalchecksifyoudonothavesearch
permissiononthedirectory.Ifyoudon'thave
searchpermission,theword"not"isaddedtothe
precedenceinmathematics,wheremultiplyand
dividearedonebeforeadditionandsubtraction.
Inourcase,
[-x"$1"-a!-d"$1"]
isequivalent
[\(-x"$1"\)-a\(!-d"$1"\)]
.Thefiletests
aredonefirst,followedbyanynegations(
)and
Asanexampleof
'soutput,assumethatyoudoan
areregularfiles,
isadirectory,and
isashellscript.Typing
fileinfoadventure
dodo is a directory that you may search.
you own the file.
Typing
fileinfo core
produces this:
core is a regular file.
342
TestComparison
-geGreater than or equal
-gtGreater than
-neNot equal
You'llfindthesetobeofthemostuseinthecontextof
theintegervariableswe'llseeinthenextchapter.They're
necessaryifyouwanttocombineintegertestswithother
However,theshellhasaseparatesyntaxforconditional
expressionsthatinvolveintegersonly.It'sconsiderably
moreefficient,soyoushoulduseitinpreferencetothe
2]Thebuilt-incommand
issynonymouswith[...].
Forexample,totesttheequivalenceoftwostringsyou
caneitherput[
]or
However,the
loopisidealforworkingwith
itprintoutinformationabouteachdirectory,suchasthe
Theeasiestwaytodothisisbychangingthe
echo "$dir doesn't exist"elif ! [ -d "$dir" ]; thenecho "$dir isn't a directory"elsels -ld $dirfidoneThistime,asthescriptloops,wefirstchecktoseeifthe
lengthof
iszero(causedbyhavingavalueof::in
Hereisaprogrammingtaskthatexploitstheothermajor
Itispossibletoprintoutallofthedirectoriesbelowa
givenonebyusingthe
optionof
.Unfortunately,
thisdoesn'tgivemuchideaaboutthedirectorystructure
becauseitprintsallthefilesanddirectorieslinebyline.
Writeascriptthatperformsarecursivedirectorylisting
andproducesoutputthatgivesanideaofthestructure
Eachcolumnrepresentsadirectorylevel.Entriesbelow
andtotherightofanentryarefilesanddirectoriesunder
thatdirectory.Filesarejustlistedwithnoentriestotheir
right.Thisexampleshowsthatthedirectory
andthefile
areinthecurrentdirectory;the
,andthefile
areunder
directory.Thisscriptisrecursive;whenthefirstargument
isadirectory,anewshellisinvokedandanewscriptis
runonthenewdirectory.Theoldscriptwaitsuntilthe
echo $tryfile
if [ -d "$tryfile" ]; then
thisfile=$tryfile
fi
done
recdir $(command ls $thisfile)
fi
thisfile=${thisfile%/*}
done
directorywillhavetobesuppliedwitharelativepathto
filesfurtherdowninthehierarchy.Todothis,weneedto
keeptrackofthedirectorywearecurrentlyexamining.
4.Hint:youneedatleasttwoothervariablesthat
Atthestartofthissectionwepointedoutthatthe
initsstandardformwasn'tcapableofiteratingovera
specifiedrangeofvaluesascanbedoneinmost
programminglanguages.
2.0introducedanewstyle
loopwhichcatersforthistask;the
checkedinorderuntilamatchisfound;ifnoneisfound,
Thisconstructshouldbecomeclearerwithanexample.
constructinthiscodedoesthesamethingasthe
statementsthatwesawintheearlierversion.Itis,
Thefirstsixpatternsinthe
statementmatchthe
variousfileextensionsthatwewishtoprocess.Thelast
patternmatchesanythingthathasn'talreadybeen
matchedbythepreviousstatements.Itisessentiallya
Thereisanotherslightdifferencetothepreviousversion;
wehavemovedthepatternmatchingandreplacement
insidetheadded
loopthatprocessesallofthe
command-linearguments.Eachtimewepassthroughthe
loop,wewanttocreateatemporaryandfinalfilewitha
namebasedonthenameinthecurrentcommand-line
Wecanimplementthisbyusinga
statementto
checkthenumberofargumentsandthebuilt-in
replacementthatwesawinthelastchapter,theresult
beingassignedto
.Ifthesubstitutiondidn'ttake
place,thepathnamewillbeunchanged.We'llusethisfact
3.Storestheselectedchoiceinthevariablename
andtheselectednumberinthebuilt-invariable
4.Executes the statements in the body
5.Repeatstheprocessforever(butseebelowfor
Hereisataskthataddsanothercommandtoour
Writeafunctionthatallowstheusertoselectadirectory
fromalistofdirectoriescurrentlyinthe
stack.Theselecteddirectoryismovedtothefrontofthe
Thedisplayandselectionofdirectoriesisbesthandledby
Ifyoutype
/usr/home/bin
"andexecute
Thebuilt-inshellvariable
containsthepromptstring
uses;itsdefaultvalueisthenotparticularly
useful"
usedtoexitanysurroundingcontrolstructurewe'veseen
sofar(except
,wherethedoublesemicolonsactlike
)aswellasthe
wewillseesoon.
Wehaven'tintroduced
untilnowbecauseitis
consideredbadcodingstyletouseittoexitaloop.
However,itcanmakecodeeasiertoreadifused
isnecessaryforexiting
whenthe
13]Now we'll add the missing pieces to the code:selectd ( ){PS3='directory? 'dirstack=" $DIR_STACK "select selection in $dirstack; doif [ $selection ]; thenDIR_STACK="$selection${dirstack%% $selection *}"DIR_STACK="$DIR_STACK ${dirstack##* $selection }"DIR_STACK=${DIR_STACK% }cd $selectionbreakelseecho 'invalid selection.'fidone}Thefirsttwolinesinitializeenvironmentvariables.
isacopyof
withspaces
appendedatthebeginningandendsothateachdirectory
inthelistisoftheform
spacedirectoryspace
.Thisform
simplifiesthecodewhenwecometomanipulatingthe
statementsarethesameasinourinitial
function.Thenewcodeinsidethe
pattern-matchingcapabilitytomanipulatethedirectory
toit.Thevalueof
/bin/home
11]selectis not available inbashversions prior to 1.14.[12]Versionsof
priorto1.14.3haveaseriousbug
.Theseversionswillcrashifthe
listis
empty.Inthiscase,surround
swithatestforanull
13]AusercanalsotypeCTRL-D(forend-of-input)to
executesaslongastheconditionistrue;in
,itruns
aslongastheconditionisfalse.The
conditionis
checkedatthe
oftheloop,
atthebottomasitisin
Theresultisthatyoucanconvertany
intoa
bysimplynegatingthecondition.Theonlyplacewhere
ls -ld ${path%%:*}path=${path#*:}doneThefirstlinecopies
toatemporarycopy,
andappendsacolontoit.Normallycolonsareusedonly
Thisisafairlysimpleuseof
.First,weusethe
commandtoperformthecopyforus.Ifitcan'tperform
Afterthe
Thisusesthe
searchutilitytotestif
matchesthe
appropriatepattern.Todothisweprovidetheregular
()case $1 in-a )process option -a;;-b )process option -b;;-c )process option -c;;* ) echo 'usage: alice [-a] [-b] [-c] args...'exit 1esacshiftdonenormal processing of arguments...Thiscodechecks
repeatedlyaslongasitstartswitha
dash(
).Thenthe
constructrunstheappropriate
codedependingonwhichoption
is.Iftheoptionis
invalidÑi.e.,ifitstartswithadashbutisn't
,or
Wehavemodifiedthecodeinthe
constructtoreflect
Thisscriptworksquitewell,inthatitwillconvertthe
variousdifferentgraphicsfilesthatwehavelyingaround
intoJPEGfilessuitableforourwebpage.However,
Wecanchangethesizeofanimagebyusingthe
The
while
,
3]Youcanalsoturnoffthe
OptionMeaning
-rMakes the variables read-only
Marksthevariablesforexportviathe
onitsowndisplaysthevaluesofall
variablesintheenvironment.The
optionlimitsthis
displaytothefunctionnamesanddefinitionscurrentlyin
theenvironment.
limitsitfurtherbydisplayingonly
optiondeclares
avariabletypethatwe
Inthefirstexample,thevariablesareordinaryshell
variablesandtheresultisjustthestring"val1*val2".In
thesecondexample,allofthevariableshavebeen
declaredastype
.Thevariable
containsthe
[
The
We'llshowwherethisfitsintheoverallschemeof
OperatorMeaning
+Plus
-Minus
/Division (with truncation)
**Exponentiation
10]Bit-shift left
��Bit-shift right
OperatorMeaning
,Sequential evaluation
10]Note that ** is not in the C language.The++and-operatorsareusefulwhenyouwantto
incrementordecrementavaluebyone.
11]Theyworkthe
sameasinJavaandC,e.g.,
incrementsvalueby
1.Thisiscalled
;thereisalsoa
.Thedifferencebecomesevident
Inbothcasesthevaluehasbeenincrementedbyone.
However,inthefirstcase(post-increment)thevalueof
thevariablewaspassedtoechoand
thevariablewas
incremented.Inthesecondcase(pre-increment)the
incrementwasperformedandthenthevariablepassedto
Parenthesescanbeusedtogroupsubexpressions.The
OperatorMeaning
=Less than or equal to
�=Greater than or equal to
==Equal to
!=Not equal to
&&Logical and
||Logical or
Forexample,
$((3�2))
hasthevalue1;
$(((3�2)||(4
=1)))
alsohasthevalue1,sinceatleastoneofthetwo
OperatorMeaning
-eqEqual to
-neNot equal to
Theaboveexpressionusingthisconstructbecomes
(((3
�2)&&(4=1)))
AssignmentValue
AssignmentValue
`17 & 3'1
`17 | 3'19
`17 ^ 3'18
echo " ($((total/1048576)) Mb)"elif [ $total -ge 1024 ]; thenecho " ($((total/1024)) Kb)"fifidoneToobtainthediskusageoffilesanddirectories,wecan
usetheUNIXutility
.Thedefaultoutputof
isalist
ofdirectorieswiththeamountofspaceeachoneuses,
405
line,wecanusethe
optionof
.Oncewehavethe
line,wewantonlythenumberofblocksandcanthrow
awaythedirectoryname.Forthisweuseouroldfriend
Oncewehavethetotal,wecanmultiplyitbythenumber
ofbytesinablock(1024inthiscase)andprinttheresult
intermsofbytes.Wethentesttoseeifthetotalisgreater
thanthenumberofbytesinonemegabyte(1048576
bytes,whichis1024
1024)andifitis,wecanprinthow
manymegabytesitisbydividingthetotalbythislarge
number.Ifnot,weseeifitcanbeexpressedinkilobytes,
Weneedtomakesurethatanyspecifieddirectoriesexist,
willprintanerrormessageandthescript
willfail.Wedothisbyusingthetestforfileordirectory
Toroundoutthisscript,itwouldbenicetoimitate
closelyaspossiblebyprovidingformultiplearguments.
Todothis,wewrapthecodeina
loop.Noticehow
takeadditionaltypesof
pushd+n
takesthenthdirectoryinthestack
(startingwith0),rotatesittothetop,and
sto
withoutarguments,insteadof
complaining,swapsthetwotopdirectoriesonthe
popd+n
takesthenthdirectoryinthestackand
DIR_STACK=${DIR_STACK#* }
cd ${DIR_STACK%% *}
echo "$PWD"
else
echo "stack empty, still in $PWD."
fi
}
Thefirstlineoftheloopbodycopiesthefirstdirectoryon
thestackto
DIR_STACK=${DIR_STACK#* }
DIR_STACK="$seconddir $firstdir $DIR_STACK"
else
# normal case of pushd dirname
DIR_STACK="$dirname ${DIR_STACK:-$PWD" "}"
else
echo still in "$PWD."
fi
fi
}
popd ( )
{
if [ $(echo $1 | grep '^+[0-9][0-9]*$') ]; then
fi
fi
}
directorymissing,anda
isperformedincasethe
5.bash'sversionsof
alsohavea
option.Inbothcases
causesthe
directoryfromtheright-handsideofthelistto
havetheoperationperformedonit.Aswith
6.Use
endingcondition
becomesfalseortheloopisexitedvia
Thescriptbeginswitha
loopusingavariable
;the
11]++and-arenotavailableinversionsof
priorto
Thisassigns
toelement
toelement
Anotherwaytoassignvaluesiswithacompound
)Thisisequivalenttothefirstexampleandisconvenient
Anelementinanarraymaybereferencedwiththesyntax
i]}.So,fromourlastexampleabove,the
echo${names[5]}
wouldprintthestring
"duchess".Ifnoindexissupplied,arrayelement0is
Youcanalsousethespecialindices
.These
Ausefuloperatorthatyoucanusewitharraysis
,the
lengthoperatorthatwesawin
Chapter4
.Tofindoutthe
lengthofanyelementinthearray,youcanuse
.Similarly,tofindouthowmanyvalues
thereareinthearray,use
astheindex.So,for
names=(hatter[5]=duchessalice)
hasthe value 7, and${#names[@]}has the value 3.Reassigningtoanexistingarraywithacompoundarray
statementreplacestheoldarraywiththenewone.Allof
theoldvaluesarelost,eveniftheywereatdifferent
indicestothenewelements.Forexample,ifwe
tobe
tweedledum),thevalues
,and
Youcandestroyanyelementortheentirearraybyusing
Toendthischapter,herearesomeproblemsrelatingto
1.ImprovetheaccountIDscriptsothatitchecks
16]Actually,upto599147937791.That'salmostsix
RedirectorFunction
Forcestandardoutputto
evenif
RedirectorFunction
Directfiledescriptor
;appendto
Duplicatestandardoutputtofiledescriptor
Duplicatestandardinputfromfile
Filedescriptor
ismadetobeacopyof
Filedescriptor
ismadetobeacopyof
Directsstandardoutputandstandarderror
&-Close the standard input.
RedirectorFunction
�&-Close the standard output.
�&-Close the output from file descriptor
&-Close the input from file descriptor
isnotspecified,thestandardoutput
(filedescriptor1)isused.Ifthedigitsin
worddonotspecifyafiledescriptoropen
foroutput,aredirectionerroroccurs.Asa
specialcase,if
isomitted,andworddoes
notexpandtooneormoredigits,the
standardoutputandstandarderrorare
Ifwordexpandstooneormoredigits,the
filedescriptordenotedby
ismadetobe
acopyofthatfiledescriptor.Ifthedigits
inworddonotspecifyafiledescriptor
openforinput,aredirectionerroroccurs.
Ifwordevaluatesto-,filedescriptornis
RedirectorFunction
closed.Ifnisnotspecified,thestandard
Movesthefiledescriptordigittofile
,orthestandardoutput(file
Movesthefiledescriptordigittofile
,orthestandardinput(file
descriptor0)ifnisnotspecified.digitis
Noticethatsomeoftheredirectorsin
Table7-1
containa
,andthattheirdescriptionscontaintheterm
Thefirsttwonewredirectors,
,aresimple
variationsonthestandardoutputredirector
.The
appendstotheoutputfile(insteadofoverwritingit)ifit
alreadyexists;otherwiseitactsexactlylike
.Acommon
useof
isforaddingalinetoaninitializationfile(such
)whenyoudon'twanttobotherwith
aren'tveryinterestingwhenusedfromthecommand
prompt.Infact,it'sthesameasthenormaluseof
standardinputexceptforthelabel.Wecouldusea
here-documenttosimulatethe
facility.Whenyou
sendamessagetosomeonewiththe
utility,youend
themessagewithadot(.).Thebodyofthemessageis
Here-documentsaremeanttobeusedfromwithinshell
*) [email protected] ;;
esac
BUGADDR="${1-$BUGBASH}"
��if (uname) /dev/null 2&1; then
UN=`uname -a`
fi
�cat $TEMP EOF
From: ${USER}
Configuration Information [Automatically generated, do not change]:
Machine: $MACHINE
bash Version: $RELEASE
Patch Level: $PATCHLEVEL
Description:
Thefirsteightlinesaregeneratedwhen
installed.Theshellwillthensubstitutetheappropriate
valuesforthevariablesinthetextwheneverthescriptis
Theredirector
hastwovariations.First,youcan
Makesureyouarecarefulwhenchoosingyour
Aslightvariationonthisisprovidedbythe
herestring
.It
takestheform
;thewordisexpandedand
supplied on the standardinput.
Youwanttostartalongjobinthebackground(sothat
yourterminalisfreedup)andsavebothstandardoutput
andstandarderrorinasinglelogfile.Writeascriptthat
outputandstandarderrortothelogfile(asabove)andto
Thecommand
takesitsstandardinputandcopiesitto
Thesescriptshaveoneshortcoming:youmustremain
OptionFunction
acceptsanumberof
escapesequences
thatstartwith
abackslash.
2]They are listed inTable 7-3.Thesesequencesexhibitfairlypredictablebehavior,
exceptfor
:onsomedisplays,itcausesascreenclear,
whileonothersitcausesalinefeed.Itejectsthepageon
mostprinters.
SequenceCharacter printed
\EEscape character
3]\fFORMFEED or CTRL-L
NEWLINE(notatendofcommand)or
SequenceCharacter printed
Theeight-bitcharacterwhosevalueisthe
hexadecimal(base-16)value
(oneor
\\Single backslash
3]Not available in versions ofbashprior to 2.0.The\n,\0,and
sequencesareevenmore
device-dependentandcanbeusedforcomplexI/O,such
quotes.Thesecondpartisanargumentlist,suchasalist
ofstringsorvariablevaluesthatcorrespondtotheformat
specifications.(Theformatisreusedasnecessarytouse
upallofthearguments.Iftheformatrequiresmore
argumentsthanaresupplied,theextraformat
specificationsbehaveasifazerovalueornullstring,as
appropriate,hadbeensupplied).Aformatspecificationis
precededbyapercentsign(%),andthespecifierisoneof
thecharactersdescribedbelow.Twoofthemainformat
Thissoundscomplicatedbutwecanbeginbyre-casting
Thisprints
helloworld
onalineofitsown,justasthe
previousexampledid.Theword
hasbeenassigned
tothefirstformatspecification,
.Likewise,
beenassignedtothesecond
thenprintsthese
Wecouldalsoachievethesameresultbymaking
Table7-4.printf format specifiers
SpecifierDescription
ASCIIcharacter(printsfirstcharacterof
%dDecimal integer
%iSame as %d
Floating-pointformat([-]
dd)(see following text for meaning ofprecision)%EFloating-pointformat([-]d.precisionE[+-]dd)%fFloating-point format ([-]
%eor%fconversion,whicheverisshorter,
SpecifierDescription
%Eor%fconversion,whicheverisshortest,
%oUnsigned octal value
%sString
%uUnsigned decimal value
Unsignedhexadecimalnumber;usesa-ffor
Unsignedhexadecimalnumber;usesA-Ffor
%%Literal %
commandcanbeusedtospecifythewidthand
alignmentofoutputfields.Aformatexpressioncantake
threeoptionalmodifiersfollowing%andprecedingthe
Thewidthoftheoutputfieldisanumericvalue.When
youspecifyafieldwidth,thecontentsofthefieldare
right-justifiedbydefault.Youmustspecifyaflagof"-"
Youcanspecifyboththewidthandprecision
dynamically,viavaluesinthe
argumentlist.You
Inthisexample,thewidthis5,theprecisionis6,andthe
isoptional.Itsexactmeaningvariesby
ConversionPrecision means
Thenumberofdigitstotherightofthe
Themaximumnumberofsignificant
Themaximumnumberofcharactersto
Finally,oneormore
mayprecedethefieldwidth
andtheprecision.We'vealreadyseenthe"-"flagfor
left-justification.Therestoftheflagsareshownin
Table7-6.Flags for printf
CharacterDescription
Left-justifytheformattedvaluewithinthe
CharacterDescription
Prefixpositivevalueswithaspaceand
Alwaysprefixnumericvalueswithasign,
Useanalternateform:%ohasapreceding
0;%xand%Xareprefixedwith0xand
0X,respectively;%e,%Eand%falways
haveadecimalpointintheresult;and%g
and%Gdonothavetrailingzeros
Padoutputwithzeros,notspaces.This
onlyhappenswhenthefieldwidthiswider
thantheconvertedresult.IntheC
language,thisflagappliestoalloutput
formats,evennon-numericones.For
Besidesthestandardspecifiersjustdescribed,the
shell(andotherPOSIXcompliantshells)acceptstwo
additionalspecifiers.Theseprovideusefulfeaturesatthe
expenseofnonportabilitytoversionsofthe
commandfoundinsomeothershellsandinotherplaces
Whenusedinsteadof%s,expands
-styleescape
Whenusedinsteadof%s,printsthestringargument
insuchawaythatitcanbeusedforshellinput.For
issortofan"escapehatch"from
traditionalshellprogrammingphilosophy,whichdictates
thatthemostimportantunitofdatatoprocessisa
,andthatUNIXutilitiessuchas
ConsiderthecaseofaUNIXmachinethathasterminals
thatarehardwiredtotheterminallinesofthemachine.It
machines'masterterminalistheconsole,whichhasa
Wecanuse
command).Ifamatchisfound,
I/Oredirectionandmultiple
Onewaytosolvetheproblemiswitha
,aswe'll
seeinthenextchapter.Thisinvolvescreatingaseparate
processtodothereading.However,itisusuallymore
efficienttodoitinthesameprocess;
givesusfour
statementtakesinputfrom
.Thismakessensebecausetheseareall
compoundstatements
thattheshelltreatsassingle
commandsforthesepurposes.Thistechniqueworks
commandreadsalineatatimeÑaslong
ButifyouwanttoredirectI/Otoorfromanarbitrary
groupofcommandswithoutcreatingaseparateprocess,
Tohelpyouunderstandhowthisworks,thinkofthecurly
Asanotherexampleofcommandblocks,considerthe
caseofcreatingastandardalgebraicnotationfrontendto
isaUNIXutilitythatsimulatesa
5]{ while read line; doecho "$(alg2rpn $line)"done} | dcWe'llassumethattheactualconversionfromonenotation
totheotherishandledbyafunctioncalled
.It
takesalineofstandardalgebraicnotationasanargument
andprintstheRPNequivalentonthestandardoutput.The
loopreadslinesandpassesthemthroughthe
conversionfunction,untilanEOFistyped.Everythingis
executedinsidethecommandblockandtheoutputis
Theothertypeoftasktowhich
issuitedis
promptingauserforinput.Thinkaboutit:wehave
hardlyseenanysuchscriptssofarinthisbook.Infact,
theonlyoneswerethemodifiedsolutionstoTask5-4,
Asyou'veprobablyfiguredout,
We'llnowlookatamorecomplexexamplebyshowing
howTask5-5wouldbedoneif
didn'texist.
Eachsuccessiveitemreadinisassignedtothegiven
dodo$Inthiscase,thearray
nowcontainstheitems
Adelimitercanbespecifiedwiththe-
option.Thiswill
readalineupuntilthe
characterofthedelimiteris
Theoption
canbeusedonlywithscriptsrunfrom
interactiveshells.Itcauses
tobeusedtogather
theinputline,whichmeansthatyoucanuseanyofthe
The-
optionspecifieshowmanycharacterswillberead
.Forexample,ifwespecifythatitshouldread
optionfollowedbyastringargumentprintsthe
stringbeforereadinginput.Wecouldhaveusedthisin
theearlierexamplesof
,whereweprintedouta
promptbeforedoingtheread.Forexample,thedirectory
selectionscriptcouldhaveused
read-p`directory?'
The-
optionforcesreadtonotechothecharactersthat
aretypedtotheterminal.Thiscanbeusefulincases
whereashellmaywanttotakesinglekeystroke
commandswithoutdisplayingthetypedcharactersonthe
6]-a,-d,-e,-n,-
p,-t
arenotavailableinversions
473
Figure7-1.Stepsincommand-line
1.Splitsthecommandintotokensthatareseparated
Italsoallowsaliasesforkeywordstobedefined,
aliasaslongas=while
4.Performsbraceexpansion.Forexample,
5.Substitutestheuser'shomedirectory(
fortildeifitisatthebeginningofaword.
Chapter4
,i.e.,asafunctioncommand,thenasa
built-in,thenasafileinanyofthedirectoriesin
ls-l$(type-pathcc)~alice/
ls-l
foritsalias
"ll".TheshellthenrepeatsSteps1through3;
ls-l$(type-pathcc)~alice/
ls-l$(type-pathcc)/home/alice/
ls-l$(type-pathcc)/home/alice/
ls-l/usr/bin/cc/home/alice/
doescommand
ls-l/usr/bin/cc/home/alice/.*537
(thearchaiccommandsubstitutiondelimiter),
Table7-7
hassimpleexamplestoshowhowthesework;
theyassumethestatement
wasrunand
ExpressionValue
"'$person'"'hatter'
~alice/home/alice
"~alice"~alice
`~alice'~alice
Inthiscaseweavoidplungingthefunctionintoa
recursiveloopbyplacing
infrontof
.This
Table7-8.command options
OptionDescription
-pUses a default value for
Printsthecommandorpathnameusedto
-VA more verbose description than with
-Turns off further option checking
optionisadefaultpathwhichguaranteesthatthe
commandlookupwillfindallofthestandardUNIX
utilities.Inthiscase,
willignorethedirectories
isverysimilarto
butismore
restrictive.Itlooksuponlybuilt-incommands,ignoring
functionsandcommandsfoundin
.Wecouldhave
Thelastcommandenablesanddisablesshellbuilt-insÑit
iscalled
.Disablingabuilt-inallowsashellscript
orexecutableofthesamenametoberunwithoutgivinga
fullpathname.Considertheproblemmanybeginning
UNIXshellprogrammershavewhentheynameascript
.Muchtotheirsurprise,executing
usuallyresults
innothing,becausetheshellisexecutingthebuilt-in
ratherthantheshellscript.Disablingthebuilt-inwith
11]Table7-9
liststheoptionsavailablewith
12]Someoptionsareforworkingwith
dynamicallyloadable
built-ins.See
AppendixC
OptionDescription
enable-p
willlistallenabledbuilt-ins,
enable-n
Insteadofproducingapaginatedfilelisting,theshellwill
asargumentsto
,and
willcomplain
thatnofilesofthosenamesexist.Why?Becausethepipe
character"appears"inStep6whentheshellevaluatesthe
ithasactuallylookedforpipecharacters.
Thevariable'sexpansionisn'tevenparseduntilStep9.As
aresult,theshellwilltreat
asargumentsto
sothat
willtrytofindfilescalled
inthe
Nowconsider
eval$listpage
insteadofjust
pipelinethatsortsafileandprintsoutthefirst
Thefirstargumentspecifiedthefiletosort;
isthe
Nowsupposewechangethetaskjustabitsothatthe
defaultistoprintthe
entirefile
insteadof10lines.This
meansthatwedon'twanttouse
atallinthedefault
sort -nr $1 | head -$2elsesort -nr $1fiInotherwords,wedecidewhichpipelinetorun
isnull.Onceagain,wecan'tjustrunthiscommand
becausethepipeis"uncovered"afterthe
shelltriestobreakthelineupintocommands.
causestheshelltorunthecorrectpipelinewhen
Next,we'llrevisitTask7-2fromearlierinthischapter,
isknownprimarilyasaprogrammer'stool,butit
seemsasthoughsomeonefindsanewuseforitevery
sources
and
done
}
upwiththefinalimage.Ifitweren'tforhavingtousea
particularconversionutility,wecouldreducethescriptto
exit 1 ;;
esac
done
shift $(($OPTIND - 1))
echo $usage
fi
case $filename in
*.gif ) convert='giftopnm' ;;
case $filename in
*.gif ) convert='giftopnm' ;;
*.tga ) convert='tgatoppm' ;;
commandstomakethem.Modify
sothatitallowsforsymbolic
2.Youcouldusetheabovetechnique
expressionsinalgebraicnotationhave
theform
expropexpr
,whereeach
iseitheranumberoranotherexpression
(perhapsinparentheses),andopis+,-,
x,/,or
(remainder).InRPN,
expressionshavetheform
exprexprop
Forexample:thealgebraicexpression
23+
inRPN;theRPNequivalent
(2+3)x(9-5)
23+95-x
.The
mainadvantageofRPNisthatit
obviatestheneedforparenthesesand
operatorprecedencerules(e.g.,xis
evaluatedbefore+).The
acceptsstandardRPN,buteach
expressionshouldhave"p"appendedto
it,whichtellsdctoprintitsresult;e.g.,
thefirstexampleaboveshouldbegiven
2 3 +p
5.Youneedtowritearoutinethatconverts
algebraicnotationtoRPN.Thisshould
be(orinclude)afunctionthatcallsitself
(arecursivefunction)wheneverit
encountersasubexpression.Itis
especiallyimportantthatthisfunction
keeptrackofwhereitisintheinput
stringandhowmuchofthestringit"eats
up"duringitsprocessing.(Hint:make
useofthepattern-matchingoperators
discussedin
Chapter4
toeasethetaskof
parsinginputstrings.)Tomakeyourlife
easier,don'tworryaboutoperator
precedencefornow;justconverttoRPN
fromlefttoright:e.g.,treat
.This
makesitpossibleforyoutoconvertthe
inputstringonthefly,i.e.,without
havingtoreadinthewholethingbefore
6.Enhanceyoursolutiontotheprevious
exercisesothatitsupportsoperator
precedenceinthe"usual"order:x,/,
(remainder)+,-.Forexample,treat
.You'llalsoneed
andoneormoreoftheconversion
newrow.Notethatyou'llneedtobuild
uptherowsindividuallyanduse
12]The-d,-f,-p,and
optionsarenotavailablein
13]BecarefulÑitispossibletodisable
-nenable
).Thereisacompile-timeoptionthatallows
Inthisexample,93istheprocessIDforthe
isa
jobnumber
assignedbytheshell(notthe
operatingsystem).What'sthedifference?Jobnumbers
refertobackgroundprocessesthatarecurrentlyrunning
underyourshell,whileprocessIDsrefertoallprocesses
currentlyrunningontheentiresystem,forallusers.The
basicallyreferstoacommandlinethatwas
Ifyoustartupadditionalbackgroundjobswhilethefirst
1]Themessagesare,bydefault,printedbeforethenext
promptisdisplayedsoasnottointerruptanyoutputon
thedisplay.Youcanmakethenotificationmessages
intotheforeground.Butifyouhaveseveraljobsrunning
inthebackground,theshellwillpicktheonethatyouput
intothebackgroundmostrecently.Ifyouwantsome
otherjobputintotheforeground,youneedtousethe
job'scommandname,precededbyapercentsign(%),or
youcanuseitsjobnumber,alsoprecededby%,orits
processIDwithoutapercentsign.Ifyoudon'tremember
whichjobsarerunning,youcanusethecommand
whosecommandcontainsthestring.Forexample,
$hatter teatime &[2] 190$Thenyoucanuse
toreferto
eachofthem,althoughactually
Table8-1
listsallofthewaystorefertobackgroundjobs.
Givenhowinfrequentlypeopleusejobcontrol
commands,jobnumbersorcommandnamesare
Table8-1.Ways to refer to background jobs
ReferenceBackground job
ReferenceBackground job
%+Most recently invoked background job
%%Same as above
Secondmostrecentlyinvokedbackground
workstation)andyouareusingatexteditorlike
ona
filethatneedstobeprocessed.Forexample,ifyouare
editingafileforthe
textprocessor,youcandothe
$ troff myfiletroff reports an error$ fgvi comes back up in the same place in your fileProgrammersoftenusethesametechniquewhen
Youwillprobablyalsofinditusefultosuspendajoband
resumeitinthebackgroundinsteadoftheforeground.
Youmaystartacommandintheforeground(i.e.,
normally)andfindthatittakesmuchlongerthanyou
expectedÑforexample,a
,ordatabasequery.
Youneedthecommandtofinish,butyouwouldalsolike
controlofyourterminalbacksothatyoucandoother
work.IfyoutypeCTRL-Zfollowedby
,youwill
7]YoucanalsosuspendajobwithCTRL-Y.Thisisslightly
differentfromCTRL-Zinthattheprocessisonlystopped
3]IfyouhaveanolderversionofUNIX,itispossible
thatyoursystemdoesnotsupportjobcontrol.Thisis
particularlytrueformanysystemsderivedfromXenix,
SystemIII,orearlyversionsofSystemV.Onsuch
doesnothavethe
commands,job
numberargumentsto
,typingCTRL-Zto
4]Options-rand-sarenotavailablein
priorto
5]Thisisanalogousto
asreferencestothe
currentandpreviousdirectory;seethefootnotein
Nowthatwe'vetoldyouhowtodothis,weshouldadd
thatwedon'trecommendit.Changingyoursignalkeys
couldleadtotroubleifsomeoneelsehastostopa
Mostoftheothersignalsareusedbytheoperatingsystem
toadviseprocessesoferrorconditions,likeabad
machinecodeinstruction,badmemoryaddress,or
divisionbyzero,or"interesting"eventssuchasatimer
("alarm")goingoff.Theremainingsignalsareusedfor
esotericerrorconditionsofinterestonlytolow-level
systemsprogrammers;newerversionsofUNIXhave
Hereisanexampleof
.Sayyouhavean
inthebackground,withprocessID150andjobnumber
1,whichneedstobestopped.Youwouldstartwiththis
Ifyouweresuccessful,youwouldseeamessagelike
Ifyoudon'tseethis,thentheTERMsignalfailedto
we'llseelaterinthischapter,or(farlesslikely)there'sa
Writeascriptcalled
thatkillsallbackground
YoumaybetemptedtousetheKILLsignalimmediately,
insteadoftryingTERM(thedefault)andQUITfirst.
Don'tdothis.TERMandQUITaredesignedtogivea
processthechanceto"cleanup"beforeexiting,whereas
KILLwillstoptheprocess,whereveritmaybeinits
Youcanusethe
commandwithanyprocessyou
create,notjustjobsinthebackgroundofyourcurrent
shell.Forexample,ifyouuseawindowingsystem,then
youmayhaveseveralterminalwindows,eachofwhich
runsitsownshell.Ifoneshellisrunningaprocessthat
youwanttostop,youcan
itfromanother
windowÑbutyoucan'trefertoitwithajobnumber
becauseit'srunningunderadifferentshell.Youmust
(YoucanignoretheSTATcolumn.)Thisisabitlikethe
command.PIDistheprocessID;TTY(orTT)isthe
terminal(orpseudo-terminal,ifyouareusinga
windowingsystem)theprocesswasinvokedfrom;TIME
istheamountofprocessortime(notrealor"wallclock"
time)theprocesshasusedsofar;COMD(or
COMMAND)isthecommand.NoticethattheBSD
versionincludesthecommand'sarguments,ifany;also
noticethatthefirstlinereportsontheparentshell
withoutargumentslistsallprocessesstartedfromthe
currentterminalorpseudo-terminal.Butsince
isnota
shellcommand,itdoesn'tcorrelateprocessIDswiththe
shell'sjobnumbers.Italsodoesn'thelpyoufindtheIDof
Figure8-1.Backgroundjobsinmultiple
Assumeyouareintheuppermostwindow.Ifyoutype
Nowyoushouldseehow
ps-a
canhelpyoutrackdowna
runawayprocess.Ifit's
,youcantype
kill2389
.If
thatdoesn'twork,try
kill-QUIT2389
,orintheworst
OnBSD-derivedsystems,
ps-a
listsalljobsthatwere
startedonanyterminal;inotherwords,it'sabitlike
concatenatingthetheresultsofplain
foreveryuseron
thesystem.Giventheabovescenario,
ps-a
willshow
youallprocessesthattheSystemVversionshows,plus
ps-a
(onanyversionofUNIX)willnot
reportprocessesthatareincertainconditionswherethey
oftheprocesstowhichyousentthesignal;aprogrammer
coulduseittohelpdebugtheprogramthatwasrunning.
Thefile'snameisa(very)old-fashionedtermfora
computer'smemory.Othersignalsleavethese"core
dumps"aswell;unlessyourequirethem,orsomeoneelse
recognizedbytheinvokingshelloncethefunctionhas
Onceagain,thetrapisredefinedinthefunction;thisis
Aspartofanelectronicmailsystem,writetheshell
Thedirectory
isconventionallyusedfortemporary
files.Manysystemsalsohaveanotherdirectory,
/var/tmp
Nevertheless,aprogramshouldcleanupsuchfilesbefore
itexits,toavoidtakingupunnecessarydiskspace.We
coulddothisinourcodeveryeasilybyaddingtheline
rm$msgfile
afterthecodethatactuallysendsthe
message.Butwhatiftheprogramreceivesasignalduring
execution?Forexample,whatifauserchangeshermind
aboutsendingthemessageandhitsCTRL-Ctostopthe
process?Wewouldneedtocleanupbeforeexiting.We'll
emulatetheactualUNIX
systembysavingthe
messagebeingwritteninafilecalled
Actually,thereisaUNIXcommandcalled
doespreciselythis.The
scriptfromthelastchapter
ThispreventsHUPfromterminatingyourcommandand
savesitsstandardanderroroutputinafile.Actually,the
Ifyouunderstandwhy
isessentiallyredundantwhen
youuse
inthiscase,thenyouhaveafirmgraspon
thematerialinthepreviouschapter.Notethatifyoudon't
specifyaredirectionforanyoutputfromthecommand,
considerableamountsofcodetodealingwithsignals.But
theseprogramsarealmostalwayslargeenoughsothat
thesignal-handlingcodeisatinyfractionofthewhole
13]Thiscommandisthesameasthebuilt-inshellno-op
14]disownisnotavailableinversionsof
priorto
1.Createtwosubprocesses,whichwe'llcallP1and
whenrunningatthesametimeasalong,I/O-intensive
Ontheotherhand,iftwoprocessesuseresourcesin
similarways,itmayevenbelessefficienttorunthemat
thesametimeasitwouldbetorunthemsequentially.
Why?Basically,becauseundersuchcircumstances,the
operatingsystemoftenhasto"time-slice"theresource(s)
Forexample,ifbothprocessesare"diskhogs,"the
operatingsystemmayenteramodewhereitconstantly
parallelmachine,especiallysincesuchmachinesare
We'llshowhowtodothisÑandgiveyouanideaofsome
problemsinvolvedÑbymeansofasimpletaskwhose
Writeautilitythatallowsyoutomakemultiplecopies
We'llcallthisscript
.Thecommand
dest1dest2.
..shouldcopy
toallofthe
destinationsgiven.Thecodeforthisshouldbefairly
Simple,right?Well,thereisonelittleproblem:what
happensiftheuserspecifiesduplicatedestinations?If
Therefore,itshouldn'tsurpriseyouthatmuchresearch
hasbeenandisbeingdoneonparallelization,theultimate
goalbeingtodeviseatoolthatparallelizescode
automatically.(Suchtoolsdoexist;theyusuallyworkin
¥Shellvariables,exceptenvironmentvariablesand
thosedefinedintheenvironmentfile(usually
¥Handling of signals that are not ignored
Wecoveredsomeofthisin
Chapter3
,butthesepoints
acommandblockareknowntotheshellcodeafterthe
Ifyourunthiscode,youwillseethemessage
$hatteris
every60seconds,andifyouhitCTRL-C,youwill
seethemessage,
YouhitCTRL-C!
.Youwillneedtohit
Ifalanguagesupportscodenesting,thenit'sconsidered
desirablethatdefinitionsinsideanestedunithaveascope
limitedtothatnestedunit.Inotherwords,nested
grasponthematerial.Don'tworryifyouhavetrouble
1.Writeashellscriptcalled
thatcombinesthe
commandsbyprintingalistofjobs
withtheirjobnumbers,correspondingprocess
Nowyouknowthat
istheprobable
culpritÑthoughitisalsopossiblethat
Noticethatformultiplelevelsofexpansion,onlythefirst
characterof
isprinted.Thismakestheoutputmore
Youtype
aliceteatime
torunitinthenormalway,andit
hangs.Thenyoutype
bash-xaliceteatime
,andyousee
Ithangsagainatthispoint.Younoticethat
haveafilenameargument,whichmeansthattheremust
Note,however,thatonceyouhaveturned
on,you
won'tbeabletoturnitoff;a
DEBUGThe shell has executed a statement
start of the script
exiting from the script
Ifyoudid,theprogramwillexitwiththemessage,
"Thankyouforplaying!",i.e.,itwillruntheEXITtrap
code.Ifyouwerewrong,itwillpromptyouagainand
ThefakesignalERRenablesyoutoruncodewhenevera
commandinthesurroundingscriptorfunctionexitswith
non-zerostatus.TrapcodeforERRcantakeadvantageof
thebuilt-invariable
,whichholdstheexitstatusofthe
previouscommand.Itsurvivesthetrapandisaccessible
Asimplebuteffectiveuseofthisistoputthefollowing
Thefirstlinesavesthenonzeroexitstatusinthelocal
sincetheerrorwasacommandthattheshellcouldnot
find.Butifthenonzeroexitstatuscomesfromanother
program,theshelldoesn'treportthelinenumber.For
Ifyouusethiswiththeaboveexample,theresultisthe
,ERRORline12:Commandexitedwith
status17
.Thisismuchmoreuseful.We'llseeavariation
Thissimplecodeisactuallynotabadall-purpose
debuggingmechanism.Ittakesintoaccountthata
nonzeroexitstatusdoesnotnecessarilyindicatean
undesirableconditionorevent:rememberthatevery
controlconstructwithaconditional(
Anotherfakesignal,DEBUG,causesthetrapcodetobe
executedbeforeeverystatementinafunctionorscript.
8]Thishastwomainuses.Firstistheuseforhumans,asa
DEBUGtrapandthencallsafunction,thestatements
withinthefunctionwillnotexecutethetrap.Thereare
Noticethatitdidn'ttrapwhenthescriptitselffinished.
Thetrapwouldonlyhaverunattheendofthescriptif
dthescript.Normally,totrapattheexitingof
thescriptwe'dalsoneedtodefineatrapfortheEXIT
Inadditiontothesefakesignals,
3.0addedsome
otherfeaturestohelpwithwritingafull-scaledebugger
.Thefirstoftheseisthe
optiontothe
command,whichswitchesoncertainthingsthat
¥The-Foptionto
displaysthesource
filenameandlinenumbercorrespondingtoeach
¥IfthecommandthatisrunbytheDEBUGtrap
3]Weshouldadmitthatifyouhadturnedonthe
�echo "$_dbname: Cannot read file '$_guineapig'." &2exit 1fishift_tmpdir=/tmp_libdir=._debugfile=$_tmpdir/bashdb.$$ # temporary file for script that isbeing debugged�cat $_libdir/bashdb.pre $_guineapig $_debugfileexec bash $_debugfile $_guineapig $_tmpdir $_libdir "[email protected]"bashdbtakesasthefirstargumentthenameofguineapig
file.Anysubsequentargumentsarepassedontothe
thelastchapter.Ifyoudon'thave(ordon'thaveaccessto)
onyoursystem,thenyoucansubstituteadifferent
directoryfor
11]Thevariable
isthe
nameofthedirectorythatcontainsfilesneededby
).Ifyouareinstalling
onyoursystemforeveryonetouse,youmight
statementbuildsthemodifiedcopyoftheguinea
pigfile:itcontainsthescriptfoundin
we'lllookatshortly)followedbyacopyoftheguinea
Thelastlinerunsthenewlycreatedscriptwith
,a
elif (( $_steps == 0 )); then
_msg "Stopped at line $_curline"
_cmdloop
fi
}
_steptrap
\? | h ) _menu ;; # print command menu
CommandAction
CommandAction
xToggle execution trace on/off
qQuit
Beforelookingattheindividualcommands,itis
importantthatyouunderstandhowcontrolpassesthrough
runsaftereverystatementintheguineapigas
aresultofthetraponDEBUGinthepreamble.Ifa
breakpointhasbeenreachedortheuserpreviouslytyped
inastepcommand(s),
callsthecommandloop.
Indoingso,iteffectively"interrupts"theshellthatis
Theusercaninvokedebuggercommandsaswellasshell
commandsthatruninthesameshellastheguineapig.
Thismeansthatyoucanuseshellcommandstocheck
valuesofvariables,signaltraps,andanyother
informationlocaltothescriptbeingdebugged.The
commandloopcontinuestorun,andtheuserstaysin
control,untilhetypes
,or
Whentheusertypes
Theoveralleffectisthatthethreestepsrunandthenthe
Alloftheotherdebuggercommandscausetheshellto
stayinthecommandloop,meaningthattheuserprolongs
Nowwe'llexaminethebreakpoint-relatedcommandsand
thebreakpointmechanismingeneral.The
callsthefunction
Tocomplementtheuser'sabilitytoaddbreakpoints,we
Anumericargumenttothe
commandmeansthecode
itcontinueslooping,lookingforamatchuntiltheendof
Thisfunctioncontainsasubshell,theoutputofwhichis
pipedtotheUNIX
command.Wehavedonethis
foruser-friendlyreasons;alongscriptwouldscrollupthe
screenquicklyandtheusersmaynothavedisplaysthat
allowthemtoscrollbacktopreviouspagesofscreen
Thecoreofthesubshellcodeloopsthroughthelinesof
theguineapigscript.Itfirstteststoseeifthelineitis
abouttodisplayisinthearrayofbreakpoints.Ifitis,a
breakpointcharacter(
Wethinkyou'llagreethattheaddedcomplexityinthe
handlingofbreakpointsiswellworthit.Beingableto
displaythescriptandthelocationofbreakpointsisan
Break conditions
bashdb
Thefinalfeatureofthedebuggeris
executiontracing
Thefunction
"toggles"executiontracingsimply
byassigningtothevariable
thelogical"not"ofits
Wehavekept
reasonablysimplesothatyoucan
seethefundamentalsofbuildingashellscriptdebugger.
Althoughitcontainssomeusefulfeaturesandisdesigned
tobearealtool,notjustascriptingexample,ithassome
importantlimitations.Somearedescribedinthelistthat
1.Debuggerstendtorunprogramsslowerthanif
theywereexecutedontheirown.
isno
exception.Dependinguponthescriptyouuseit
on,you'llfindthedebuggerrunseverything
anywherefrom8to30timesmoreslowly.This
isn'tsomuchofaproblemifyouarestepping
throughascriptinsmallincrements,butbearitin
mindifyouhave,say,initializationcodewith
2.Thedebuggerwillnot"stepdown"intoshell
scriptsthatarecalledfromtheguineapig.Todo
this,you'dhavetoedityourguineapigscriptand
changeacalltoscriptnameto
3.Similarly,nestedsubshellsaretreatedasone
giganticstatement;youcannotstepdowninto
4.Theguineapigitselfshouldnottraponthefake
signalsDEBUGandEXIT;otherwisethe
5.Commanderrorhandlingcouldbesignificantly
Manyofthesearenotinsurmountableandyoucan
experimentwithsolvingthemyourself;seetheexercises
Thedebuggerfromanearlierversionofthisbookhelped
inspireamorecomprehensive
debuggermaintained
byRockyBernstein,whichyoucanfindattheBash
�bashdb
bp
Breakpoints at lines: 4 11
Break on condition:
�bashdb
!total=5600
�bashdb
g
Total for . = 5600 bytes (5 Kb)
Reached breakpoint at line 11
�bashdb
cb
All breakpoints have been cleared
ds
1: for dir in ${*:-.}; do
2: if [ -e $dir ]; then
Next,wecontinueexecutionofthescriptthatbreaksat
line4.Weprintoutthevalueof
nowanddecideto
clearthebreakpointatline8.Displayingthescript
confirmsthatthebreakpointatline8isindeedgone.We
canalsousethe
command,andittooshowsthatthe
1.Implementitasthecommand-lineoption
2.Implementitasthedebuggercommand
totoggleitonandoff.(Hint:whenyou
isstilltheexitstatus
5.Implementacommandthatprintsoutthestatus
2.Addanothercommand
that,without
anargument,removesallofthevariables
fromthewatchlist.Withanargument,it
8.Althoughplacinganunderscoreatthestartofthe
debuggeridentifierswillavoidnameclashesin
if _at_linenumbp ; then
_msg "Reached breakpoint at line $_curline"
_cmdloop
x ) _xtrace ;; # toggle execution trace
* ) eval ${cmd#!} $args ;; # pass to the shell
* ) _msg "Invalid command: '$cmd'" ;;
esac
done
}
# See if this line number has a breakpoint
function _at_linenumbp
local i=0
# Loop through the breakpoints array and check to see if any of
# to see if the line number contains text. If it doesn't then
# print an error message. If it does then echo the current
# Note that we can remove duplicate breakpoints here by using
# the -u option to sort which uniquifies the list.
if [ -z "$1" ]; then
_listbp
elif [ $(echo $1 | grep '^[0-9]*') ]; then
if [ -n "${_lines[$1]}" ]; then
_linebp=($(echo $( (for i in ${_linebp[*]} $1; do
echo $i; done) | sort -n) ))
# Clear individual or all breakpoints
function _clearbp
local i bps
_msg "Break when true: $_brcond"
else
_brcond=
_msg "Break condition cleared"
fi
}
# Print out the shell script and mark the location of breakpoints
# and the current line
function _displayscript
{
local i=1 j=0 bp cl
( while (( $i ${#_lines[@]} )); do
if [ ${_linebp[$j]} ] && (( ${_linebp[$j]} == $i )); then
bp='*'
10]Unfortunately,thedebuggerwillnotworkwith
versionsof
priorto2.0,becausetheydonot
11]Allfunctionnamesandvariables(exceptthoselocal
tofunctions)in
havenamesbeginningwithan
underscore(_),tominimizethepossibilityofclasheswith
12]execcanalsobeusedwithanI/Oredirectoronly;this
makestheredirectortakeeffectfortheremainderofthe
scriptorloginsession.Forexample,theline
atthetopofascriptdirectsstandarderrortothe
13]Ifyouaretypingorscanninginthepreamblecode
fromthisbook,makesurethatthelastlineinthefileis
[
changesitsbehaviorslightlyifstartedas
,aswe
,aresmallandaremostlyconcernedwiththecommand
lookuporderandhowfunctionsarehandled.Most
isnotCorPOSIX.Thisalsoturns
Interactiveshell.Ignoressignals
TERM,INT,andQUIT.Withjob
controlineffect,TTIN,TTOU,
actasifinvokedasa
Takesthesameargumentsas
Iftheinvocationoptionis
,the
outputisdisplayedinaformatthat
Readscommandsfromthe
standardinput.Ifanargumentis
givento
,thisflagtakes
precedence(i.e.,theargument
won'tbetreatedasascriptname
Restrictedshell.Seethe
Printsshellinputlinesasthey're
Signalstheendofoptionsand
disablesfurtheroptionprocessing.
Anyoptionsafterthisaretreatedas
filenamesandarguments.
Arrangesforthedebuggerprofile
tobeexecutedbeforetheshell
starts.Turnsonextended
debuggingmodeandshellfunction
7]Ñdump-stringsDoes the same as
Doesthesameas-
buttheoutput
isintheGNU
Doesnotreadthestartupfile
ÑverboseEquivalent to
Showstheversionnumberofthis
7]Only available inbashversion 3.0 and later.Themulticharacteroptionshavetoappearonthe
commandlinebeforethesingle-characteroptions.In
additiontothese,any
2]Theexactmessagevariesfromsystemtosystem;
makesurethatyoursprintsthismessagewhengiventhe
nameofashellscript.Ifnot,justsubstitutethemessage
commandprintsfor"shellscript"inthe
3]Theinclusionof
/dev/null
inthe
commandisa
kludgethatforces
toprintthenamesoffilesthat
containamatch,evenifthereisonlyonesuchfileina
4]bashalsoentersPOSIXmodewhenstartedas
Versionsof
priorto2.0don'tÑPOSIXmodehasto
containsthepermissionsthatareturnedoff
bydefaultwheneveraprocesscreatesafile,regardlessof
8]We'lluseoctalnotationtoshowhowthisworks.Asyou
probablyknow,thedigitsinapermissionnumberstand
(lefttoright)forthepermissionsoftheowner,owner's
group,andallotherusers,respectively.Eachdigit,in
turn,consistsofthreebits,whichspecifyread,write,and
executepermissionsfromlefttoright.(Ifafileisa
directory,the"execute"permissionbecomes"search"
OptionResource limited
Eachtakesanumericalargumentthatspecifiesthelimit
inunitsshowninthetable.Youcanalsogivethe
argument"unlimited"(whichmayactuallymeansome
physicallimit),"hard"and"soft",whichrefertothe
currenthardandsoftlimits(seebelow),oryoucanomit
theargument,inwhichcaseitwillprintthecurrentlimit.
ulimit-a
printslimits(or"unlimited")ofalltypes.
10]Youcanspecifyonlyonetypeofresourceatatime.If
Someoftheseoptionsdependonoperatingsystem
capabilitiesthatdon'texistinolderUNIXversions.In
particular,someolderversionshaveafixedlimitof20
filedescriptorsperprocess(making
irrelevant),and
somedon'tsupportvirtualmemory(making
optionshavetodowith
dynamicmemory
,i.e.,memoryforwhichaprocessasksthe
operatingsystematruntime.It'snotnecessaryforcasual
userstolimitthese,thoughsoftwaredevelopersmaywant
todosotopreventbuggyprogramsfromtryingto
optionsaresimilar;
putsalimitonall
usesofmemory,and
limitstheamountofphysical
memorythataprocessisallowedtouse.Youdon'tneed
theseunlessyoursystemhasseverememoryconstraints
optionisanotheroptionwhichisusefulifyou
havesystemmemoryconstraintsoryouwishjustwishto
Youmaywanttospecifylimitsonfilesize(
)if
printscurrentlimits,itprintssoftlimits
Youcanalsoturnonoptions,suchas
modes,or
toprotectagainstinadvertentfile
overwriting.Anyshellscriptsyouhavewrittenfor
Unfortunately,it'snotpossibletocreateaglobalalias.
Youcandefinealiasesin
¥Redirectingoutputtoafile:theredirectors
¥Assigninganewvaluetotheenvironment
,or
¥Specifyinganycommandswithslashes(/)in
them.Theshellwilltreatfilesoutsideofthe
¥Using the
¥Specifyingafilenamecontaininga
asan
¥Importingfunctiondefinitionsfromtheshell
Thismeansthattherestrictedshelluser'sentire
whencreated,willbethatmostheinousof
¥Sitsbackandwaitsfortheusertorunthesuid
shellscriptÑwhichcallstheTrojanhorse,which
inturncreatesthesuidshellandthen
¥Runs the
Finally,ifyouwouldliketolearnmoreaboutUNIX
security,werecommend
Ifyouareusingasourcecontrolsystem(e.g.,CVS),you
candispensewiththeauthoranddateasthesewillbe
storedwhenthescriptisarchived.Ifyouaren'tusingsuch
asystem,westronglyadvisethatyounotonlyincludethe
aboveinformationbutalsoplaceintheheaderadditional
Whateversystemyouuse,makesurethatyoumakethe
Everyfunctionshouldalsohaveaheader.Ifitisa
standalonefunction,itshouldhaveamainheader,as
givenabove.Ifitisafunctionusedlocallyinascript,it
shouldhaveasimplerbannerstatingwhatitdoes,what
...
if [ -d "$startup_dir" ]
# the startup directory exists so read any initialisation file.
657
...Notonlydoesthismakethecodemorereadablebutit
makeschangingthevalueeasier,especiallyifitisused
Thisoptionshoulddirecttheprogramtoprint
informationaboutitsname,version,origin,andlegal
status,allonstandardoutput,andthenexit
successfully.Otheroptionsandargumentsshouldbe
ignoredoncethisisseen,andtheprogramshouldnot
Thisoptionshouldoutputbriefdocumentationfor
howtoinvoketheprogram,onstandardoutput,then
exitsuccessfully.Otheroptionsandarguments
shouldbeignoredoncethisisseen,andtheprogram
Neartheendofthe
option'soutputthere
shouldbealinethatsayswheretomailbugreports.
¥Report bugs to
Table11-1
Long optionOptionExamples where used
Long optionOptionExamples where used
Ñlong-lls
Ñline-lwc
Ñlinks-Lcpio, ls
Ñoutput-occ, sort
Long optionOptionExamples where used
Ñverbose-v
Ñwidth-w
Forcommandsthattakeoneormoreinputfilesand
produceanoutputfileitisconsideredgoodpracticeto
makeonlytheinputfilesnormalarguments(i.e
commandfilename
)andhavetheoutputfilespecifiedby
Anotherthingtowatchoutforisassumingthata
particularenvironmentvariableneededbyyourscripthas
¥Don'tusethesamenamesforvariablesand
andnameyourfunctionsusingverbs,e.g.,
from there.
Oftheotherdocuments,
isaFrequentlyAsked
Questionsdocumentwithanswers,
isthe
manualentryforthe
facility,and
isan
articleabouttheshellthatappearedin
LinuxJournal
,by
Aftertheconfigurationfinishesandyoutype
,the
executableisbuilt.Ascriptcalled
isalso
generated,whichallowsyoutoreportbugsintheformat
maintainerswant.We'lllookathowyouuseit
Oncethebuildfinishes,youcanseeifthe
executableworksbytyping
.Ifitdoesn't,turnto
Toinstall
,type
makeinstall
.Thiswillcreateallof
thenecessarydirectories(
andits
Ifyou'veinstalled
inyourhomedirectory,besureto
addyourown
pathtoyour
andyourown
comespreconfiguredwithnearlyallofitsfeatures
enabled,butitispossibletocustomizeyourversionby
specifyingwhatyouwantwiththe
command-line optionsto
Table12-1
isalistoftheconfigurablefeaturesanda
Table12-1.Configurable features
Supportforthealternateform
ofthe`for'commandthat
behavesliketheClanguage
statement.
Supportforonedimensional
C-shell-likehistoryexpansion
brace-expansionBrace expansion.
Supportforthe
Supportforthe
SupportformatchingPOSIX
regularexpressionsusingthe
binaryoperatorinthe
conditional command.directory-stackSupportforthe
manipulation commands.
Jobcontrolvia
,and
ifsupportedbythe
Supportformultibyte
charactersiftheoperating
systemprovidesthenecessary
support.
Feature
Description
progcomp
intheSingleUnix
Theoptions
Manyothershellfeaturescanbeturnedonoroffby
modifyingthefile
Ifyoudon'thaverootaccessand
doesn'twork,you
canstillmake
yourloginshell.Thetrickisto
replaceyourcurrentshellwith
byusing
Ifyourcurrentshellissimilarto
),youhave
pathname/bash ] && exec /pathname/bash --logintoyour
,where
isthepathtoyour
Youwillalsohavetocreateanemptyfilecalled
.Theexistenceofthisfileprevents
fromreadingyour
andre-executingthe
thusenteringaninfiniteloop.Anyinitialization
codethatyouneedfor
canjustbeplacedin
Ifyourcurrentshellissimilarto
)thingsare
toyour
,where
isthepathtoyour
AnimplementationoftheTenthEditionBourneshell
AnalmostexactcloneoftheKornshell
Especiallyhelpful,ifyoucomefromaKornshell
background,is
.Thiscontainsfunctiondefinitions
forsomecommonKornfacilitiessuchas
2]Thisconfigurationinformationpertainsto
version3.0andlater.Theconfigurationandinstallation
forearlierversionsisfairlyeasy,althoughitdiffersin
Whenaskingaquestion,trytogiveameaningful
HISTCONTROLHISTFILE
HISTIGNOREHISTSIZE
HISTFILESIZEHOSTFILE
HOSTNAMEHOSTTYPE
IGNOREEOFINPUTRC
LC_COLLATELC_MESSAGES
MAILCHECKOLDPWD
POSIXLY_CORRECTPROMPT_COMMAND
SHELLOPTSSHLVL
TIMEFORMATTMOUT
auto_resumehistchars
Functions;the
command;the
usetheolder
insteadof
keyword;the
constructisn'tsupported.
TheBourneshell
commandsonlyacceptprocessIDs.The
optionto
Standard1003.1-2001.Thelatestversionofthestandard
ThePOSIXstandardswerenevermeanttoberigidand
absolute.Thecommitteememberscertainlyweren'tabout
toputgunstotheheadsofoperatingsystem
implementersandforcethemtoadhere.Instead,the
standardsaredesignedtobeflexibleenoughtoallowfor
bothcoexistenceofsimilaravailablesoftware,sothat
existingcodeisn'tindangerofobsolescence,andthe
additionofnewfeatures,sothatvendorshavethe
incentivetoinnovate.Inotherwords,theyaresupposed
tobethekindofthird-partystandardsthatvendorsmight
Asaresult,mostUNIXvendorscurrentlycomplywith
bothstandards.
isnoexception;itisalmost100%
Theshellpartofthestandarddescribesutilitiesthatmust
bepresentonallsystems,andothersthatareoptional,
dependinguponthenatureofthesystem.Onesuchoption
istheUserPortabilityUtilitiesoption,whichdefines
standardsforinteractiveshelluseandinteractiveutilities
likethevieditor.ThestandardÑontheorderof2,000
pagesÑisavailablethroughtheIEEE;forinformation,
Thecommitteemembershadtwomotivatingfactorsto
weighwhentheydesignedtheshellstandard.Ontheone
hand,thedesignhadtoaccommodate,asmuchas
possible,existingshellcodewrittenundervarious
Bourne-derivedshells(theVersion7,SystemV,BSD,
andKornshells).Theseshellsaredifferentinseveral
extremelysubtleways,mostofwhichhavetodowiththe
Itmusthavebeenquitedifficultandtedioustospellout
existingshells'innovationsto"sneakthrough"without
becomingpartofthestandard,whilelistingomitted
historicalversionsofUNIX.Ingeneral,shell
ThePOSIXstandardsupportsfunctions,butthe
semanticsareweaker:itisnotpossibletodefinelocal
Thecommandlookuporderhasbeenchangedtoallow
certainbuilt-incommandstobeoverriddenbyfunctions.
¥Coroutinesaresupported.Twoprocessescan
communicatewithoneanotherbyusingthe
¥Thecommand
haveafiledescriptorspecifiedandcanbeusedto
¥Functionautoloadingissupported.Functionsare
¥One-dimensionalarraysaresupported,although
theyarelimitedinsize(4,096elementsinearly
versionsof
,64Kelementsinlater
¥Thehistorylistiskeptinafileratherthanin
memory.Thisallowsconcurrentinstantiationsof
theshelltoaccessthesamehistorylist,apossible
¥Thereisnodefaultstartupfile.Ifthe
environmentvariable
isnotdefined,
¥The
commandisreplacedwiththemore
¥Theprimarypromptstring(
)doesn'tallow
¥There is no built-in equivalent to
¥Thereisnoprovisionforkeybindingsandno
¥Therearenobuilt-inequivalentsto
.Theyhavetobedefinedasfunctionsif
¥Thehistorysubstitutionmechanismisnot
¥Promptstringsdon'tallowbackslash-escaped
¥Manyofthebashenvironmentvariablesdon't
Inaddition,thestartupandenvironmentfilesforKornare
different,consistingof
andthefilespecifiedby
variable.Thedefaultenvironmentfilecanbe
overriddenbyusingthevariable
.Thereisnologout
Oneimportantadvantagethat
hasover
isthat
theexecutableisonlyaboutathirdthesizeanditruns
considerablyfaster.Weighedagainstthisisthatitisless
POSIX-compliant,hashadnumerouspeopleaddcodeto
it(soithasn'tbeenasstronglycontrolledas
),and
isn'taspolishedaproductas
(forexample,the
shell.
708
portedalargenumberofGNUutilitiestovarious
versionsofMicrosoftWindows.Thegreatest
functionalitycomesunderWindows/NT,Windows2000,
andWindowsXP,althoughtheenvironmentcananddoes
environmentuses
foritsshell,GCCfor
itsCcompiler,andtherestoftheGNUutilitiesforits
Alistofalldouble-quotedstrings
precededby
isprintedonthe
standardouput.Thesearethe
stringsthataresubjecttolanguage
translationwhenthecurrentlocale
isnotCorPOSIX.Thisalsoturns
Interactiveshell.Ignoressignals
TERM,INT,andQUIT.Withjob
controlineffect,TTIN,TTOU,
actasifinvokedasa
Takesthesameargumentsas
Option
Meaning
-O
Signalstheendofoptionsand
disablesfurtheroptionprocessing.
Anyoptionsafterthisaretreatedas
filenamesandarguments.
Arrangesforthedebuggerprofile
tobeexecutedbeforetheshell
starts.Turnsonextended
debuggingmodeandshellfunction
2]Ñdump-stringsDoes the same as
Doesthesameas-
buttheoutput
isintheGNU
actasifinvokedasa
DoesnotusetheGNU
librarytoreadcommandlinesif
Doesnotreadthestartupfile
Option
Meaning
Commandsarereadfrom
,if
present.Anyargumentsafter
filenamesandarguments.
Doesnotreadtheinitializationfile
iftheshellisinteractive.
Thisisonbydefaultiftheshellis
Doesnotreadthestartupfile
actasifinvokedasa
Doesnotperformcurlybrace
DoesnotusetheGNU
librarytoreadcommandlinesif
Changesthebehaviorof
followthePOSIXguidelinesmore
closelywherethedefaultoperation
isdifferent.
1]Atthetimeofwriting,theold1.
versionsof
stillused.Westronglyrecommendthatyouupgradeto
thelatestversion.Wehaveincludedatableofoldoptions
TableB-2
)justincaseyouencounteranoldversionof
CommandMeaning
Theformatispassedtostrftime(3)andthe
resultisinsertedintothepromptstring;an
emptyformatresultsinalocale-specific
\eThe ASCII escape character (033)
\HThe hostname
\hThe hostname up to the first "."
Thenumberofjobscurrentlymanagedby
Thebasenameoftheshell'sterminal
CommandMeaning
CommandMeaning
\wThe current working directory
Thebasenameofthecurrentworking
Thecommandnumberofthecurrent
Thehistorynumberofthecurrent
IftheeffectiveUIDis0,printa#,
\nnnCharacter code in octal
\\Print a backslash
CommandMeaning
Beginasequenceofnon-printing
characters,suchasterminalcontrol
\]End a sequence of non-printing characters
CommandChapterTypeSummary
alias3
CommandChapterTypeSummary
cd1
Changeworking
command7
Runacommand
bypassingshellfunction
compgenD
Generatepossible
CommandChapterTypeSummary
dirs6
Displaythelistof
currentlyremembered
disown8
Removeajobfromthe
do5R
Partofa
,or
done5R
Partofa
,or
echo4
Expandandprintany
elif5RPart of an
CommandChapterTypeSummary
else5RPart of an
enable7
Enableanddisable
esac5RPart of a
eval7
Runthegivenarguments
throughcommand-line
exec9
Replacetheshellwith
exit5
export3
Createenvironment
CommandChapterTypeSummary
fc2
Fixcommand(edit
fg8
Putbackgroundjobin
fi5RPart of an
for5RLooping construct.
function4RDefine a function.
CommandChapterTypeSummary
help1
Displayhelpful
informationonbuilt-in
history1
Displaycommand
if5RConditional construct.
in5RPart of a
jobs1
Listanybackground
kill8
Sendasignaltoa
CommandChapterTypeSummary
local4
logout1
popd4
Removesadirectory
pushd4
Addsadirectorytothe
pwd1
Printtheworking
read7
Readalinefrom
readonly6
Makevariablesread-only
CommandChapterTypeSummary
CommandChapterTypeSummary
Runcommandpipeline
andprintexecution
times.Theformatofthe
outputcanbecontrolled
Printtheaccumulated
userandsystemtimesfor
processesrunfromthe
trap8
CommandChapterTypeSummary
ulimit10
ChapterTypeDescription
4R
ChapterTypeDescription
8R
ProcessIDofthelast
4R
Nameoftheshellorshell
Thefullpathnameusedto
invokethisinstanceof
9A
Anarrayofvalueswhich
arethenumberof
ChapterTypeDescription
9A
ChapterTypeDescription
Thenameofafiletorun
astheenvironmentfile
9A
Anarraywhosemembers
arethelinenumbersin
sourcefilescorresponding
toeachmemberof
isthelinenumberinthe
sourcefilewhere
${FUNCNAME[$i+1]}
wascalled.The
correspondingsourcefile
${BASH_SOURCE[$i+
Anarraywhosemembers
areassignedbythe
binaryoperatortothe
conditionalcommand.The
elementwithindex0isthe
ChapterTypeDescription
portionofthestring
matchingtheentireregular
expression.Theelement
withindex
istheportion
ofthestringmatchingthe
thparenthesized
9A
Anarraycontainingthe
sourcefilenames
correspondingtothe
elementsinthe
Incrementedbyoneeach
timeasubshellorsubshell
environmentisspawned.
Theversionnumberofthis
ChapterTypeDescription
3,6AR
Versioninformationfor
thisinstanceof
.Each
elementofthearrayholds
partsoftheversion
3L
Alistofdirectoriesforthe
Anindexinto
thewordcontainingthe
currentcursorposition.
Thisvariableisavailable
onlyinshellfunctions
invokedbythe
ChapterTypeDescription
invokedbythe
ChapterTypeDescription
ChapterTypeDescription
TheeffectiveuserIDof
9ARU
Anarraycontainingthe
namesofallshell
functionscurrentlyinthe
executioncallstack.The
elementwithindex0isthe
nameofany
currently-executingshell
function.Thebottom-most
elementis"main".This
variableexistsonlywhena
Thedefaulteditorforthe
Alistofnamestoignore
whendoingfilename
ChapterTypeDescription
Alistofpatternsdefining
filenamestoignoreduring
Anarraycontainingalist
ofgroupsofwhichthe
TheInternalField
Separator:alistof
charactersthatactasword
ChapterTypeDescription
:lines
beginningwithaspaceare
notenteredintothehistory
:lines
matchingthelasthistory
linearenotentered.
:allprevious
linesmatchingthecurrent
linetoareremovedfrom
thehistorylistbeforethe
lineissaved.
enablesboth
Thenameofthecommand
Alistofpatternstodecide
ChapterTypeDescription
Themaximumnumberof
lineskeptinthehistory
HISTTIMEFORMAT3
ChapterTypeDescription
Thenameofthecurrent
Thetypeofmachine
ThenumberofEOF
charactersreceivedbefore
ChapterTypeDescription
variablespecifyinga
ChapterTypeDescription
ChapterTypeDescription
Thepreviousworking
Thevalueofthelast
optionargumentprocessed
ChapterTypeDescription
6A
Anarrayvariable
containingalistofexit
statusvaluesfromthe
processesinthemost
recentlyexecuted
Ifintheenvironmentwhen
starts,theshellenters
posixmode
beforereading
thestartupfiles,asifthe
invocationoption
hadbeensupplied.Ifitis
ChapterTypeDescription
Theprimarycommand
Thepromptstringforline
Thepromptstringforthe
Thepromptstringforthe
8R
TheprocessIDofthe
Thecurrentworking
ChapterTypeDescription
9U
Arandomnumber
ChapterTypeDescription
Incrementedbyoneeach
timeaninstanceof
Specifiestheformatfor
theoutputfromusingthe
reservedwordona
ChapterTypeDescription
Specifieswhattouseas
thehistorycontrol
OperatorTrue if...
filefile
filefile
OperatorTrue if...
existsandisownedbytheeffective
existsandisapipeornamedpipe
filefile
filefile
filefile
OperatorTrue if...
existsandisexecutable,or
isa
stringstring
OperatorTrue if...
matchestheextendedregular
3]stringAstringBstringAsortsbefore
sortsafter
OperatorTrue if...
istrue
3]Onlyavailablein
version3.0andlater.May
OptionFull nameMeaning
-Cnoclobber
Don'tallowredirectionto
-Eerrtrace
Anytrapon
isinheritedby
shellfunctions,command
substitutions,andcommands
executedinasubshell
-eerrexit
Exittheshellwhenasimple
commandexitswithnon-zero
status.Asimplecommandisa
commandnotpartofa
,or
;orpartofa
OptionFull nameMeaning
-Hhistexpand
stylehistory
substitution.Onbydefaultinan
Enablecommandhistory.Onby
-hhashall
Disablethehashingof
DisallowCTRL-Dtoexitthe
-kkeyword
Placekeywordargumentsinthe
-mmonitor
Enablejobcontrol(onby
OptionFull nameMeaning
-nnoexec
Readcommandsandcheck
syntaxbutdonotexecutethem.
-Pphysical
Donotfollowsymboliclinkson
commandsthatchangethe
currentdirectory.Usethe
-pprivilegedScript is running in
OptionFull nameMeaning
-Tfunctrace
Anytrapon
inheritedbyshellfunctions,
commandsubstitutions,and
commandsexecutedina
-tonecmd
Exitafterreadingandexecuting
OptionFull nameMeaning
Signalstheendofoptions.All
remainingargumentsare
assignedtothepositional
Option
Option
Option
Option
Option
Option
Option
Option
Option
RedirectorFunction
Forcestandardoutputto
evenif
RedirectorFunction
Directfiledescriptor
;appendto
Duplicatestandardoutputtofiledescriptor
Duplicatestandardinputfromfile
Filedescriptor
ismadetobeacopyof
Filedescriptor
ismadetobeacopyof
Directsstandardoutputandstandarderror
&-Close the standard input
RedirectorFunction
�&-Close the standard output
�&-Close the output from file descriptor
&-Close the input from file descriptor
isnotspecified,thestandardoutput
(filedescriptor1)isused;ifthedigitsin
worddonotspecifyafiledescriptoropen
foroutput,aredirectionerroroccurs;asa
specialcase,if
isomitted,andworddoes
notexpandtooneormoredigits,the
standardoutputandstandarderrorare
Ifwordexpandstooneormoredigits,the
filedescriptordenotedby
ismadetobe
acopyofthatfiledescriptor;ifthedigits
inworddonotspecifyafiledescriptor
openforinput,aredirectionerroroccurs;
ifwordevaluatesto-,filedescriptornis
RedirectorFunction
closed;if
isnotspecified,thestandard
Movesthefiledescriptordigittofile
,orthestandardoutput(file
Movesthefiledescriptordigittofile
,orthestandardinput(file
descriptor0)ifnisnotspecified;digitis
CommandMeaning
Abortthecurrenteditingcommandand
CommandMeaning
CTRL-RSearch backward
CTRL-SSearch forward
CTRL-TTranspose two characters
Killbackwardfrompointtothe
CTRL-VMake the next character typed verbatim
Killthewordbehindthecursor,using
CommandMeaning
CommandMeaning
Readinthecontentsofthe
Displayversioninformationonthis
CommandMeaning
ESC-FMove one word forward
Changewordafterpointtoall
CommandMeaning
CommandMeaning
CommandMeaning
CommandMeaning
Movetobeginningofprecedingnon-blank
.Repeat the last
CommandMeaning
CommandMeaning
CommandMeaning
k or -Move backward one line
j or +Move forward one line
GMove to line given by repeat count
nRepeat search forward
NRepeat search backward
CommandMeaning
Moverighttonextoccurrenceof
,then
Movelefttopreviousoccurrenceof
,then
;Redo last character finding command
Redolastcharacterfindingcommandin
CommandMeaning
Invert(twiddle)caseofcurrent
Appendlastwordofpreviouscommand,
Startanewlineandredrawthecurrentline
(commentcharacter)totheline
Inourexamplewe'llcallthebuilt-in
,theCfunction
,andthehelparray
.Theusagestring
. The resulting structure looks like this:struct builtin tty_struct = {"tty",tty_builtin,BUILTIN_ENABLED,tty_doc,"tty [-s]",0};Thenextsectionisthecodethatdoesthework.Itlooks
t = ttyname (0);
if (sflag == 0)
puts (t ? t : "not a tty");
Thelastmajorsectionisthehelpdefinition.Thisis
simplyanarrayofstrings,thelastelementofthearray
beingNULL.Eachstringisprintedtostandardoutput
isrunonthebuilt-in.Youshould,therefore,
keepthestringsto76charactersorless(an80-character
standarddisplayminusa4-charactermargin).Inthecase
char *t;
0};Wenowneedtocompileandlinkthisasadynamic
sharedobject.Unfortunately,differentsystemshave
differentwaystospecifyhowtocompiledynamicshared
TableC-1
listssomecommonsystemsandthe
commandsneededtocompileandlink
.Replace
TableC-1.Shared object compilation
SystemCommands
cc-pic-I
cc-Kpic-I
SystemCommands
cc-KPIC-I
cc-K-I
ld-bdynamic-bnoentry-bexpall-G-o
cc-fPIC-I
SystemCommands
Afteryouhavecompiledandlinkedtheprogram,you
shouldhaveasharedobjectcalled
.Toloadthisinto
,justtype
enable-f
ttytty
,where
isthe
fullpathnameofthesharedobject.Youcanremovea
loadedbuilt-inatanytimewiththe
option,e.g.,
Youcanputasmanybuilt-insasyoulikeintooneshared
object;allyouneedarethethreemainsectionsthatwe
sawaboveforeachbuilt-ininthesameCfile.Itisbest,
however,tokeepthenumberofbuilt-inspershared
objectsmall.Youwillalsoprobablyfinditbesttokeep
Themainargumentof
ofthesethreepatterns.Wethenhavetonegatethiswitha
Wecanactuallytrythisoutfirstandseewhat
withPIDsbut,ifthereisadashora
,withsignal
Thisisslightlymorecomplexthantheone-lineexample
above.Herewewillneedsomecodetodistinguishwhat
Thecodeisfairlystandardapartfromtheuseofsome
specialenvironmentvariablesandacalltoafunction
ThevariableCOMPREPLYisusedtoholdtheresultthat
Theremainingpartinthe
resultthrough
toremovethefirstline(whichisthe
heading"PID").
4]Thisisthengivenasanargumentto
the-
optionof
,whichtakesawordlist.
formthatisveryusableandsowecan'tusethisto
directlygeneratethearrayofnames.Thenames
Project,whichcanbefoundat
Ourlookistheresultofreadercomments,ourown
experimentation,andfeedbackfromdistribution
channels.Distinctivecoverscomplementourdistinctive
approachtotechnicaltopics,breathingpersonalityand
TheanimalonthecoverofLearningthebashShell,Third
Edition,isasilverbass,oneofthe400-500speciesofsea
bass.Thesilverbass,alsoknownasthewhiteperch,is
foundinfreshwaterbaysandrivermouthsalongthe
AtlanticcoastofNorthAmericafromNovaScotiato
SouthCarolina,andismostabundantintheChesapeake
region.Silverbassliveinlargeschoolsandfeedonsmall
fishesandcrustaceans.Althoughmanybassneverstray
farfromoneplacetheirwholelives,silverbassswim
upstreamtospawn,oftenbecominglandlockedinthe
process.Likemostbass,thes\ilverbassisattractedto
bright,shinyobjects,andcanbedrawnquitecloseto
ColleenGormanwastheproductioneditorand
copyeditorforLearningthebashShell,ThirdEdition.
MaryAnneWeeksMayo,LydiaOnofrei,andEmilyQuill
EdieFreedmandesignedthecoverofthisbook.The
coverimageisa19th-centuryengravingfromtheDover
PictorialArchive.KarenMontgomeryproducedthecover
layoutwithAdobeInDesignCSusingAdobe'sITC
DavidFutatodesignedtheinteriorlayout.Thisbookwas
convertedbyJudyHoertoFrameMaker5.5.6witha
formatconversiontoolcreatedbyErikRay,Jason
McIntosh,NeilWalls,andMikeSierrathatusesPerland
XMLtechnologies.ThetextfontisLinotypeBirka;the
headingfontisAdobeMyriadCondensed;andthecode
fontisLucasFont'sTheSansMonoCondensed.The
illustrationsthatappearinthebookwerecreatedbyChris
ReilleyandupdatedforthethirdeditionbyRobert
Romano,JessamynRead,andLesleyBorashusing
MacromediaFreeHandMXandAdobePhotoshopCS.
ThiscolophonwaswrittenbyClairemarieFisher
TheonlineeditionofthisbookwascreatedbytheDigital
Booksproductiongroup(JohnChodacki,KenDouglass,

Приложенные файлы

  • pdf 11434626
    Размер файла: 2 MB Загрузок: 0

Добавить комментарий