Practical Guide To Linux Commands, Editors, And Shell Programming Commands Editors Shel
Practical_Guide_to_Linux_Commands_Editors_and_Shel
Practical_Guide_to_Linux_Commands_Editors_and_Shel
User Manual:
Open the PDF directly: View PDF
.
Page Count: 1517 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Praise for Mark Sobell's Books
- Chapter 1. Welcome to Linux
- Part I: The Linux Operating System
- Chapter 2. Getting Started
- Chapter 3. Command Line Utilities
- Chapter 4. The Linux Filesystem
- Chapter 5. The Shell
- Part II: The Editors
- Chapter 6. The vim Editor
- Chapter 7. The emacs Editor
- Part III: THE SHELLS
- Chapter 8. The Bourne Again Shell
- Chapter 9. The Tc Shell
- Part IV: Programming Tools
- Chapter 10. Programming Tools
- Chapter 11. Programming The Bourne Again Shell
- Chapter 12. The gawk Pattern Processing Language
- Chapter 13. The sed Editor
- Part V: Command Reference
- Part VI: Appendixes


APracticalGuidetoLinuxCommands,Editors,andShellProgramming
TableofContents
Copyright
PraiseforMarkSobell'sBooks
Preface
Commandlineinterface(CLI)
Linuxdistributions
Overlap
Audience
Benefits
FeaturesOfThisBook
Contents
Supplements
Thanks
Chapter1.WelcometoLinux
Freebeer
TheGnu-LinuxConnection
TheHeritageofLinux:Unix
Whatissogoodaboutlinux?
OverviewofLinux
AdditionalFeaturesofLinux
ChapterSummary
Exercises
PartI:TheLinuxOperatingSystem
Chapter2.GettingStarted
ConventionsUsedinThisBook
LoggingIn
WorkingwiththeShell
CurbingYourPower:SuperuserAccess
GettingtheFacts:WheretoFindDocumentation
MoreAboutLoggingIn
ChapterSummary

Exercises
AdvancedExercises
Chapter3.CommandLineUtilities
SpecialCharacters
BasicUtilities
WorkingwithFiles
|(Pipe):CommunicatesBetweenProcesses
FourMoreUtilities
CompressingandArchivingFiles
LocatingCommands
ObtainingUserandSystemInformation
CommunicatingwithOtherUsers
Email
ChapterSummary
Exercises
AdvancedExercises
Chapter4.TheLinuxFilesystem
TheHierarchicalFilesystem
DirectoryandOrdinaryFiles
WorkingwithDirectories
touch
Accessperemissions
Links
Chaptersummary
Exercises
ADVANCEDEXERCISES
Chapter5.TheShell
TheCommandLine
StandardInputandStandardOutput
RunningaProgramintheBackground
FilenameGeneration/PathnameExpansion
Builtins

ChapterSummary
Exercises
AdvancedExercises
PartII:TheEditors
Chapter6.ThevimEditor
History
Tutorial:CreatingandEditingaFilewithvim
ThecompatibleParameter
IntroductiontovimFeatures
CommandMode:MovingtheCursor
InputMode
CommandMode:DeletingandChangingText
SearchingandSubstituting
MiscellaneousCommands
Yank,Put,andDeleteCommands
ReadingandWritingFiles
SettingParameters
AdvancedEditingTechniques
UnitsofMeasure
ChapterSummary
Exercises
AdvancedExercises
Chapter7.TheemacsEditor
History
Tutorial:GettingStartedwithemacs
BasicEditingCommands
OnlineHelp
AdvancedEditing
Language-SensitiveEditing
MoreInformation
ChapterSummary
Exercises

AdvancedExercises
PartIII:THESHELLS
Chapter8.TheBourneAgainShell
Background
ShellBasics
ParametersandVariables
Processes
History
Aliases
Functions
ControllingbashFeaturesandOptions
ProcessingTheCommandLine
ChapterSummary
Exercises
AdvancedExercises
Chapter9.TheTcShell
Assignmentstatement
PartIV:ProgrammingTools
Chapter10.ProgrammingTools
ProgrammingInC
UsingSharedLibraries
make:KeepsaSetofProgramsCurrent
DebuggingCPrograms
Threads
SystemCalls
SourceCodeManagement
ChapterSummary
Exercises
AdvancedExercises
Chapter11.ProgrammingTheBourneAgainShell
ControlStructures
fileDescriptors

ParametersAndVariables
BuiltinCommands
Expressions
ShellPrograms
ChapterSummary
Exercises
AdvancedExercises
Chapter12.ThegawkPatternProcessingLanguage
Syntax
Arguments
Options
Notes
LanguageBasics
Examples
ErrorMessages
ChapterSummary
Exercises
AdvancedExercises
Chapter13.ThesedEditor
Syntax
Arguments
Options
EditorBasics
Examples
ChapterSummary
Exercises
PartV:CommandReference
CommandReference
UtilitiesThatDisplayandManipulateFiles
NetworkUtilities
UtilitiesThatDisplayandAlterStatus
UtilitiesThatAreProgrammingTools

MiscellaneousUtilities
StandardMultiplicativeSuffixes
CommonOptions
ThesampleUtility
PartVI:Appendixes
AppendixA.RegularExpressions
Characters
Delimiters
SimpleStrings
SpecialCharacters
Rules
BracketingExpressions
TheReplacementString
ExtendedRegularExpressions
AppendixSummary
AppendixB.Help
SolvingAProblem
FindingLinux-RelatedInformation
SpecifyingaTerminal
AppendixC.KeepingTheSystemUp-To-Date
yum:UpdatesAndInstallsPackages
APT:AnAlternativeToyum
BitTorrent
Glossary
Index
index_SYMBOL
index_A
index_B
index_C
index_D
index_E
index_F

APracticalGuidetoLinux®Commands,
Editors,andShellProgramming
ByMarkG.Sobell
...............................................
Publisher:PrenticeHallPTR
PubDate:July01,2005
ISBN:0-13-147823-0
Pages:1008
TableofContents|Index
TheessentialreferenceforcorecommandsthatLinuxusersneeddaily,alongwithsuperiortutorialonshell
programmingandmuchmoreSystemadministrators,softwaredevelopers,qualityassuranceengineersand
othersworkingonaLinuxsystemneedtoworkfromthecommandlineinordertobeeffective.Linuxis
famousforitshugenumberofcommandlineutilityprograms,andtheprogramsthemselvesarefamousfor
theirlargenumbersofoptions,switches,andconfigurationfiles.Butthetruthisthatuserswillonlyusea
limited(butstillsignificant)numberoftheseutilitiesonarecurringbasis,andthenonlywithasubsetofthe
mostimportantandusefuloptions,switchesandconfigurationfiles.Thisbookcutsthroughallthenoise
andshowsthemwhichutilitiesaremostuseful,andwhichoptionsmostimportant.Anditcontains
examples,lot'sandlot'sofexamples.Thisisnotjustareprintofthemanpages.
AndLinuxisalsofamousforits"programmability."Utilitiesaredesigned,bydefault,toworkwtihother
utilitieswithinshellprogramsasawayofautomatingsystemtasks.Thisbookcontainsasuperb
introductiontoLinuxshellprogramming.Andsinceshellprogrammersneedtowritetheirprogramsintext
editors,thisbookcoversthetwomostpopularones:viandemacs.

APracticalGuidetoLinux®Commands,
Editors,andShellProgramming
ByMarkG.Sobell
...............................................
Publisher:PrenticeHallPTR
PubDate:July01,2005
ISBN:0-13-147823-0
Pages:1008
TableofContents|Index
C opyright
PraiseforMarkSobell'sBooks
Preface
Commandlineinterface(C LI)
Linuxdistributions
Overlap
Audience
Benefits
FeaturesOfThisBook
Contents
Supplements
Thanks
Chapter1.WelcometoLinux
Freebeer
TheGnuLinuxConnection
TheHeritageofLinux:Unix
Whatissogoodaboutlinux?
OverviewofLinux
AdditionalFeaturesofLinux
ChapterSummary
Exercises
PartI.TheLinuxOperatingSystem
C hapter2.GettingStarted
ConventionsUsedinThisBook
LoggingIn
WorkingwiththeShell
CurbingYourPower:SuperuserAccess
GettingtheFacts:WheretoFindDocumentation
MoreAboutLoggingIn
ChapterSummary
Exercises
AdvancedExercises
C hapter3.CommandLineUtilities
SpecialCharacters
BasicUtilities
WorkingwithFiles
|(Pipe):CommunicatesBetweenProcesses
FourMoreUtilities
CompressingandArchivingFiles
LocatingC ommands
ObtainingUserandSystemInformation
CommunicatingwithOtherUsers
Email
ChapterSummary
Exercises
AdvancedExercises
C hapter4.TheLinuxFilesystem
TheHierarchicalFilesystem
DirectoryandOrdinaryFiles
WorkingwithDirectories
touch
Accessperemissions
Links
Chaptersummary
Exercises
ADVANCEDEXERCISES
C hapter5.TheShell
TheC ommandLine
StandardInputandStandardOutput
RunningaProgramintheBackground
FilenameGeneration/PathnameExpansion
Builtins
ChapterSummary
Exercises
AdvancedExercises
PartII.TheEditors
C hapter6.ThevimEditor
History
Tutorial:CreatingandEditingaFilewithvim
ThecompatibleParameter
IntroductiontovimFeatures
CommandMode:MovingtheC ursor
InputMode
CommandMode:DeletingandChangingText
SearchingandSubstituting
MiscellaneousC ommands
Yank,Put,andDeleteCommands
ReadingandWritingFiles
SettingParameters
AdvancedEditingTechniques
UnitsofMeasure
ChapterSummary
Exercises
AdvancedExercises
C hapter7.TheemacsEditor
History
Tutorial:GettingStartedwithemacs
BasicEditingC ommands
OnlineHelp
AdvancedEditing
Language-SensitiveEditing
MoreInformation
ChapterSummary
Exercises
AdvancedExercises
PartIII.THESHELLS
C hapter8.TheBourneAgainShell
Background
ShellBasics
ParametersandVariables
Processes
History
Aliases
Functions
ControllingbashFeaturesandOptions
ProcessingTheCommandLine
ChapterSummary
Exercises
AdvancedExercises
C hapter9.TheTcShell
Assignmentstatement
PartIV.ProgrammingTools
C hapter10.ProgrammingTools
ProgrammingInC
UsingSharedLibraries
make:KeepsaSetofProgramsCurrent
DebuggingCPrograms
Threads
SystemC alls
SourceCodeManagement
ChapterSummary
Exercises
AdvancedExercises
C hapter11.ProgrammingTheBourneAgainShell
ControlStructures
fileDescriptors
ParametersAndVariables
BuiltinC ommands
Expressions
ShellPrograms
ChapterSummary
Exercises
AdvancedExercises
C hapter12.ThegawkPatternProcessingLanguage
Syntax
Arguments
Options
Notes
LanguageBasics
Examples
ErrorMessages
ChapterSummary
Exercises
AdvancedExercises
C hapter13.ThesedEditor
Syntax
Arguments
Options
EditorBasics
Examples
ChapterSummary
Exercises
PartV.C ommandReference
C ommandReference
UtilitiesThatDisplayandManipulateFiles
NetworkUtilities
UtilitiesThatDisplayandAlterStatus
UtilitiesThatAreProgrammingTools
MiscellaneousUtilities
StandardMultiplicativeSuffixes
CommonOptions
ThesampleUtility
PartVI.Appendixes
AppendixA.RegularExpressions
Characters
Delimiters
SimpleStrings
SpecialCharacters
Rules
BracketingExpressions
TheReplacementString
ExtendedRegularExpressions
AppendixSummary
AppendixB.Help
SolvingAProblem
FindingLinux-RelatedInformation
SpecifyingaTerminal
AppendixC .KeepingTheSystemUp-To-Date
yum:UpdatesAndInstallsPackages
APT:AnAlternativeToyum
BitTorrent
Glossary
Index
Copyright
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedas
trademarks.Wherethosedesignationsappearinthisbook,andthepublisherwasawareofatrademark
claim,thedesignationshavebeenprintedwithinitialcapitallettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressedor
impliedwarrantyofanykindandassumenoresponsibilityforerrorsoromissions.Noliabilityis
assumedforincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuseofthe
informationorprogramscontainedherein.
Thepublisheroffersexcellentdiscountsonthisbookwhenorderedinquantityforbulkpurchasesor
specialsales,whichmayincludeelectronicversionsand/orcustomcoversandcontentparticulartoyour
business,traininggoals,marketingfocus,andbrandinginterests.Formoreinformation,pleasecontact:
U.S.CorporateandGovernmentSales
(800)382-3419
corpsales@pearsontechgroup.com
ForsalesoutsidetheU.S.,pleasecontact:
InternationalSales
international@pearsoned.com
VisitusontheWeb:www.phptr.com
LibraryofCongressCataloging-in-PublicationData
Sobell,MarkG.
APracticalGuidetoLinuxCommands,Editors,andShellProgramming/MarkG.Sobell
p.cm.
Includesbibliographicalreferencesandindex.
ISBN0-13-147823-0(alk.paper)
1.Linux.2.Operatingsystems(Computers)I.Title.
QA76.76.O63.S594832005
005.4'46dc22
2005050051
Copyright©2005MarkSobell
Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationisprotectedbycopyright,
andpermissionmustbeobtainedfromthepublisherpriortoanyprohibitedreproduction,storageina
retrievalsystem,ortransmissioninanyformorbyanymeans,electronic,mechanical,photocopying,
recording,orlikewise.Forinformationregardingpermissions,writeto:
PearsonEducation,Inc.
RightsandContractsDepartment
OneLakeStreet
UpperSaddleRiver,NJ07458
TextprintedintheUnitedStatesonrecycledpaperatCourierinStoughton,Massachusetts.
Firstprinting,June2005
Dedication
Withloveformyguys,
Sam,Zach,andMax
PraiseforMarkSobell'sBooks
"Ikeepsearchingforbooksthatcollecteverythingyouwanttoknowaboutasubjectinoneplace,
andkeepgettingdisappointed.Usuallythebooksleaveoutsomeimportanttopic,whileothersgo
toodeepinsomeareasandmustskimlightlyovertheothers.APracticalGuidetoRedHat®
Linux®isoneofthoserarebooksthatactuallypullsitoff.MarkG.Sobellhascreatedasingle
referenceforRedHatLinuxthatcannotbebeat!Thismarveloustext(witha4-CDsetofLinux
FedoraCore2included)iswellworththeprice.Thisisasclosetoan"everythingyouever
neededtoknow"bookthatI'veseen.It'sjustthatgoodandrates5outof5."
RayLodatoSlashdotcontributor
"MarkSobellhaswrittenabookasapproachableasitisauthoritative."
JeffreyBianchineAdvocate,Author,Journalist
"Excellentreferencebook,wellsuitedforthesysadminofalinuxcluster,ortheownerofaPC
contemplatinginstallingarecentstablelinux.Don'tbeputoffbythedauntingheftofthebook.
Sobellhasstriventobeasinclusiveaspossible,intryingtoanticipateyoursystemadministration
needs."
WesBoudvilleInventor
"APracticalGuidetoRedHat®Linux®isabrilliantbook.ThankyouMarkSobell."
C.PozrikidisUniversityofCaliforniaatSanDiego
"ThisbookpresentsthebestoverviewoftheLinuxoperatingsystemthatIhavefound....[It]
shouldbeveryhelpfulandunderstandablenomatterwhatthereader'sbackgroundis:traditional
UNIXuser,newLinuxdevotee,orevenWindowsuser.Eachtopicispresentedinaclear,
completefashionandveryfewassumptionsaremadeaboutwhatthereaderknows....Thebook
isextremelyusefulasareference,asitcontainsa70-pageglossaryoftermsandisverywell
indexed.Itisorganizedinsuchawaythatthereadercanfocusonsimpletaskswithouthavingto
wadethroughmoreadvancedtopicsuntiltheyareready."
CamMarshallMarshallInformationServiceLLCMemberofFrontRangeUNIXUsersGroup
[FRUUG]Boulder,Colorado
"Conclusively,thisisTHEbooktogetifyouareanewLinuxuserandyoujustgotintoRH/Fedora
world.There'snootherbookthatdiscussessomanydifferenttopicsandinsuchdepth."
EugeniaLoli-QueruEditorinChiefOSNews.com
Preface
APracticalGuidetoLinux®Commands,Editors,andShellProgrammingexplainshowtoworkwith
theLinuxoperatingsystemfromthecommandline.Thefirstfewchaptersquicklybringreaderswithlittle
computerexperienceuptospeed.Therestofthebookisappropriateformoreexperiencedcomputer
users.ThisbookdoesnotdescribeaparticularreleaseordistributionofLinuxbutratherpertainstoall
recentversionsofLinux.
Commandlineinterface(CLI)
Inthebeginningtherewasthecommandline(textual)interface(CLI),whichenabledyoutogiveLinux
commandsfromthecommandline.Therewasnomouseoriconstodraganddrop.Someprograms,such
asemacs,implementedrudimentarywindowsusingtheveryminimalgraphicsavailableintheASCII
characterset.Reversevideohelpedseparateareasofthescreen.Linuxwasbornandraisedinthis
environment.
NaturallyalloftheoriginalLinuxtoolswereinvokedfromthecommandline.TherealpowerofLinux
stillliesinthisenvironment,whichexplainswhymanyLinuxprofessionalsworkexclusivelyfromthe
commandline.Usingcleardescriptionsandlotsofexamples,thisbookshowsyouhowtogetthemostout
ofyourLinuxsystemusingthecommandlineinterface.
Linuxdistributions
ALinuxdistributioncomprisestheLinuxkernel,utilities,andapplicationprograms.Manydistributions
areavailable,includingDebian,RedHat,FedoraCore,SUSE,Mandriva(formerlyMandrake),
KNOPPIX,andSlackware.Althoughthedistributionsdifferfromoneanotherinvariousways,allofthem
relyontheLinuxkernel,utilities,andapplications.Thisbookisbasedonthecodethatiscommontomost
distributions.Asaconsequenceyoucanuseitregardlessofwhichdistributionyouarerunning.
Overlap
IfyoureadAPracticalGuidetoRedHat®Linux®:FedoraCore™andRedHatEnterpriseLinux,
SecondEdition,orasubsequentedition,youwillnoticesomeoverlapbetweenthatbookandtheoneyou
arereadingnow.Theintroduction,theappendixonregularexpressions,andthechaptersontheutilities
(Chapter3ofthisbooknotPartV),thefilesystem,andprogrammingtoolsareverysimilarinthetwo
books.ThethreechaptersthatcovertheBourneAgainShell(bash)havebeenexpandedandrewritten
forthistext.ChaptersthatappearinthisbookandbutnotinAPracticalGuidetoRedHat®Linux®,
SecondEdition,includethosecoveringthevimandemacseditors,theTCShell(tcsh),thegawkand
sedlanguages,andPartV,whichdescribes80ofthemostusefulLinuxutilityprogramsindetail.

Audience
Thisbookisdesignedforawiderangeofreaders.Itdoesnotrequireprogrammingexperience,although
someexperienceusingageneral-purposecomputerishelpful.Itisappropriateforthefollowingreaders:
StudentstakingaclassinwhichtheyuseLinux
PoweruserswhowanttoexplorethepowerofLinuxfromthecommandline
ProfessionalswhouseLinuxatwork
SystemadministratorswhoneedadeeperunderstandingofLinuxandthetoolsthatareavailableto
them
ComputersciencestudentswhoarestudyingtheLinuxoperatingsystem
ProgrammerswhoneedtounderstandtheLinuxprogrammingenvironment
TechnicalexecutiveswhowanttogetagroundinginLinux
Benefits
APracticalGuidetoLinux®Commands,Editors,andShellProgramminggivesyouanin-depth
understandingofhowtouseLinuxfromthecommandline.Regardlessofyourbackground,itoffersthe
knowledgeyouneedtogetonwithyourwork:Youwillcomeawayfromthisbookunderstandinghowto
useLinux,andthistextwillremainavaluablereferenceforyearstocome.

FeaturesOfThisBook
Thisbookisorganizedforeaseofuseindifferentsituations.Forexample,youcanreaditfromcoverto
covertolearncommandlineLinuxfromthegroundup.Alternatively,onceyouarecomfortableusing
Linux,youcanusethisbookasareference:Lookupatopicofinterestinthetableofcontentsorindex
andreadaboutit.Or,refertooneoftheutilitiescoveredinPartV,"CommandReference."Youcanalso
thinkofthisbookasacatalogofLinuxtopics:Flipthroughthepagesuntilatopiccatchesyoureye.The
bookalsoincludesmanypointerstoWebsiteswhereyoucangetadditionalinformation:Considerthe
Webanextensionofthisbook.
APracticalGuidetoLinux®Commands,Editors,andShellProgrammingoffersthefollowingfeatures:
Optionalsectionsallowyoutoreadthebookatdifferentlevels,returningtomoredifficultmaterial
whenyouarereadytotackleit.
Cautionboxeshighlightproceduresthatcaneasilygowrong,givingyouguidancebeforeyourun
intotrouble.
Tipboxeshighlightplacesinthetextwhereyoucansavetimebydoingsomethingdifferentlyor
whenitmaybeusefulorjustinterestingtohaveadditionalinformation.
Securityboxespointoutwaysthatyoucanmakeasystemmoresecure.
TheSupportingWebsiteatwww.sobell.comincludescorrectionstothebook,downloadable
examplesfromthebook,pointerstousefulWebsites,andanswerstoeven-numberedexercises.
Conceptsareillustratedbypracticalexamplesfoundthroughoutthebook.
ThemanyusefulURLs(Internetaddresses)identifysiteswhereyoucanobtainsoftwareand
information.
Chaptersummariesreviewtheimportantpointscoveredineachchapter.
Reviewexercisesareincludedattheendofeachchapterforreaderswhowanttohonetheirskills.
Answerstoeven-numberedexercisesareavailableatwww.sobell.com.
ImportantGNUtools,includinggcc,gdb,GNUConfigureandBuildSystem,make,gzip,and
manyothers,aredescribedindetail.
Pointersthroughoutthebookprovidehelpinobtainingonlinedocumentationfrommanysources,
includingthelocalsystemandtheInternet.

Contents
Thissectiondescribestheinformationthateachchaptercoversandexplainshowthatinformationcan
helpyoutakeadvantageofthepowerofLinux.Youmaywanttoreviewthetableofcontentsformore
detail.
Chapter1WelcometoLinuxPresentsbackgroundinformationonLinux.Thischaptercoversthe
historyofLinux,explainshowtheGNUProjecthelpedLinuxgetstarted,anddiscussessomeof
Linux'simportantfeaturesthatdistinguishitfromotheroperatingsystems.
PartI:TheLinuxOperatingSystem
tip:ExperiencedusersmaywanttoskimPartI
IfyouhaveusedaUNIX/Linuxsystembefore,youmaywanttoskimorskipsomeorallof
thechaptersinPartI.Allreadersshouldtakealookat"ConventionsUsedinThisBook"
(page22),whichexplainsthetypographicconventionsthatthisbookuses,and"Gettingthe
Facts:WheretoFindDocumentation"(page29),whichpointsyoutowardbothlocaland
remotesourcesofLinuxdocumentation.
PartIintroducesLinuxandgetsyoustartedusingit.
Chapter2GettingStartedExplainsthetypographicconventionsthatthisbookusestomake
explanationsclearerandeasiertoread.Thischapterprovidesbasicinformationandexplainshowto
login,changeyourpassword,giveLinuxcommandsusingtheshell,andfindsystem
documentation.
Chapter3CommandLineUtilitiesExplainsthecommandlineinterface(CLI)andbriefly
introducesmorethan30commandlineutilities.Workingthroughthischaptergivesyouafeelfor
Linuxandintroducessomeofthetoolsyouwillusedayinanddayout.Theutilitiescoveredinthis
chapterinclude
grep,whichsearchesthroughfilesforstringsofcharacters;
unix2dos,whichconvertsLinuxtextfilestoWindowsformat;

tar,whichcreatesarchivefilesthatcanholdmanyotherfiles;
bzip2andgzip,whichcompressfilessothattheytakeuplessspaceondiskandallowyou
totransferthemoveranetworkmorequickly;and
diff,whichdisplaysthedifferencesbetweentwotextfiles.
Chapter4TheLinuxFilesystemDiscussestheLinuxhierarchicalfilesystem,coveringfiles,
filenames,pathnames,workingwithdirectories,accesspermissions,andhardandsymboliclinks.
Understandingthefilesystemallowsyoutoorganizeyourdatasothatyoucanfindinformation
quickly.Italsoenablesyoutosharesomeofyourfileswithotheruserswhilekeepingotherfiles
private.
Chapter5TheShellExplainshowtouseshellfeaturestomakeyourworkfasterandeasier.Allof
thefeaturescoveredinthischapterworkwithbothbashandtcsh.Thischapterdiscusses
Usingcommandlineoptionstomodifythewayacommandworks;
Howaminorchangeinacommandlinecanredirectinputtoacommandtocomefromafile
insteadofthekeyboard;
Howtoredirectoutputfromacommandtogotoafileinsteadofthescreen;
Usingpipestosendtheoutputofoneutilitydirectlytoanotherutilitysothatyoucansolve
problemsrightonthecommandline;
RunningprogramsinthebackgroundsothatyoucanworkononetaskwhileLinuxisworking
onadifferentone;and
Usingtheshelltogeneratefilenamestosaveyoutimespentontypingandhelpyouwhenyou
donotremembertheexactnameofafile.
PartII:TheEditors
PartIIcoverstwoclassic,powerfulLinuxcommandlinetexteditors.MostLinuxdistributionsincludethe
vimtexteditor,an"improved"versionofthewidelyusedvieditor,aswellasthepopularGNUemacs
editor.Texteditorsenableyoutocreateandmodifytextfilesthatcanholdprograms,shellscripts,
memos,andinputtotextformattingprograms.BecauseLinuxsystemadministrationinvolveseditingtext-
basedconfigurationfiles,skilledLinuxadministratorsareadeptatusingtexteditors.

Chapter6ThevimEditorStartswithatutorialonvimandthenexplainshowtousemanyofthe
advancedfeaturesofvim,includingspecialcharactersinsearchstrings,theGeneral-Purposeand
Namedbuffers,parameters,markers,andexecutionofcommandsfromvim.Thechapterconcludes
withasummaryofvimcommands.
Chapter7TheemacsEditorOpenswithatutorialandthenexplainsmanyofthefeaturesofthe
emacseditoraswellashowtousetheMETA,ALT,andESCAPEkeys.Thechapteralsocovers
keybindings,buffers,andincrementalandcompletesearchingforbothcharacterstringsand
regularexpressions.Inaddition,itdetailstherelationshipbetweenPoint,thecursor,Mark,and
Region.Italsoexplainshowtotakeadvantageoftheextensiveonlinehelpfacilitiesavailablefrom
emacs.Othertopicscoveredincludecuttingandpasting,usingmultiplewindowsandframes,and
workingwithemacsmodesspecificallyCmode,whichaidsprogrammersinwritinganddebugging
Ccode.Chapter7concludeswithasummaryofemacscommands.
PartIII:TheShells
PartIIIgoesintomoredetailaboutbashandintroducestheTCShell(tcsh).
Chapter8TheBourneAgainShellPicksupwhereChapter5leavesoff,coveringmoreadvanced
aspectsofworkingwithashell.ForexamplesitusestheBourneAgainShellbash,theshellused
almostexclusivelyforsystemshellscripts.Chapter8describeshowto
Useshellstartupfiles,shelloptions,andshellfeaturestocustomizeyourshell;
Usejobcontroltostopjobsandmovejobsfromtheforegroundtothebackgroundandvice
versa;
Modifyandreexecutecommandsusingtheshellhistorylist;
Createaliasestocustomizecommands;
Workwithuser-createdandkeywordvariablesinshellscripts;
Setupfunctions,whicharesimilartoshellscriptsbutcanexecutemorequickly;
Writeandexecutesimpleshellscripts;and
Redirecterrormessagessothattheygotoafileinsteadofthescreen.
Chapter9TheTCShellDescribestcshandcoversfeaturesthatarecommontoanddifferent

betweenbashandtcsh.Thischapterexplainshowto
Runtcshandchangeyourdefaultshelltotcsh;
Redirecterrormessagessothattheygotofilesinsteadofthescreen;
Usecontrolstructurestoaltertheflowofcontrolwithinshellscripts;
Workwithtcsharrayandnumericvariables;and
Useshellbuiltincommands.
PartIV:ProgrammingTools
PartIVcoversprogrammingunderLinux.ItdiscussestheCprogrammingenvironment,theuseofbash
asaprogramminglanguage,andwaystowriteprogramsusinggawkandsed.
Chapter10ProgrammingToolsIntroducesLinux'sexceptionalprogrammingenvironment.This
chapter
ExplainshowtoinvoketheGNUgcccompiler;
Describeshowtousemaketokeepasetofprogramsup-to-date;
ExplainshowtodebugaCprogramusinggdb;
Describeshowtoworkwithsharedlibraries;
ExplainshowtosetupanduseCVStomanageandtrackprogrammodulesinasoftware
developmentproject;and
Discussessystemcallsandexplainshowyoucanusethemtoinitiatekerneloperations.
OnceyouhavemasteredthebasicsofLinux,youcanuseyourknowledgetobuildmorecomplexand
specializedprograms,usingtheshellasaprogramminglanguage.
Chapter11ProgrammingtheBourneAgainShellShowshowtousebashtowriteadvanced
shellscripts.Thischapterdiscusses
Controlstructuressuchasif...then...elseandcase;

Variables,includinglocalityofvariables;
Arithmeticandlogical(Boolean)expressions;and
Someofthemostusefulshellbuiltincommands,includingexec,trap,andgetopts.
Chapter11posestwocompleteshellprogrammingproblemsandthenshowsyouhowtosolvethem
stepbystep.Thefirstproblemusesrecursiontocreateahierarchyofdirectories.Thesecond
problemdevelopsaquizprogramandshowsyouhowtosetupashellscriptthatinteractswitha
userandhowthescriptprocessesdata.(TheexamplesinPartValsodemonstratemanyfeaturesof
theutilitiesyoucanuseinshellscripts.)
Chapter12ThegawkPatternProcessingLanguageExplainshowtowriteprogramsusingthe
powerfulgawklanguagethatfilterdata,writereports,andretrievedatafromtheInternet.The
advancedprogrammingsectiondescribeshowtosetuptwo-waycommunicationwithanother
programusingacoprocessandhowtoobtaininputoveranetworkinsteadoffromalocalfile.
Chapter13ThesedEditorDescribessed,thenoninteractivestreameditorthatfindsmany
applicationsasafilterwithinshellscripts.Thischapterdiscusseshowtousesed'sbufferstowrite
simpleyetpowerfulprogramsandincludesmanyexamples.
PartV:CommandReference
Linuxincludeshundredsofutilities.Chapters11and12aswellasPartVprovideextensiveexamplesof
theuseofmorethan80ofthemostimportantutilitieswithwhichyoucansolveproblemswithout
resortingtoprogramminginC.IfyouarealreadyfamiliarwithUNIX/Linux,thispartofthebookwillbe
avaluable,easy-to-usereference.Ifyouarenotanexperienceduser,itwillserveasauseful
supplementwhileyouaremasteringtheearliersectionsofthebook.
AlthoughthedescriptionsoftheutilitiesinChapters11and12andPartVarepresentedinaformat
similartothatusedbytheLinuxmanual(man)pages,theyaremucheasiertoreadandunderstand.These
utilitieswerechosenbecauseyouwillworkwiththemdayinanddayout(forexample,lsandcp),
becausetheyarepowerfultoolsthatareespeciallyusefulinshellscripts(sort,paste,andtest),
becausetheyhelpyouworkwithyourLinuxsystem(ps,kill,andfsck),orbecausetheyenableyou
tocommunicatewithothersystems(ssh,scp,andftp).Eachutilitydescriptionincludescomplete
explanationsofitsmostusefuloptions.The"Discussion"and"Notes"sectionspresenttipsandtricksfor
usingtheutilitytofulladvantage.The"Examples"sectionsdemonstratehowtousetheseutilitiesinreal
life,aloneandtogetherwithotherutilitiestogeneratereports,summarizedata,andextractinformation.
Takealookatthe"Examples"sectionsforgawk(morethan20pages,startingonpage537),ftp(page
674),andsort(page764)toseehowextensivethesesectionsare.

PartVI:Appendixes
PartVIincludestheappendixes,theglossary,andtheindex.
AppendixARegularExpressionsExplainshowtouseregularexpressionstotakeadvantageof
thehiddenpowerofLinux.Manyutilities,includinggrep,sed,vim,andgawk,acceptregular
expressionsinplaceofsimplestringsofcharacters.Asingleregularexpressioncanmatchmany
simplestrings.
AppendixBHelpDetailsthestepstypicallyusedtosolvetheproblemsyoumayencounterwitha
Linuxsystem.ThisappendixalsoincludesmanylinkstoWebsitesthatofferdocumentation,useful
Linuxinformation,mailinglists,andsoftware.
AppendixCKeepingtheSystemUp-to-dateDescribeshowtousetoolstodownloadsoftware
andkeepyoursystemcurrent.Thisappendixincludesinformationon
yumDownloadssoftwarefromtheInternet,keepingasystemup-to-dateandresolving
dependenciesasitgoes.
AptAnalternativetoyumforkeepingasystemcurrent.
BitTorrentGoodfordistributinglargeamountsofdatasuchasLinuxinstallationCDs.
GlossaryDefinesmorethan500termsthatpertaintotheuseofLinux.
IndexHelpsyoufindtheinformationyouwantquickly.
Supplements
Theauthor'shomepage(www.sobell.com)containsdownloadablelistingsofthelongerprogramsfrom
thisbookaswellaspointerstomanyinterestingandusefulLinux-relatedsitesontheWorldWideWeb,a
listofcorrectionstothebook,answerstoeven-numberedexercises,andasolicitationforcorrections,
comments,andsuggestions.
Thanks
FirstandforemostIwanttothankmyeditoratPrenticeHallPTR,MarkL.Taub,whoencouragedmeand
keptmeontrack.Markisuniqueinmyexperience:HeisaneditorwhoworkswiththetoolsIamwriting
about.BecauseMarkrunsLinuxonhishomecomputer,wecouldshareexperiencesasIwrote.His
commentsanddirectionwereinvaluable.Thankyou,MarkT.
Abig"ThankYou"tothefolkswhoreadthroughthedraftsofthebookandmadecommentsthatcausedme
torefocuspartsofthebookwherethingswerenotclearorwereleftoutaltogether:LarsKellogg-
Stedman,HarvardUniversity;JimA.Lola,PrincipalSystemsConsultant,PrivateerSystems,LLC;EricS.
Raymond,cofounder,OpenSourceInitiative;ScottMann;RandallLechlitner,IndependentComputer
Consultant;JasonWertz,ComputerScienceInstructor,MontgomeryCountyCommunityCollege;Justin
Howell,SolanoCommunityCollege;EdSawicki,TheAcceleratedLearningCenter;DavidMercer,
Contechst;JeffreyBianchine,Advocate,Author,Journalist;JohnKennedy;ChrisKarr;andJimDennis,
StarshineTechnicalServices.
ThankstoMollySharpofContentWorks,theproductionmanagerwhomadesurethebookcametogether
asitwassupposedto,andtoJillHobbs,thecopyeditorwhokeptthevariouspartsoftheEnglish
languageintheirproperrelativeplaces.ThanksalsotothefolksatPrenticeHallPTRwhohelpedbring
thisbooktolife:HeatherFox,Publicist;SuzetteCiancio,MarketingManager;RobinO'Brien,Executive
MarketingManager;JulieNahil,Full-ServiceProductionManager;NoreenRegina,EditorialAssistant;
andeveryoneelsewhoworkedbehindthescenestomakethisbookhappen.
IamalsoindebtedtoDenisHowe,theeditorofTheFreeOn-LineDictionaryofComputing(FOLDOC).
Dennishasgraciouslypermittedmetouseentriesfromhiscompilation.Besuretovisitthedictionary
(www.foldoc.org).
Dr.BrianKernighanandRobPikegraciouslyallowedmetoreprintthebundlescriptfromtheirbook,
TheUNIXProgrammingEnvironment(PrenticeHall,1984).
PartsofAPracticalGuidetoLinux®Commands,Editors,andShellProgramminghavegrownfrommy
previousLinuxbooksandIwanttothankthepeoplewhohelpedwiththosebooks.
ThankyoutoDavidChisnall,computerscientistextraordinaire;CarstenPfeiffer,SoftwareEngineerand
KDEDeveloper;AaronWeber,Ximian;MatthewMiller,BostonUniversity;CristofFalk,Software
DeveloperatCritterDesign;ScottMann,IBM,SystemsManagmentandIntegrationProfessional;Steve
Elgersma,ComputerScienceDepartment,PrincetonUniversity;ScottDier,UniversityofMinnesota;and
RobertHaskins,ComputerNetWorks.
ThanksalsotoDustinPuryear,PuryearInformationTechnology;GaborLiptak,IndependentConsultant;
BartSchaefer,ChiefTechnicalOfficer,iPost;MichaelJ.Jordan,WebDeveloper,LinuxOnlineInc.;
StevenGibson,ownerofSuperAnt.com;JohnViega,founderandChiefScientist,SecureSoftware,Inc.;
K.RachaelTreu,InternetSecurityAnalyst,GlobalCrossing;KaraPritchard,K&SPritchard
Enterprises,Inc.;GlenWiley,CapitolOneFinances;KarelBaloun,SeniorSoftwareEngineer,Looksmart,
Ltd.;MatthewWhitworth;DameonD.Welch-Abernathy,NokiaSystems;JoshSimon,Consultant;Stan
Isaacs;andDr.EricH.HerrinII,VicePresident,HerrinSoftwareDevelopment,Inc.AndthankstoDoug
Hughes,long-timesystemdesignerandadministrator,whogavemeabighandwiththesectionsonsystem
administration,networks,theInternet,andprogramming.
MorethanksgotoconsultantsLorraineCallahanandSteveWampler;RonaldHiller,GraburnTechnology,
Inc.;CharlesA.Plater,WayneStateUniversity;BobPalowoda;TomBialaski,SunMicrosystems;Roger
Hartmuller,TISLabsatNetworkAssociates;KaowenLiu;AndySpitzer;RikSchneider;JesseSt.
Laurent;SteveBellenot;RayW.Hiltbrand;JenniferWitham;Gert-JanHagenaars;andCasperDik.
APracticalGuidetoLinux®Commands,Editors,andShellProgrammingisbasedinpartontwoofmy
previousUNIXbooks:UNIXSystemV:APracticalGuideandAPracticalGuidetotheUNIXSystem.
Manypeoplehelpedmewiththosebooks,andthanksheregotoPatParseghian,Dr.KathleenHemenway,
andBrianLaRose;ByronA.Jeff,ClarkAtlantaUniversity;CharlesStross;JeffGitlin,Lucent
Technologies;KurtHockenbury;MauryBach,IntelIsraelLtd.;PeterH.Salus;RahulDave,Universityof
Pennsylvania;SeanWalton,IntelligentAlgorithmicSolutions;TimSegall,ComputerSciences
Corporation;BehrouzForouzan,DeAnzaCollege;MikeKeenan,VirginiaPolytechnicInstituteandState
University;MikeJohnson,OregonStateUniversity;JandelynPlane,UniversityofMaryland;Arnold
RobbinsandSathisMenon,GeorgiaInstituteofTechnology;CliffShaffer,VirginiaPolytechnicInstitute
andStateUniversity;andStevenStepanek,CaliforniaStateUniversity,Northridge,forreviewingthe
book.
IcontinuetobegratefultothemanypeoplewhohelpedwiththeearlyeditionsofmyUNIXbooks.
SpecialthanksareduetoRogerSippl,LauraKing,andRoyHarringtonforintroducingmetotheUNIX
system.Mymother,Dr.HelenSobell,providedinvaluablecommentsontheoriginalmanuscriptatseveral
junctures.Also,thanksgotoIsaacRabinovitch,ProfessorRaphaelFinkel,ProfessorRandolphBentson,
BobGreenberg,ProfessorUdoPooch,JudyRoss,Dr.RobertVeroff,Dr.MikeDenny,JoeDiMartino,Dr.
JohnMashey,DianeSchulz,RobertJung,CharlesWhitaker,DonCragun,BrianDougherty,Dr.Robert
Fish,GuyHarris,PingLiao,GaryLindgren,Dr.JarrettRosenberg,Dr.PeterSmith,BillWeber,Mike
Bianchi,ScooterMorris,ClarkeEchols,OliverGrillmeyer,Dr.DavidKorn,Dr.ScottWeikart,andDr.
RichardCurtis.
Itakeresponsibilityforanyerrorsandomissionsinthisbook.Ifyoufindoneorjusthaveacomment,let
meknow(mgs@sobell.com)andIwillfixitinthenextprinting.Myhomepage(www.sobell.com)
containsalistoferrorsandcreditsthosewhofoundthem.Italsoofferscopiesofthelongerscriptsfrom
thebookandpointerstomanyinterestingLinuxpages.
MarkG.Sobell
SanFrancisco,California
Chapter1.WelcometoLinux
INTHISCHAPTER
TheGNULinuxConnection2
TheHeritageofLinux:UNIX5
WhatIsSoGoodAboutLinux?6
OverviewofLinux10
AdditionalFeaturesofLinux15
TheLinuxkernelwasdevelopedbyFinnishundergraduatestudentLinusTorvalds,whousedtheInternet
tomakethesourcecodeimmediatelyavailabletoothersforfree.TorvaldsreleasedLinuxversion0.01in
September1991.
Thenewoperatingsystemcametogetherthroughalotofhardwork.Programmersaroundtheworldwere
quicktoextendthekernelanddevelopothertools,addingfunctionalitytomatchthatalreadyfoundinboth
BSDUNIXandSystemVUNIX(SVR4)aswellasnewfunctionality.
TheLinuxoperatingsystem,developedthroughthecooperationofmany,manypeoplearoundtheworld,
isaproductoftheInternetandisafreeoperatingsystem.Inotherwords,allthesourcecodeisfree.You
arefreetostudyit,redistributeit,andmodifyit.Asaresult,thecodeisavailablefreeofcostnocharge
forthesoftware,source,documentation,orsupport(vianewsgroups,mailinglists,andotherInternet
resources).AstheGNUFreeSoftwareDefinition(www.gnu.org/philosophy/free-sw.html)putsit:
Freebeer
"Freesoftware"isamatterofliberty,notprice.Tounderstandtheconcept,youshouldthinkof"free"as
in"freespeech,"notasin"freebeer."
TheGnuLinuxConnection
Anoperatingsystemisthelow-levelsoftwarethatschedulestasks,allocatesstorage,andhandlesthe
interfacestoperipheralhardware,suchasprinters,diskdrives,thescreen,keyboard,andmouse.An
operatingsystemhastwomainparts:thekernelandthesystemprograms.Thekernelallocatesmachine
resources,includingmemory,diskspace,andCPU(page869)cycles,toallotherprogramsthatrunon
thecomputer.Thesystemprogramsperformhigher-levelhousekeepingtasks,oftenactingasserversina
client/serverrelationship.LinuxisthenameofthekernelthatLinusTorvaldspresentedtotheworldin
1991andthatmanyothershaveworkedonsincethentoenhance,stabilize,expand,andmakemore
secure.
TheHistoryofGnuLinux
ThissectionpresentssomebackgroundontherelationshipbetweenGNUandLinux.
Fadeto1983
RichardStallman(www.stallman.org)announces[1]theGNUProjectforcreatinganoperatingsystem,
bothkernelandsystemprograms,andpresentstheGNUManifesto,[2]whichbeginsasfollows:
[1]www.gnu.org/gnu/initial-announcement.html
[2]www.gnu.org/gnu/manifesto.html.
GNU,whichstandsforGnu'sNotUNIX,isthenameforthecompleteUNIX-compatiblesoftware
systemwhichIamwritingsothatIcangiveitawayfreetoeveryonewhocanuseit.
SomeyearslaterStallmanaddedafootnotetotheprecedingsentencewhenherealizedthatitwas
creatingconfusion:
Thewordingherewascareless.Theintentionwasthatnobodywouldhavetopayfor*permission*
tousetheGNUsystem.Butthewordsdon'tmakethisclear,andpeopleofteninterpretthemas
sayingthatcopiesofGNUshouldalwaysbedistributedatlittleornocharge.Thatwasneverthe
intent;lateron,themanifestomentionsthepossibilityofcompaniesprovidingtheserviceof
distributionforaprofit.SubsequentlyIhavelearnedtodistinguishcarefullybetween"free"inthe
senseoffreedomand"free"inthesenseofprice.Freesoftwareissoftwarethatusershavethe
freedomtodistributeandchange.Someusersmayobtaincopiesatnocharge,whileotherspayto
obtaincopiesandifthefundshelpsupportimprovingthesoftware,somuchthebetter.The
importantthingisthateveryonewhohasacopyhasthefreedomtocooperatewithothersinusing
it.
Inthemanifesto,afterexplainingalittleabouttheprojectandwhathasbeenaccomplishedsofar,
Stallmancontinues:
WhyIMustWriteGNU
IconsiderthatthegoldenrulerequiresthatifIlikeaprogramImustshareitwithotherpeople
wholikeit.Softwaresellerswanttodividetheusersandconquerthem,makingeachuseragree
nottosharewithothers.Irefusetobreaksolidaritywithotherusersinthisway.Icannotingood
consciencesignanondisclosureagreementorasoftwarelicenseagreement.ForyearsIworked
withintheArtificialIntelligenceLabtoresistsuchtendenciesandotherinhospitalities,but
eventuallytheyhadgonetoofar:Icouldnotremaininaninstitutionwheresuchthingsaredonefor
meagainstmywill.
SothatIcancontinuetousecomputerswithoutdishonor,Ihavedecidedtoputtogetherasufficient
bodyoffreesoftwaresothatIwillbeabletogetalongwithoutanysoftwarethatisnotfree.Ihave
resignedfromtheAILabtodenyMITanylegalexcusetopreventmefromgivingGNUaway.
NextScene,1991
TheGNUProjecthasmovedwellalongtowarditsgoal.MuchoftheGNUoperatingsystem,exceptfor
thekernel,iscomplete.RichardStallmanlaterwrites:
Bytheearly'90swehadputtogetherthewholesystemasidefromthekernel(andwewerealso
workingonakernel,theGNUHurd,[3]whichrunsontopofMach[4]).Developingthiskernelhas
beenalotharderthanweexpected,andwearestillworkingonfinishingit.[5]
...[M]anybelievethatonceLinusTorvaldsfinishedwritingthekernel,hisfriendslookedaround
forotherfreesoftware,andfornoparticularreasonmosteverythingnecessarytomakeaUNIX-
likesystemwasalreadyavailable.
WhattheyfoundwasnoaccidentitwastheGNUsystem.Theavailablefreesoftware[6]addedup
toacompletesystembecausetheGNUProjecthadbeenworkingsince1984tomakeone.The
GNUManifestohadsetforththegoalofdevelopingafreeUNIX-likesystem,calledGNU.The
InitialAnnouncementoftheGNUProjectalsooutlinessomeoftheoriginalplansfortheGNU
system.BythetimeLinuxwaswritten,the[GNU]systemwasalmostfinished.[7]
[3]www.gnu.org/software/hurd/hurd.html
[4]www.gnu.org/software/hurd/gnumach.html
[5]www.gnu.org/software/hurd/hurd-and-linux.html
[6]www.gnu.org/philosophy/free-sw.html
[7]www.gnu.org/gnu/linux-and-gnu.html
TodaytheGNU"operatingsystem"runsontopoftheFreeBSD(www.freebsd.org)andNetBSD
(www.netbsd.org)kernelswithcompleteLinuxbinarycompatibilityandontopofHurdpre-releasesand
Darwin(developer.apple.com/darwin)withoutthiscompatibility.
TheCodeisFree
ThetraditionoffreesoftwaredatesbacktothedayswhenUNIXwasreleasedtouniversitiesatnominal
cost,whichcontributedtoitsportabilityandsuccess.ThistraditiondiedasUNIXwascommercialized
andmanufacturersregardedthesourcecodeasproprietary,makingiteffectivelyunavailable.Another
problemwiththecommercialversionsofUNIXrelatedtotheircomplexity.Aseachmanufacturertuned
UNIXforaspecificarchitecture,itbecamelessportableandtoounwieldyforteachingand
experimentation.
MINIX
Twoprofessorscreatedtheirownstripped-downUNIXlook-alikesforeducationalpurposes:Doug
ComercreatedXINU(www.cs.purdue.edu/research/xinu.html)andAndrewTanenbaumcreatedMINIX
(www.cs.vu.nl/~ast/minix.html).LinusTorvaldscreatedLinuxtocounteracttheshortcomingsinMINIX.
Everytimetherewasachoicebetweencodesimplicityandefficiency/featuresTanenbaumchose
simplicity(tomakeiteasytoteachwithMINIX),whichmeantthatthissystemlackedmanyoffeatures
peoplewanted.Linuxgoesintheoppositedirection.
YoucanobtainLinuxatnocostovertheInternet.YoucanalsoobtaintheGNUcodeviatheU.S.mailat
amodestcostformaterialsandshipping.YoucansupporttheFreeSoftwareFoundationbybuyingthe
same(GNU)codeinhigher-pricedpackages,andyoucanbuycommercialpackagedreleasesofLinux
(calleddistributions)thatincludeinstallationinstructions,software,andsupport.
GPL
LinuxandGNUsoftwarearedistributedunderthetermsoftheGNUGeneralPublicLicense(GPL,
www.gnu.org/licenses/licenses.html).TheGPLsaysyouhavetherighttocopy,modify,andredistribute
thecodecoveredbytheagreement.Ifyouredistributethecode,youmustalsodistributethesamelicense
withthecode,makingthecodeandthelicenseinseparable.IfyougetthesourcecodeofftheInternetfor
anaccountingprogramthatisundertheGPL,modifythecode,andthenredistributeanexecutableversion
oftheprogram,youmustalsodistributethemodifiedsourcecodeandtheGPLagreementwithit.Because
thisisthereverseofthewayanormalcopyrightworks(itgivesrightsinsteadoflimitingthem),ithas
beentermedacopyleft.(ThisparagraphisnotalegalinterpretationoftheGPL;itsimplygivesyouan
ideaofhowitworks.RefertotheGPLitselfwhenyouwanttomakeuseofit.)
Havefun!
TwokeywordsforLinuxare"HaveFun!"Thesewordspopupinpromptsanddocumentation.The
UNIXnowLinuxcultureissteepedinhumorthatcanbeseenthroughoutthesystem.Forexample,lessis
moreGNUhasreplacedtheUNIXpagingutilitynamedmorewithanimprovedutilitynamedless.The
utilitytoviewPostScriptdocumentsisnamedghostscript,andoneofseveralreplacementsforthe
vieditorisnamedelvis.WhilemachineswithIntelprocessorshave"IntelInside"logosontheir
outside,someLinuxmachinessport"LinuxInside"logos.AndTorvaldshimselfhasbeenseenwearinga
T-shirtbearinga"LinusInside"logo.
TheHeritageofLinux:Unix
TheUNIXsystemwasdevelopedbyresearcherswhoneededasetofmoderncomputingtoolstohelp
themwiththeirprojects.Thesystemallowedagroupofpeopleworkingtogetheronaprojecttoshare
selecteddataandprogramswhilekeepingotherinformationprivate.
UniversitiesandcollegesplayedamajorroleinfurtheringthepopularityoftheUNIXoperatingsystem
throughthe"four-yeareffect."WhentheUNIXoperatingsystembecamewidelyavailablein1975,Bell
Labsofferedittoeducationalinstitutionsatnominalcost.Theschools,inturn,useditintheircomputer
scienceprograms,ensuringthatcomputersciencestudentsbecamefamiliarwithit.BecauseUNIXwas
suchanadvanceddevelopmentsystem,thestudentsbecameacclimatedtoasophisticatedprogramming
environment.Asthesestudentsgraduatedandwentintoindustry,theyexpectedtoworkinasimilarly
advancedenvironment.Asmoreofthemworkedtheirwayuptheladderinthecommercialworld,the
UNIXoperatingsystemfounditswayintoindustry.
InadditiontointroducingstudentstotheUNIXoperatingsystem,theComputerSystemsResearchGroup
(CSRG)attheUniversityofCaliforniaatBerkeleymadesignificantadditionsandchangestoit.Infact,it
madesomanypopularchangesthatoneversionofthesystemiscalledtheBerkeleySoftwareDistribution
(BSD)oftheUNIXsystem(orjustBerkeleyUNIX).TheothermajorversionisUNIXSystemV(SVR4),
whichdescendedfromversionsdevelopedandmaintainedbyAT&TandUNIXSystemLaboratories.
Whatissogoodaboutlinux?
InrecentyearsLinuxhasemergedasapowerfulandinnovativeUNIXwork-alike.Itspopularityis
surpassingthatofitsUNIXpredecessors.AlthoughitmimicsUNIXinmanyways,theLinuxoperating
systemdepartsfromUNIXinseveralsignificantways:TheLinuxkernelisimplementedindependentlyof
bothBSDandSystemV,thecontinuingdevelopmentofLinuxistakingplacethroughthecombinedefforts
ofmanycapableindividualsthroughouttheworld,andLinuxputsthepowerofUNIXwithineasyreachof
businessandpersonalcomputerusers.UsingtheInternet,today'sskilledprogrammerssubmitadditions
andimprovementstotheoperatingsystemtoLinusTorvalds,GNU,oroneoftheotherauthorsofLinux.
Applications
ArichselectionofapplicationsisavailableforLinuxbothfreeandcommercialaswellasawidevariety
oftools:graphical,wordprocessing,networking,security,administration,Webserver,andmanyothers.
LargesoftwarecompanieshaverecentlyseenthebenefitinsupportingLinuxandhavenowon-staff
programmerswhosejobitistodesignandcodetheLinuxkernel,GNU,KDE,orothersoftwarethatruns
onLinuxForexample,IBM(www.ibm.com/linux)isamajorLinuxsupporter.Linuxconforms
increasinglymorecloselytoPOSIXstandards,andsomedistributionsandpartsofothersmeetthis
standard.(See"Standards"onpage8formoreinformation.)ThesefactsmeanthatLinuxisbecoming
moremainstreamandisrespectedasanattractivealternativetootherpopularoperatingsystems.
Peripherals
AnotheraspectofLinuxthatappealstousersistheamazingrangeofperipheralsthatissupportedandthe
speedwithwhichsupportfornewperipheralsemerges.Linuxoftensupportsaperipheralorinterface
cardbeforeanycompanydoes.Unfortunatelysometypesofperipheralsparticularlyproprietarygraphics
cardslagintheirsupportbecausethemanufacturersdonotreleasespecificationsorsourcecodefor
driversinatimelymanner,ifatall.
Software
Alsoimportanttousersistheamountofsoftwarethatisavailablenotjustsourcecode(whichneedstobe
compiled)butalsoprebuiltbinariesthatareeasytoinstallandreadytorun.Theseincludemorethanfree
software.Netscape,forexample,hasbeenavailableforLinuxfromthestartandincludedJavasupport
beforeitwasavailablefrommanycommercialvendors.NowitssiblingMozillaisalsoaviable
browser,mailclient,andnewsreader,performingmanyotherfunctionsaswell.
Platforms
LinuxisnotjustforIntel-basedplatformsbuthasbeenportedtoandrunsonthePowerPCincluding
Applecomputers(ppclinux),theCompaq's(néeDigitalEquipmentCorporation)Alpha-basedmachines,
MIPS-basedmachines,Motorola's68K-basedmachines,andIBM'sS/390.NorisLinuxjustforsingle-
processormachines:Asofversion2.0,itrunsonmultipleprocessormachines(SMPs).Asofversion
2.5.2,LinuxincludesanO(1)scheduler,whichdramaticallyincreasesscalabilityonSMPsystems.
Emulators
Linuxsupportsprograms,calledemulators,thatruncodeintendedforotheroperatingsystems.Byusing
emulatorsyoucanrunsomeDOS,Windows,andMacintoshprogramsunderLinux.Wine
(www.winehq.com)isanopen-sourceimplementationoftheWindowsAPIontopofXandUNIX/Linux;
QEMU(fabrice.bellard.free.fr/qemu)isaCPU-onlyemulatorthatexecutesx86Linuxbinariesonnon-x86
Linuxsystems.
WhyLinuxIsPopularWithHardwareCompaniesAnd
Developers
TwotrendsinthecomputerindustrysetthestageforthepopularityofUNIXandLinux.First,advancesin
hardwaretechnologycreatedtheneedforanoperatingsystemthatcouldtakeadvantageofavailable
hardwarepower.Inthemid-1970s,minicomputersbeganchallengingthelargemainframecomputers
because,inmanyapplications,minicomputerscouldperformthesamefunctionslessexpensively.More
recently,powerful64-bitprocessorchips,plentifulandinexpensivememory,andlower-pricedharddisk
storagehaveallowedhardwarecompaniestoinstallmultiuseroperatingsystemsondesktopcomputers.
Proprietaryoperatingsystems
Second,withthecostofhardwarecontinuallydropping,hardwaremanufacturerscannolongeraffordto
developandsupportproprietaryoperatingsystems.Aproprietaryoperatingsystemusedtobewritten
andownedbythemanufacturerofthehardware(forexample,DEC/CompaqownsVMS).Today's
manufacturersneedagenericoperatingsystemthattheycaneasilyadapttotheirmachines.
Genericoperatingsystems
Agenericoperatingsystemiswrittenoutsideofthecompanymanufacturingthehardwareandissold
(UNIX,Windows)orgiven(Linux)tothemanufacturer.Linuxisagenericoperatingsystembecauseit
runsondifferenttypesofhardwareproducedbydifferentmanufacturers.Ofcourse,ifmanufacturerscan
payonlyfordevelopmentandavoidper-unitcosts(astheyhavetopaytoMicrosoftforeachcopyof
Windowstheysell),developersaremuchbetteroff.Inturn,softwaredevelopersneedtokeeptheprices
oftheirproductsdown;theycannotaffordtoconverttheirproductstorunundermanydifferent
proprietaryoperatingsystems.Likehardwaremanufacturers,softwaredevelopersneedageneric
operatingsystem.
AlthoughtheUNIXsystemoncemettheneedsofhardwarecompaniesandresearchersforageneric
operatingsystem,overtimeithasbecomemoreproprietaryaseachmanufacturerhasaddedsupportfor
specializedfeaturesandintroducednewsoftwarelibrariesandutilities.
Linuxemergedtoservebothneeds.Itisagenericoperatingsystemthattakesadvantageofavailable
hardwarepower.
LinuxIsPortable
Aportableoperatingsystemisonethatcanrunonmanydifferentmachines.Morethan95percentofthe
LinuxoperatingsystemiswrittenintheCprogramminglanguage,andCisportablebecauseitiswritten
inahigher-level,machine-independentlanguage.(TheCcompileriswritteninC.)
BecauseLinuxisportable,itcanbeadapted(ported)todifferentmachinesandcanmeetspecial
requirements.Forexample,Linuxisusedinembeddedcomputers,suchastheonesfoundincellphones,
PDAs,andthecableboxesontopofmanyTVs.Thefilestructuretakesfulladvantageoflarge,fasthard
disks.Equallyimportant,Linuxwasoriginallydesignedasamultiuseroperatingsystemitwasnot
modifiedtoserveseveralusersasanafterthought.Sharingthecomputer'spoweramongmanyusersand
givingthemtheabilitytosharedataandprogramsarecentralfeaturesofthesystem.
Becauseitisadaptableandtakesadvantageofavailablehardware,Linuxnowrunsonmanydifferent
microprocessor-basedsystemsaswellasmainframes.Thepopularityofthemicroprocessor-based
hardwaredrivesLinux;thesemicrocomputersaregettingfasterallthetime,ataboutthesamepricepoint.
Linuxonafastmicrocomputerhasbecomegoodenoughtodisplaceworkstationsonmanydesktops.Linux
benefitsbothusers,whodonotlikehavingtolearnanewoperatingsystemforeachvendor'shardware,
andthesystemadministrators,wholikehavingaconsistentsoftwareenvironment.
Theadventofastandardoperatingsystemhasaidedthedevelopmentofthesoftwareindustry.Now
softwaremanufacturerscanaffordtomakeoneversionofaproductavailableonmachinesfromdifferent
manufacturers.
Standards
IndividualsfromcompaniesthroughoutthecomputerindustryhavejoinedtogethertodevelopthePOSIX
(PortableOperatingSystemInterfaceforcomputerEnvironments)standard,whichisbasedlargelyonthe
UNIXSystemVInterfaceDefinition(SVID)andotherearlierstandardizationefforts.Theseeffortshave
beenspurredbytheU.S.government,whichneedsastandardcomputingenvironmenttominimizeits
trainingandprocurementcosts.Nowthatthesestandardsaregainingacceptance,softwaredevelopersare
abletodevelopapplicationsthatrunonallconformingversionsofUNIX,Linux,andotheroperating
systems.
TheCProgrammingLanguage
KenThompsonwrotetheUNIXoperatingsystemin1969inPDP-7assemblylanguage.Assembly
languageismachinedependent:Programswritteninassemblylanguageworkononlyonemachineor,at
best,onefamilyofmachines.TheoriginalUNIXoperatingsystemthereforecouldnoteasilybe
transportedtorunonothermachines(itwasnotportable).
TomakeUNIXportable,ThompsondevelopedtheBprogramminglanguage,amachine-independent
language,fromtheBCPLlanguage.DennisRitchiedevelopedtheCprogramminglanguagebymodifying
Band,withThompson,rewroteUNIXinCin1973.Therevisedoperatingsystemcouldbetransported
moreeasilytorunonothermachines.
ThatdevelopmentmarkedthestartofC.Itsrootsrevealsomeofthereasonswhyitissuchapowerful
tool.Ccanbeusedtowritemachine-independentprograms.Aprogrammerwhodesignsaprogramtobe
portablecaneasilymoveittoanycomputerthathasaCcompiler.Cisalsodesignedtocompileintovery
efficientcode.WiththeadventofC,aprogrammernolongerhadtoresorttoassemblylanguagetoget
codethatwouldrunwell(thatis,quickly,althoughanassemblerwillalwaysgeneratemoreefficientcode
thanahigh-levellanguage).
Cisagoodsystemslanguage.YoucanwriteacompileroranoperatingsysteminC.Itishighlystructured
butisnotnecessarilyahigh-levellanguage.Callowsaprogrammertomanipulatebitsandbytes,asis
necessarywhenwritinganoperatingsystem.Butitalsohashigh-levelconstructsthatallowefficient,
modularprogramming.
Inthelate1980stheAmericanNationalStandardsInstitute(ANSI)definedastandardversionoftheC
language,commonlyreferredtoasANSICorC89(fortheyearthestandardwaspublished).Tenyears
latertheC99standardwaspublished;itismostlysupportedbytheGNUProject'sCcompiler(named
gcc).TheoriginalversionofthelanguageisoftenreferredtoasKernighan&Ritchie(orK&R)C,
namedfortheauthorsofthebookthatfirstdescribedtheClanguage.
AnotherresearcheratBellLabs,BjarneStroustrup,createdanobject-orientedprogramminglanguage
namedC++,whichisbuiltonthefoundationofC.Becauseobject-orientedprogrammingisdesiredby
manyemployerstoday,C++ispreferredoverCinmanyenvironments.TheGNUProject'sCcompiler
anditsC++compiler(g++)areintegralpartsoftheLinuxoperatingsystem.

OverviewofLinux
TheLinuxoperatingsystemhasmanyuniqueandpowerfulfeatures.Likeotheroperatingsystems,Linuxis
acontrolprogramforcomputers.ButlikeUNIX,itisalsoawell-thought-outfamilyofutilityprograms
(Figure1-1)andasetoftoolsallowinguserstoconnectandusetheseutilitiestobuildsystemsand
applications.
Figure1-1.AlayeredviewoftheLinuxoperatingsystem
LinuxHasaKernelProgrammingInterface
TheheartoftheLinuxoperatingsystemistheLinuxkernel,whichisresponsibleforallocatingthe
computer'sresourcesandschedulinguserjobssothateachonegetsitsfairshareofsystemresources,
includingaccesstotheCPU;peripheraldevices,suchasdisk,DVD,andCD-ROMstorage;printers;and
tapedrives.Programsinteractwiththekernelthroughsystemcalls,specialfunctionswithwell-known
names.Aprogrammercanuseasinglesystemcalltointeractwithmanykindsofdevices.Forexample,
thereisonewritesystemcall,notmanydevice-specificones.Whenaprogramissuesawriterequest,the
kernelinterpretsthecontextandpassestherequesttotheappropriatedevice.Thisflexibilityallowsold
utilitiestoworkwithdevicesthatdidnotexistwhentheutilitieswereoriginallywritten.Italsomakesit
possibletomoveprogramstonewversionsoftheoperatingsystemwithoutrewritingthem(providedthat
thenewversionrecognizesthesamesystemcalls).
LinuxCanSupportManyUsers
Dependingonthehardwareandwhattypesoftasksthecomputerperforms,aLinuxsystemcansupport
from1tomorethan1,000users,eachconcurrentlyrunningadifferentsetofprograms.Theper-usercost

ofacomputerthatcanbeusedbymanypeopleatthesametimeislessthanthatofacomputerthatcanbe
usedbyonlyasinglepersonatatime.Itislessbecauseonepersoncannotgenerallyusealltheresources
acomputerhastooffer.Noonecankeeptheprintersgoingconstantly,keepallthesystemmemoryinuse,
keepthedisksbusyreadingandwriting,keeptheInternetconnectioninuse,andkeepalltheterminals
busyatthesametime.Amultiuseroperatingsystemallowsmanypeopletousethesesystemresources
almostsimultaneously.Theuseofcostlyresourcescanbemaximized,andthecostperusercanbe
minimized.Thesearetheprimaryobjectivesofamultiuseroperatingsystem.
LinuxCanRunManyTasks
Linuxisafullyprotectedmultitaskingoperatingsystem,allowingeachusertorunmorethanonejobata
time.Processescancommunicatewithoneanotherbutremainfullyprotectedfromoneanother,justasthe
kernelisprotectedfromallprocesses.Youcanrunseveraljobsinthebackgroundwhilegivingallyour
attentiontothejobbeingdisplayedonyourscreen,andyoucanswitchbackandforthbetweenjobs.If
youarerunningtheXWindowSystem(page15),youcanrundifferentprogramsindifferentwindowson
thesamescreenandwatchallofthem.Thiscapabilityensuresthatuserscanbemoreproductive.
LinuxProvidesaSecureHierarchicalFilesystem
Afileisacollectionofinformation,suchastextforamemoorreport,anaccumulationofsalesfigures,
animage,asong,oranexecutableprogram.Eachfileisstoredunderauniqueidentifieronastorage
device,suchasaharddisk.TheLinuxfilesystemprovidesastructurewherebyfilesarearrangedunder
directories,whicharelikefoldersorboxes.Eachdirectoryhasanameandcanholdotherfilesand
directories.Directories,inturn,arearrangedunderotherdirectories,andsoforth,inatreelike
organization.Thisstructurehelpsuserskeeptrackoflargenumbersoffilesbygroupingrelatedfilesinto
directories.Eachuserhasoneprimarydirectoryandasmanysubdirectoriesasrequired(Figure1-2).
Figure1-2.TheLinuxfilesystemstructure

Standards
Withtheideaofmakinglifeeasierforsystemadministratorsandsoftwaredevelopers,agroupgot
togetherovertheInternetanddevelopedtheLinuxFilesystemStandard(FSSTND),whichhassince
evolvedintotheLinuxFilesystemHierarchyStandard(FHS).Beforethisstandardwasadopted,key
programswerelocatedindifferentplacesindifferentLinuxdistributions.Todayyoucansitdownata
Linuxsystemandknowwheretoexpecttofindanygivenstandardprogram.
Links
Alinkallowsagivenfiletobeaccessedbymeansoftwoormoredifferentnames.(Windowsusesthe
termshortcutinsteadoflink.)Thealternativenamescanbelocatedinthesamedirectoryastheoriginal
fileorinanotherdirectory.Linkscanbeusedtomakethesamefileappearinseveralusers'directories,
enablingthemtosharethefileeasily.
Security
Likemostmultiuseroperatingsystems,Linuxallowsuserstoprotecttheirdatafromaccessbyother
users.Italsoallowsuserstoshareselecteddataandprogramswithcertainotherusersbymeansofa
simplebuteffectiveprotectionscheme.Thislevelofsecurityisprovidedbyfileaccesspermissions,
whichlimitwhichuserscanreadfrom,writeto,orexecuteafile.AccessControlLists(ACLs)have
recentlybeenaddedtotheLinuxkernel.ACLsgiveusersandadministratorsfiner-grainedcontrolover
fileaccesspermissions.
TheShell:CommandInterpreterAndProgrammingLanguage
Inatextualenvironment,theshellthecommandinterpreteractsasaninterfacebetweenyouandthe
operatingsystem.Whenyouenteracommandonthescreen,theshellinterpretsthecommandandcallsthe
programyouwant.AnumberofshellsareavailableforLinuxincludingthesetwocommonones:
TheBourneAgainShell(bash),anenhancedversionoftheBourneShell,oneoftheoriginalUNIX
shells
TheTCShell(tcsh),anenhancedversionoftheCShell,developedaspartofBSDUNIX
Becauseusersoftenpreferdifferentshells,multiusersystemscanhaveanumberofdifferentshellsinuse
atanygiventime.ThechoiceofshellsdemonstratesoneofthepowersoftheLinuxoperatingsystem:the
abilitytoprovideacustomizeduserinterface.
Besidesperformingitsfunctionofinterpretingcommandsfromakeyboardandsendingthemtothe
operatingsystem,theshellisahigh-levelprogramminglanguage.Shellcommandscanbearrangedina
fileforlaterexecution.Linuxcallsthesefilesshellscripts;DOSandWindowscallthembatchfiles.
Theirflexibilityallowsuserstoperformcomplexoperationswithrelativeease,oftenbyusingrather
shortcommands,andtobuildwithsurprisinglylittleeffortelaborateprogramsthatperformhighly
complexoperations.
FilenameGeneration
Whenyouaretypingcommandstobeprocessedbytheshell,youcanconstructpatternsusingcharacters
thathavespecialmeaningstotheshell.Thecharactersarecalledwildcardcharacters.Thesepatterns
representakindofshorthand:Ratherthantypingincompletefilenamesuserscantypeinpatterns,andthe
shellwillexpandthemintomatchingfilenames.Thesepatternsarecalledambiguousfilereferences.An
ambiguousfilereferencecansaveyoutheeffortoftypingalongfilenameoralongseriesofsimilar
filenames.Itcanalsobeusefulwhenyouknowonlypartofafilenameorcannotrememberitsexact
spelling.
Device-IndependentInputAndOutput
Redirection
Devices(suchasaprinterorterminal)anddiskfilesallappearasfilestoLinuxprograms.Whenyou
giveacommandtotheLinuxoperatingsystem,youcaninstructittosendtheoutputtoanyoneofseveral
devicesorfiles.Thisdiversioniscalledoutputredirection.
Inasimilarmanneraprogram'sinputthatnormallycomesfromakeyboardcanberedirectedsothatit
comesfromadiskfileinstead.Inputandoutputaredeviceindependent;theycanberedirectedtoorfrom
anyappropriatedevice.
Asanexample,thecatutilitynormallydisplaysthecontentsofafileonthescreen.Whenyourunacat
command,youcaneasilyredirectitsoutputtogotoadiskfileinsteadofthescreen.
ShellFunctions
Oneofthemostimportantfeaturesoftheshellisthatuserscanuseitasaprogramminglanguage.Because
theshellisaninterpreter,itdoesnotcompileprogramswrittenforitbutratherinterpretsthemeachtime
theyareloadedfromthedisk.Loadingandinterpretingprogramscanbetime-consuming.
Manyshells,includingtheBourneAgainShell,includeshellfunctionsthattheshellholdsinmemoryso
thatitdoesnothavetoreadthemfromthediskeachtimeyouwanttoexecutethem.Theshellalsokeeps
functionsinaninternalformatsothatitdoesnothavetospendasmuchtimeinterpretingthem.
JobControl
Jobcontrolisashellfeaturethatallowsuserstoworkonseveraljobsatonce,switchingbackandforth
betweenthemasdesired.Whenyoustartajobitisfrequentlyintheforeground,soitisconnectedtoyour
terminal.Usingjobcontrol,youcanmovethejobyouareworkingwithintothebackgroundandcontinue
runningittherewhileworkingonorobservinganotherjobintheforeground.Ifabackgroundjobthen
needsyourattention,youcanmoveitintotheforegroundsothatitisonceagainattachedtotheterminal.
TheconceptofjobcontroloriginatedwithBSDUNIX,whereitappearedintheCShell.
ALargeCollectionOfUsefulUtilities
Linuxincludesafamilyofseveralhundredutilityprograms,oftenreferredtoascommands.These
utilitiesperformfunctionsthatareuniversallyrequiredbyusers.Anexampleissort.Thesortutility
putslists(orgroupsoflists)inalphabeticalornumericalorderandcanbeusedtosortbypartnumber,
lastname,city,ZIPcode,telephonenumber,age,size,cost,andsoforth.Thesortutilityisanimportant
programmingtoolandispartofthestandardLinuxsystem.Otherutilitiesallowuserstocreate,display,
print,copy,search,anddeletefiles,aswellastoedit,format,andtypesettext.Theman(formanual)and
infoutilitiesprovideonlinedocumentationofLinuxitself.
InterprocessCommunication
Pipesandfilters
Linuxallowsuserstoestablishbothpipesandfiltersonthecommandline.Apipesendstheoutputofone
programtoanotherprogramasinput.Afilterisaspecialformofapipethatprocessesastreamofinput
datatoyieldastreamofoutputdata.Afilterprocessesanotherprogram'soutput,alteringitasaresult.
Thefilter'soutputthenbecomesinputtoanotherprogram.
Pipesandfiltersfrequentlyjoinutilitiestoperformaspecifictask.Forexample,youcanuseapipeto
sendtheoutputofthecatutilitytosort,afilter.Youcanthenuseanotherpipetosendtheoutputof
sorttoathirdutility,lpr,thatsendsthedatatoaprinter.Thus,inonecommandline,youcanusethree
utilitiestogethertosortandprintafile.
SystemAdministration
OnaLinuxsystemthesystemadministratorisfrequentlytheownerandonlyuserofthesystem.This
personhasmanyresponsibilities.Thefirstresponsibilitymaybetosetupthesystemandinstallthe
software.
Oncethesystemisupandrunning,thesystemadministratorisresponsiblefordownloadingandinstalling
software(includingupgradingtheoperatingsystem),backingupandrestoringfiles,andmanagingsuch
systemfacilitiesasprinters,terminals,servers,andalocalnetwork.Thesystemadministratorisalso
responsibleforsettingupaccountsfornewusersonamultiusersystem,bringingthesystemupanddown
asneeded,andtakingcareofanyproblemsthatarise.
AdditionalFeaturesofLinux
ThedevelopersofLinuxincludedfeaturesfromBSD,SystemV,andSunMicrosystems'Solaris,aswell
asnewfeaturesintheiroperatingsystem.AlthoughmostofthetoolsfoundonUNIXexistforLinux,in
manycasesthesetoolshavebeenreplacedbymoremoderncounterparts.Thefollowingsectionsdescribe
manyofthepopulartoolsandfeaturesavailableunderLinux.
Guis:GraphicalUserInterfaces
TheXWindowSystem(alsocalledX)wasdevelopedinpartbyresearchersattheMassachusetts
InstituteofTechnologyandprovidesthefoundationfortheGUIsavailablewithLinux.Givenaterminal
orworkstationscreenthatsupportsX,ausercaninteractwiththecomputerthroughmultiplewindowson
thescreen,displaygraphicalinformation,orusespecial-purposeapplicationstodrawpictures,monitor
processes,orpreviewformattedoutput.Xisanacross-the-networkprotocolthatallowsausertoopena
windowonaworkstationorcomputersystemthatisremotefromtheCPUgeneratingthewindow.
Desktopmanager
UsuallytwolayersrununderX:adesktopmanagerandawindowmanager.Adesktopmanagerisa
picture-orienteduserinterfacethatenablesyoutointeractwithsystemprogramsbymanipulatingicons
insteadoftypingthecorrespondingcommandstoashell.GNOME(www.gnome.org)andKDE
(www.kde.org)arethemostpopulardesktopmanagers.
Windowmanager
Awindowmanagerisaprogramthatrunsunderthedesktopmanagerandallowsyoutoopenandclose
windows,startprogramsrunning,andsetupamousesoitdoesdifferentthingsdependingonhowand
whereyouclick.Thewindowmanageralsogivesthescreenitspersonality.MicrosoftWindowsallows
youtochangethecolorofkeyelementsinawindow,butawindowmanagerunderXallowsyouto
changetheoveralllookandfeelofyourscreen:changethewayawindowlooksandworks(bygivingit
differentborders,buttons,andscrollbars),setupvirtualdesktops,createmenus,andmore.
SeveralpopularwindowmanagersrununderXandLinux,includingMetacity(defaultunderGNOME)
andkwin(defaultunderKDE).Otherwindowmanagers,suchasSawfishandWindowMaker,arealso
available.
(Inter)NetworkingUtilities
Linuxnetworksupportincludesmanyvaluableutilitiesthatenableyoutoaccessremotesystemsovera
varietyofnetworks.Inadditiontosendingemailtousersonothersystems,youcanaccessfilesondisks
mountedonothercomputersasiftheywerelocatedonthelocalsystem,makeyourfilesavailabletoother
systemsinasimilarmanner,copyfilesbackandforth,runprogramsonremotesystemswhiledisplaying
theresultsonthelocalsystem,andperformmanyotheroperationsacrosslocalareanetworks(LANs)and
wideareanetworks(WANs),includingtheInternet.
Layeredontopofthisnetworkaccessareawiderangeofapplicationprogramsthatextendthecomputer's
resourcesaroundtheglobe.Youcancarryonconversationswithpeoplethroughouttheworld,gather
informationonawidevarietyofsubjects,anddownloadnewsoftwareovertheInternetquicklyand
reliably.
SoftwareDevelopment
OneofLinux'smajorstrengthsisitsrichsoftwaredevelopmentenvironment.Youcanfindcompilersand
interpretersformanycomputerlanguages.BesidesCandC++,languagesavailableforLinuxinclude
Ada,Fortran,Java,Lisp,Pascal,Perl,andPythonamongmanyothers.Thebisonutilitygenerates
parsingcodethatmakesiteasiertowriteprogramstobuildcompilers(toolsthatparsefilescontaining
structuredinformation).Theflexutilitygeneratesscanners,orcodethatrecognizeslexicalpatternsin
text.ThemakeutilityandGNU'sautomaticconfigurationutility(configure)makeiteasytomanage
complexdevelopmentprojects.Sourcecodemanagementsystems,suchasCVS,simplifyversioncontrol.
Severaldebuggers,includingupsandgdb,helpintrackingdownandrepairingsoftwaredefects.The
GNUCcompiler(gcc)workswiththegprofprofilingutilitytohelpprogrammersidentifypotential
bottlenecksinaprogram'sperformance.TheCcompilerincludesoptionstoperformextensivechecking
ofCcodethatcanmakethecodemoreportableandreducedebuggingtime.
ChapterSummary
TheLinuxoperatingsystemgrewoutoftheUNIXheritagetobecomeapopularalternativetotraditional
systems(thatis,Windows)availableformicrocomputer(PC)hardware.UNIXuserswillfindafamiliar
environmentinLinux.DistributionsofLinuxcontaintheexpectedcomplementofUNIXutilities,
contributedbyprogrammersaroundtheworld,includingthesetoftoolsdevelopedaspartoftheGNU
Project.TheLinuxcommunityiscommittedtothecontinueddevelopmentofthissystem.Supportfornew
microcomputerdevicesandfeaturesisaddedsoonafterthehardwarebecomesavailable,andthetools
availableonLinuxcontinuetoberefined.Withmanycommercialsoftwarepackagesavailabletorunon
LinuxplatformsandmanyhardwaremanufacturersofferingLinuxontheirsystems,itisclearthatthe
systemhasevolvedwellbeyonditsoriginasanundergraduateprojecttobecomeanoperatingsystemof
choiceforacademic,commercial,professional,andpersonaluse.
Exercises
1. Whatisfreesoftware?Listthreecharacteristicsoffreesoftware.
2. WhyisLinuxpopular?Whyisitpopularinacademia?
3. Whataremultiusersystems?Whyaretheysuccessful?
4. WhatistheFreeSoftwareFoundation/GNU?WhatisLinux?WhichpartsoftheLinuxoperatingsystemdideachprovide?Whoelsehas
helpedbuildandrefinethisoperatingsystem?
5. InwhatlanguageisLinuxwritten?WhatdoesthelanguagehavetodowiththesuccessofLinux?
6. Whatisautilityprogram?
7. Whatisashell?Howdoesitworkwiththekernel?Withtheuser?
8. Howcanyouuseutilityprogramsandashelltocreateyourownapplications?
9. WhyistheLinuxfilesystemreferredtoashierarchical?
10. Whatisthedifferencebetweenamultiprocessorandamultiprocessingsystem?
11. Giveanexampleofwhenyouwouldwanttouseamultiprocessingsystem.
12. ApproximatelyhowmanypeoplewroteLinux?Whyisthisunique?
13. WhatarethekeytermsoftheGNUGeneralPublicLicense(GPL)?
Chapter2.GettingStarted
INTHISCHAPTER
ConventionsUsedinThisBook22
LoggingIn24
LoggingInRemotely:TerminalEmulation,ssh,andtelnet25
CurbingYourPower:SuperuserAccess28
GettingtheFacts:WheretoFindDocumentation29
ThehelpOption29
man:DisplaystheSystemManual30
info:DisplaysInformationAboutUtilities32
HOWTOs:FindingOutHowThingsWork34
WhattoDoIfYouCannotLogIn36
ChangingYourPassword37
Onewayoranotheryouaresittinginfrontofascreenthatisconnectedtoacomputerthatisrunning
Linux.Youmaybeworkingwithagraphicaluserinterface(GUI)oratextualinterface.Thisbookisabout
thetextual,orcommandline,interfacetoLinux.IfyouareworkingwithaGUI,youwillneedtousea
terminalemulatorsuchasxterm,Konsole,orGNOMETerminal,tofollowalongwiththeexamplesin
thisbook.
Thischapterstartswithadiscussionofthetypographicalconventionsusedinthisbook,followedbya
sectiononlogginginonthesystem.NextthereisabriefreminderaboutthepowersofSuperuser(root)
andhowtoavoidmakingmistakesthatwillmakeyoursysteminoperableorhardtoworkwith.The
chaptercontinueswithadiscussionaboutwheretofindmoreinformationaboutLinux.Itconcludeswith
additionalinformationonloggingin,includinghowtochangeyourpassword.
WhileheedingthewarningaboutthedangersofmisusingthepowersofSuperuseronpage29,feelfreeto
experimentwithyoursystem:Givecommands,createfiles,followtheexamplesinthisbook,andhave
fun.
ConventionsUsedinThisBook
Thisbookusesconventionstomakeitsexplanationsshorterandclearer.Thefollowingparagraphs
describetheseconventions.
Textandexamples
Thetextissetinthistype,whereasexamplesareshowninamonospacefont(alsocalledafixed-
widthfont):
$catpractice
ThisisasmallfileIcreated
withatexteditor.
Thenextparagraphexplainswhypartofthefirstlineisinaboldtypeface.
Itemsyouenter
Everythingyouenteratthekeyboardisshowninaboldtypeface:Withinthetext,thisboldtypefaceis
used;withinexamplesandscreens,thisoneisused.Inthepreviousexample,thedollarsign($)on
thefirstlineisapromptthatLinuxdisplays,soitisnotbold;theremainderofthefirstlineisenteredbya
user,soitisbold.
Utilitynames
Namesofutilitiesareprintedinthisboldsansseriftypeface.Thisbookreferencesthe
emacseditorandthelsutilityorlscommand(orjustls),butinstructsyoutoenterlsaonthe
commandline.Thetextdistinguishesbetweenutilities,whichareprograms,andtheinstructionsyougive
onthecommandlinetoinvoketheutilities.
Filenames

Filenamesappearinaboldtypeface.Examplesarememo5,letter.1283,andreports.Filenamesmay
includeuppercaseandlowercaseletters;however,Linuxiscasesensitive(866),somemo5,MEMO5,
andMemo5namethreedifferentfiles.
Characterstrings
Withinthetext,charactersandcharacterstringsaremarkedbyputtingtheminaboldtypeface.This
conventionavoidstheneedforquotationmarksorotherdelimitersbeforeandafterastring.Anexample
isthefollowingstring,whichisdisplayedbythepasswdutility:Sorry,passwordsdonotmatch.
Keysandcharacters
ThisbookusesSMALLCAPSforthreekindsofitems:
Importantkeyboardkeys,suchastheSPACEbarandtheRETURN,[1]ESCAPE,andTABkeys.
[1]Differentkeyboardsusedifferentkeystomovethecursor(870)tothebeginningofthenextline.Thisbookalwaysrefers
tothekeythatendsalineastheRETURNkey.YourkeyboardmayhaveaRET,NEWLINE,Enter,RETURN,orother
key.Somekeyboardshaveakeywithabentarrowonit.(Thekeywiththebentarrowisnotanarrowkey.Arrowkeyshave
straightshafts.)UsethecorrespondingkeyonyourkeyboardeachtimethisbookasksyoutopressRETURN.
Thecharactersthatkeysgenerate,suchastheSPACEsgeneratedbytheSPACEbar.
KeyboardkeysthatyoupresswiththeCONTROLkey,suchasCONTROL-D.(EventhoughDis
shownasanuppercaseletter,youdonothavetopresstheSHIFTkey.EnterCONTROL-Dby
holdingdowntheCONTROLkeyandpressingd.)
PromptsandRETURNs
MostexamplesincludetheshellpromptthesignalthatLinuxiswaitingforacommandasadollarsign($).
Thepromptisnotinboldface,becauseyoudonotenterit.Donottypethepromptonthekeyboardwhen
youareexperimentingwithexamplesfromthisbook.Ifyoudo,theexampleswillnotwork.
ExamplesomittheRETURNkeystrokethatyoumustusetoexecutethem.Anexampleofacommandline
is
$vimmemo.1204
Tousethisexampleasamodelforrunningthevimeditor,givethecommandvimmemo.1204andpress
theRETURNkey.(PressESCAPEZZtoexitfromvim;seepage141foravimtutorial.)Thismethodof
enteringcommandsmakestheexamplesinthebookcorrespondtowhatappearsonyourscreen.
Definitions
AllentriesmarkedwithFOLDOCarecourtesyofDenisHowe,editoroftheFreeOnlineDictionaryof
Computing(www.foldoc.org),andareusedwithpermission.Thissiteisanongoingworkcontainingnot
justdefinitionsbutalsoanecdotesandtrivia.

optional
Passagesmarkedasoptionalarenotcentraltotheideaspresentedinthechapterbutofteninvolvemorechallengingconcepts.A
goodstrategywhenreadingachapteristoskiptheoptionalsectionsandthenreturntothemwhenyouarecomfortablewiththe
mainideaspresentedinthechapter.Thisisanoptionalparagraph.
URLs(Webaddresses)
Webaddresses,orURLs,haveanimplicithttp://prefix,unlessftp://orhttps://isshown.Youdonot
normallyneedtospecifyaprefixwhentheprefixishttp://,butyoumustuseaprefixfromabrowser
whenyouspecifyanFTPorsecureHTTPsite.ThusyoucanspecifyaURLinabrowserexactlyasshown
inthisbook.
Tip,Caution,andSecurityboxes
Thefollowingboxeshighlightinformationthatmaybehelpfulwhileyouareusingoradministratinga
Linuxsystem.
tip:Thisisatipbox
Atipboxmayhelpyouavoidrepeatingacommonmistakeormaypointtowardadditional
information.
caution:Thisboxwarnsyouaboutsomething
Acautionboxwarnsyouaboutapotentialpitfall.
security:Thisboxmarksasecuritynote
Asecurityboxhighlightsapotentialsecurityissue.Thesenotesareusuallyforsystem
administratorsbutsomeapplytoallusers.
LoggingIn
Tologinonaterminal,terminalemulator,orothertext-baseddevice,enteryourusernameandpassword
inresponsetothesystemprompts.Ifyouareusingaterminal(905)andyourscreendoesnotdisplay
login:,checkwhethertheterminalispluggedinandturnedon,andthenpresstheRETURNkeyafew
times.Iflogin:stilldoesnotappear,trypressingCONTROL-Q.Ifyouareusingaworkstation(910),
makesureitisrunning.Runssh,telnet,orwhatevercommunications/emulationsoftwareyouhaveto
loginonthesystem.Tryloggingin,makingsurethatyouenteryourusernameandpasswordastheywere
specifiedwhenyouraccountwassetup;theroutinethatverifiestheusernameandpasswordiscase
sensitive.Likemostsystems,Linuxdoesnotechoyourpasswordwhenyouenterit.
tip:MakesureTERMissetcorrectly
TheTERMshellvariableestablishesthepseudographicalcharacteristicsofacharacter-
basedterminalorterminalemulator.TypicallyTERMissetforyouyoudonothavetoset
itmanually.Ifthingsonthescreendonotlookright,referto"SpecifyingaTerminal"on
page844.
LoggingInFromaTerminal
Thefollowingexampleshowswhatitlookslikewhenyouloginfromaterminal.Maxislogginginonthe
bravosystem.
bravologin:max
Password:
Lastlogin:TueMar119:50:38fromkudos
[max@bravomax]$
Afteryoulogin,theshellprompt(orjustprompt)appears,indicatingthatyouhavesuccessfullylogged
in.Itshowsthatthesystemisreadyforyoutogiveitacommand.Theshellpromptlinemaybepreceded
byoneortwoshortmessagescalledthemessageoftheday(ormotd)andissue.Thesemessages
generallyidentifytheversionofLinuxthatisrunning,alongwithlocalmessagesplacedineitherthe
/etc/motdorthe/etc/issuefile.
security:Didyouloginlast?
Immediatelyafteryoulogin,thesystemmaydisplayinformationaboutthelastloginonthis
account,showingwhenittookplaceandwhereitoriginated.Youcanusethisinformation
toseewhetheranyoneelsemayhaveaccessedthisaccountsinceyoulastusedit.Perhaps
anunauthorizeduserhaslearnedyourpasswordandhasloggedinasyou.Intheinterestof
security,advisethesystemadministratorofthecircumstancesthatmadeyoususpiciousand
changeyourpassword(page37).
Theusualpromptisadollarsign($).Donotbeconcernedifyouhaveadifferentprompt;theexamplesin
thisbookwillworkregardlessofwhatyourpromptlookslike.Inthepreviousexamplethe$prompt(last
line)isprecededbytheusername(max),anatsign(@),thesystemname(bravo),andthenameofthe
directoryMaxisworkingin(max).Forinformationonhowtochangeyourprompt,refertopage286
(bash)orpage363(tcsh).
LoggingInRemotely:TerminalEmulation,ssh,andtelnet
Whenyouarenotusingtheconsole,aterminal,oranotherdeviceconnecteddirectlytotheLinuxsystem
youarelogginginon,youareprobablyconnectedtoLinuxusingterminalemulationsoftwareonanother
system.Thissoftwarerunsonyourcomputer,connectstotheLinuxsystemviaanetwork(e.g.,Ethernet,
asynchronousphoneline,PPP),andallowsyoutologinontheLinuxsystem.
Whenyouloginviaadial-upline,theconnectionisstraightforward:Youinstructtheemulatorprogramto
contactthecomputer,itdialsthephone,andyougetaloginpromptfromtheremotesystem.Whenyoulog
inviaadirectlyconnectednetwork,youusetelnet(notsecure,page792)orssh(secure,page773)
toconnecttotheremotesystem.Oneofthereasonsthattelnetisnotsecureisthatitsendsyour
usernameandpasswordoverthenetworkincleartext(867)whenyoulogin,allowingsomeoneto
captureyourlogininformationandloginonyouraccount.Thesshutilityencryptsallinformationit
sendsoverthenetworkand,ifavailable,isabetterchoicethantelnet.
FromanApple,PC,UNIX,orothermachine,givethecommandsshortelnet,followedbythenameor
IPaddress(882)ofthemachineyouwanttologinon.Followingisanexampleoflogginginusingssh:
$sshbravo
max@bravo'spassword:
Permissiondenied,pleasetryagain.
max@bravo'spassword:
Lastlogin:WedMar221:21:492005frombravo.example.com
[max@bravomax]$
Intheprecedingexampletheusermistypedhispassword,receivedanerrormessageandanotherprompt,
andretypedthepasswordcorrectly.
WorkingwiththeShell
Whenyouloginandareworkinginatextual(nongraphical)environment,andwhenyouareusinga
terminalemulatorwindowinagraphicalenvironment,youareusingtheshellasacommandinterpreter.
Thatis,theshelldisplaysaprompt,youtypeacommand,andtheshellexecutesthecommandand
displaysanotherprompt.
Thissectiontellsyouhowtoidentifytheshellyouareusingandexplainsthekeystrokesyoucanuseto
correctmistakesonthecommandline.Itcovershowtoabortarunningcommandandbrieflydiscusses
howtoeditacommandline.Severalchaptersofthisbookarededicatedtoshells:Chapter5introduces
shells,Chapter8goesintomoredetailabouttheBourneAgainShellwithsomecoverageoftheTCShell,
Chapter9coverstheTCShellexclusively,andChapter11discusseswritingprograms(shellscripts)
usingtheBourneAgainShell.
WhichShellAreYouRunning?
ThisbookdiscussesboththeBourneAgainShell(bash)andtheTCShell(tcsh).Youareprobably
runningbash,butyoumayberunningtcshoranothershellsuchastheZShell(zsh).Youcanidentify
theshellyouarerunningbyusingthepsutility.Typepsinresponsetotheshellpromptandpress
RETURN.
$ps
PIDTTYTIMECMD
2402pts/500:00:00bash
7174pts/500:00:00ps
Thiscommandshowsthatyouarerunningtwoutilitiesorcommands:bashandps.Ifyouarerunning
tcsh,pswilldisplaytcshinsteadofbash.Ifyouarerunningadifferentshell,pswilldisplayitsname.
CorrectingMistakes
Thissectionexplainshowtocorrecttypographicalandothererrorsyoumaymakewhileyouarelogged
inonacharacter-baseddisplay.Becausetheshelldoesnotbegintointerpretthecommandlineorother
textuntilyoupressRETURN,youcancorrecttypingmistakesbeforeyoupressthatkey.
Youcancorrecttypingmistakesinseveralways:Youcaneraseonecharacteratatime,backupawordat
atime,orbackuptothebeginningofthecommandlineinonestep.AfteryoupressRETURN,itistoo
latetocorrectamistake.Youmusteitherwaitforthecommandtoruntocompletionorabortexecutionof
theprogram(page27).
ErasingaCharacter
Whileenteringcharactersfromthekeyboard,youcanbackupanderaseamistakebypressingtheerase
keyonceforeachcharacteryouwanttodelete.Theerasekeybacksoverasmanycharactersasyouwish.
Usuallyitwillnotbackuppastthebeginningoftheline.
ThedefaulterasekeyisBACKSPACE.Ifthiskeydoesnotwork,tryDELETEorCONTROL-H.Ifthese
keysdonotwork,givethefollowingcommandtosettheeraseandlinekillkeys(see"DeletingaLine"on
page27)totheirdefaults:
$sttyek
Forinformationonchangingwhichkeyerasescharacters,refertopage781.
tip:CONTROL-Zsuspendsaprogram
Althoughnotawayofcorrectingamistake,youmaypressthesuspendkey(typically
CONTROL-Z)bymistakeandwonderwhathappened(youwillseeamessagecontaining
thewordStopped).Youhavejuststoppedthejobyouwererunning,usingjobcontrol
(page271).Givethecommandfgtocontinueyourjobintheforeground,andyoushould
returntowhereyouwerebeforeyoupressedthesuspendkey.Formoreinformationreferto
"bg:SendsaJobtotheBackground:SendsaJobtotheBackground"onpage273.
DeletingaWord
YoucandeleteawordyouenteredbypressingCONTROL-W.Awordisanysequenceofcharactersthat
doesnotcontainaSPACEorTAB.WhenyoupressCONTROL-W,thecursormoveslefttothebeginning
ofthecurrentword(asyouareenteringaword)orthepreviousword(whenyouhavejustentereda
SPACEorTAB),removingtheworditpassesover.
DeletingaLine
AnytimebeforeyoupressRETURN,youcandeletealineyouareenteringbypressingthelinekillkey,
alsocalledthekillkey.Whenyoupressthiskey,thecursormovestotheleft,erasingcharactersasit
goes,backtothebeginningoftheline.ThedefaultlinekillkeyisCONTROL-U.Ifthiskeydoesnot
work,tryCONTROL-X.Ifneitherkeyworks,givethefollowingcommandtosettheeraseandlinekill
keystotheirdefaults:
$sttyek
Forinformationonchangingwhichkeydeletesaline,refertopage781.
AbortingExecution
Sometimesyoumaywanttoterminatearunningprogram.Forexample,aLinuxprogrammaybe
performingalengthytasksuchasdisplayingthecontentsofafilethatisseveralhundredpageslongor
copyingafilethatisnottheoneyoumeanttocopy.
Toterminateaprogramfromacharacter-baseddisplay,presstheinterruptkey(CONTROL-Cor
sometimesDELETEorDEL).Whenyoupressthiskey,theLinuxoperatingsystemsendsaterminal
interruptsignalbothtotheprogramyouarerunningandtotheshell.Exactlywhateffectthissignalhas
dependsontheprogram.Someprogramsstopexecutionimmediately;othersignorethesignal.Some
programstakeotheractions.Whenitreceivesaterminalinterruptsignal,theshelldisplaysapromptand
waitsforanothercommand.Forinformationonchangingwhichkeyabortsexecution,refertopage781.
Ifthesemethodsdonotterminatetheprogram,trystoppingtheprogramwiththesuspendkey(typically
CONTROL-Z),givingthejobscommandtoverifythejobnumberoftheprogram,andusingkillto
aborttheprogram.Thejobnumberisthenumberwithinthebracketsattheleftendofthelinethatjobs
displays([1]).Thekillcommandsendsasignaltothejobspecifiedasitsargument.Youmustprecede
thejobnumberwithapercentsign(%1):
$bigjob
^Z
[1]+Stoppedbigjob
$jobs
[1]+Stoppedbigjob
$kill%1
[1]+Stoppedbigjob
$RETURN
[1]+Killedbigjob
Bydefaultkillsendsasoftwareterminationsignal(TERM).Whenthissignaldoesnotwork,tryusing
akill(KILL)signal:
$kill-KILL%1
Arunningprogramcannotignoreakillsignalitissuretoaborttheprogram.Thekillcommandreturnsa
prompt;pressRETURNagaintoseetheconfirmationmessage.Formoreinformationonjobcontrol,refer
to"RunningaProgramintheBackground"onpage125.Foralistofsignals,seeTable11-5onpage494.
Repeating/EditingCommandLines
Torepeatapreviouscommandonthecommandline,presstheUPARROWkey.EachtimeyoupressUP
ARROW,youseeanearliercommandline.Toreexecutethedisplayedcommandline,pressRETURN.
PressDOWNARROWtobrowsethroughthecommandlinesintheotherdirection.
TheRIGHTandLEFTARROWkeysmovethecursorbackandforthalongthedisplayedcommandline.
Atanypointalongthecommandline,youcanaddcharactersbytyping.Usetheerasekeytoremove
charactersfromthecommandline.
Formorecomplexcommandlineediting,seepage297(bash)andpage353(tcsh).
CurbingYourPower:SuperuserAccess
Whileyouareloggedinastheusernamedroot,youarereferredtoasSuperuseroradministratorand
haveextraordinaryprivileges.Youcanreadfromorwritetoanyfileonthesystem,executeprogramsthat
ordinaryuserscannot,andmore.Onamultiusersystemyoumaynotbepermittedtoknowtheroot
password,butsomeoneusuallythesystemadministratorknowstherootpasswordandmaintainsthe
system.WhenyouarerunningLinuxonyourowncomputer,youwillassignapasswordtorootwhenyou
installLinux.
caution:DonotexperimentasSuperuser
Feelfreetoexperimentwhenyouareloggedinasyourself.WhenyouloginasSuperuser,
alsocalledrootoradministrator,orwheneveryougivetheSuperuserpassword,doonly
whatyouhavetodoandmakesureyouknowexactlywhatyouaredoing.Afteryouhave
completedthetaskathand,reverttoworkingasyourself.WhenworkingasSuperuseryou
candamagetheLinuxsystemtosuchanextentthatyouwillneedtoreinstallLinuxtogetit
workingagain.
GettingtheFacts:WheretoFindDocumentation
DistributionsofLinuxtypicallydonotcomewithhardcopyreferencemanuals.However,itsonline
documentationhasalwaysbeenoneofLinux'sstrengths.Themanual(orman)andinfopageshavebeen
availableviathemanandinfoutilitiessinceearlyreleasesoftheoperatingsystem.Withthegrowthof
LinuxandtheInternet,thesourcesofdocumentationhaveexpanded.Thefollowingsectionsdiscusssome
oftheplacesyoucanlookforinformationonvariousaspectsofLinux.
ThehelpOption
MostGNUutilitieshaveahelpoptionthatdisplaysinformationabouttheutility.
$cat--help
Usage:cat[OPTION][FILE]...
ConcatenateFILE(s),orstandardinput,tostandardoutput.
-A,--show-allequivalentto-vET
-b,--number-nonblanknumbernonblankoutputlines
-eequivalentto-vE
-E,--show-endsdisplay$atendofeachline
...
Iftheinformationthathelpdisplaysrunsoffthescreen,sendtheoutputthroughthelesspager(page31)
usingapipe:
$ls--help|less
Moreinformationaboutpipesappearsonpage52.Non-GNUutilitiesmayuseahorhelpoptionto
displayhelpinformation.
Figure2-1.Themanutilitydisplayinginformationaboutwho
WHO(1)UserCommands
WHO(1)
NAME
who-showwhoisloggedon
SYNOPSIS
who[OPTION]...[FILE|ARG1ARG2]
DESCRIPTION
-a,--all
sameas-b-d--login-p-r-t-T-u
-b,--boot
timeoflastsystemboot
-d,--dead
printdeadprocesses
-H,--heading
printlineofcolumnheadings
-i,--idle
addidletimeasHOURS:MINUTES,.orold(deprecated,use
-u)
man:DisplaystheSystemManual
Theman(manual)utilitydisplayspages(manpages)fromthesystemdocumentation.Thisdocumentation
ishelpfulwhenyouknowwhichutilityyouwanttousebuthaveforgottenexactlyhowtouseit.Youcan
alsorefertothemanpagestogetmoreinformationaboutspecifictopicsortodeterminewhichfeatures
areavailablewithLinux.Becausethedescriptionsinthesystemdocumentationareoftenterse,theyare
mosthelpfulifyoualreadyunderstandbasicallywhatautilitydoes.
Tofindoutmoreaboutautility,includingthemanutilityitself,givethecommandman,followedbythe
nameoftheutility.Figure2-1showstheoutputofamanwhocommand.
less(pager)
Thecommandmanmandisplaysinformationaboutthemanutility.Themanutilityautomaticallysends
theoutputthroughapager,usuallyless(page45),whichallowsyoutoviewafileonescreenatatime.
Whenyoudisplayamanualpageinthismanner,lessdisplaysaprompt(:)atthebottomofthescreen
aftereachscreenoftextandwaitsforyoutorequestanotherscreenbypressingtheSPACEbar.Pressing
h(help)displaysalistoflesscommands.Pressingq(quit)stopsmanandcausestheshelltodisplaya
prompt.Youcansearchfortopicscoveredbymanpagesbyusingtheaproposutility(page62).
Manualsections
BasedontheFHS(FilesystemHierarchyStandard,page86),theLinuxsystemmanualandthemanpages
aredividedintotensections.Eachsectiondescribesrelatedtools:
1. UserCommands
2. SystemCalls
3. Subroutines
4. Devices
5. FileFormats
6. Games
7. Miscellaneous
8. SystemAdministration
9. Local
10. New
ThislayoutcloselymimicsthewaythesetofUNIXmanualshasalwaysbeendivided.Unlessyouspecify
amanualsection,mandisplaystheearliestoccurrenceinthemanualofthewordyouprovideonthe
commandline.Mostusersfindtheinformationtheyneedinsections1,6,and7;programmersandsystem
administratorsfrequentlyneedtoconsulttheothersections.
Insomecasesthemanualcontainsentriesfordifferenttoolswiththesamename.Forexample,the
followingcommanddisplaysthemanualpageforthewriteutility(page67)fromsection1ofthe
systemmanual:
$manwrite
Toseethemanualpageforthewritesystemcallfromsection2,enter
$man2write
Theprecedingcommandinstructsmantolookonlyinsection2forthemanualpage.Usetheaoption(see
theadjacenttip)toviewallthemanpagesforagivensubject(pressqtomovetothenextsection).Use
manawritetoviewallthemanpagesforwrite.
tip:Options
Anoptionmodifiesthewayautilityorcommandworks.Optionsarespecifiedasoneor
morelettersthatareprecededbyoneortwohyphens(withsomeexceptions).Theoption
appearsfollowingthenameoftheutilityyouarecallingandaSPACE.Anyother
arguments(861)tothecommandfollowtheoptionandaSPACE.Formoreinformation
referto"Options"onpage109.
tip:manandinfodisplaydifferentinformation
Theinfoutilitydisplaysmorecompleteandup-to-dateinformationonGNUutilitiesthan
doesman.Whenamanpagedisplaysabbreviatedinformationonautilitythatiscovered
byinfo,themanpagerefersyoutoinfo.Themanutilityfrequentlydisplaystheonly
informationavailableonnon-GNUutilities.Wheninfodisplaysinformationonnon-GNU
utilities,itisfrequentlyacopyofthemanpage.

info:DisplaysInformationAboutUtilities
Thecharacter-basedinfoutilityisamenu-basedhypertextsystemdevelopedbytheGNUprojectand
distributedwithLinux.Theinfoutilityincludesatutorialonitself(givethecommandinfoinfoorgoto
www.gnu.org/software/texinfo/manual/info)anddocumentationonmanyLinuxshells,utilities,and
programsdevelopedbytheGNUproject(page2).Figure2-2showsthescreenthatinfodisplayswhen
yougivethecommandinfo.
Figure2-2.Thefirstscreenthatinfodisplays
[Viewfullsizeimage]
Becausetheinformationonthisscreenisdrawnfromaneditablefile,yourdisplaymaydiffer.Whenyou
seetheinitialinfoscreen,youcanpress
htogothroughaninteractivetutorialoninfo
?tolistinfocommands
SPACEtoscrollthroughthemenuofitemsforwhichinformationisavailable
mfollowedbythenameofthemenuitemyouwanttodisplay

qtoquit
Thenotationinfousestodescribekeyboardkeysmaynotbefamiliartoyou.ThenotationC-histhe
sameasCONTROL-H.SimilarlyM-xmeansholddowntheMETAorALTkeyandpressx.(Onsome
systemsyouneedtopressESCAPEandthenxtoduplicatethefunctionofMETA-x.)
Aftergivingthecommandinfo,presstheSPACEbarafewtimestoscrollthedisplay.Figure2-3shows
theentryforsleep.Theasteriskattheleftendofthelinemeansthatthisentryisthebeginningofamenu
item.Followingtheasteriskisthenameofthemenuitem,followedbyacolon,thenameofthepackage
(inparentheses)thatthemenuitembelongsto,otherinformation,andadescriptionoftheitemontheright.
Figure2-3.ThescreenthatinfodisplaysafteryoupressSPACEafewtimes
[Viewfullsizeimage]
Eachmenuitemisanactivelinktotheinfopagethatdescribestheitem.Tojumptothatpage,movethe
cursortothelinecontainingthemenuitemandpressRETURN.Alternativelyyoucantypethenameofthe
menuiteminamenucommandtoviewtheinformation.Togetinformationonsleep,forexample,you
givethecommandmsleep,followedbyaRETURN.Whenyoutypem(formenu),thecursormovesto
thebottomlineofthescreenanddisplaysMenuitem:.Typingsleepdisplayssleeponthatline,and
pressingRETURNtakesyoutothemenuitemyouhavechosen.
Figure2-4showsthetopnodeofinformationonsleep.Anodeisonegroupofinformationthatyoucan
scrollthroughwiththeSPACEbar.Togettothenextnode,pressn.Pressptogettothepreviousnode.
Youcanalwayspressdtodisplaytheinitialmenu(Figure2-2).
Figure2-4.Theinfopageonthesleeputility

[Viewfullsizeimage]
Asyoureadthisbookandlearnaboutnewutilities,youcanusemanorinfotofindoutmoreaboutthe
utilities.IfyoucanprintPostScriptdocuments,youcanprintamanualpagewiththemanutilityusingthe
toption(forexample,mantcat|lprprintsinformationaboutthecatutility).Betteryet,useabrowser
tolookatthedocumentationatwww.tldp.organdprinttheinformationfromthebrowser.
HOWTOs:FindingOutHowThingsWork
AHOWTOdocumentexplainsindetailhowtodosomethingrelatedtoLinuxfromsettingupaspecialized
pieceofhardwaretoperformingasystemadministrationtasktosettingupspecificnetworkingsoftware.
Mini-HOWTOsoffershorterexplanations.AswithLinuxsoftware,onepersonorafewpeoplegenerally
areresponsibleforaHOWTOdocument,yetmanypeoplecontributetoit.
TheLinuxDocumentationProject(LDP,page35)sitehousesmostHOWTOandmini-HOWTO
documents.Useabrowsertogotowww.tldp.org,clickHOWTOs,andpicktheindexyouwanttouseto
findaHOWTOormini-HOWTO.OrusetheLDPsearchfeatureonitshomepagetofindHOWTOsand
more.
UsingtheInternettoGetHelp
TheInternetprovidesmanyhelpfulsitesrelatedtoLinux.Asidefromsitesthatcarryvariousformsof
documentation,youcanenteranerrormessagethatyouarehavingaproblemwithinasearchenginesuch
asGoogle(www.google.com).Enclosetheerrormessagewithindoublequotationmarkstoimprovethe
qualityofyourresults.Youwilllikelyfindapostconcerningyourproblemandhowtosolveit.See
Figure2-5.

Figure2-5.Googlereportingonanerrormessage
[Viewfullsizeimage]
GNU
GNUmakesmanyofitsmanualsavailableatwww.gnu.org/manual.Inaddition,gototheGNUhomepage
(www.gnu.org)formoredocumentationandotherGNUresources.ManyoftheGNUpagesandresources
areavailableinawidevarietyoflanguages.
TheLinuxDocumentationProject
TheLinuxDocumentationProject(www.tldp.org),whichhasbeenaroundforalmostaslongasLinux,
housesacompletecollectionofguides,HOWTOs,FAQs,manpages,andLinuxmagazines.Thehome
pageisavailableinEnglish,Portuguese,Spanish,Italian,Korean,andFrenchandiseasytouse,
supportinglocaltextsearches.Italsohasacompletesetoflinks(Figure2-6)thatcanhelpyoufind
almostanythingyouwantthatisrelatedtoLinux(clickLinksintheSearchboxorgoto
www.tldp.org/links).Thelinkspageincludessectionsongeneralinformation,events,gettingstarted,user
groups,mailinglists,andnewsgroups,eachcontainingmanysubsections.
Figure2-6.TheLinuxDocumentationProjecthomepage

[Viewfullsizeimage]

MoreAboutLoggingIn
Thissectioncoverswhattodoifyouhaveaproblemloggingin,howtousevirtualconsoles,howtolog
inremotely,andhowtochangeyourpassword.
WhattoDoIfYouCannotLogIn
Whenyouenteryourusernameorpasswordincorrectly,thesystemdisplaysanerrormessageafteryou
enterbothyourusernameandyourpassword.Thismessageindicatesthatyouhaveenteredeitherthe
loginnameorthepasswordincorrectlyorthattheyarenotvalid.Itdoesnotdifferentiatebetweenan
unacceptableloginnameandanunacceptablepasswordtodiscourageunauthorizedpeoplefromguessing
namesandpasswordstogainaccesstothesystem.Somecommonreasonsthatloginsfailarelistedhere:
LogInontheRightMachine
Thelogin/passwordcombinationmaynotbevalidifyouaretryingtologinonthewrongmachine.
Onalarger,networkedsystem,youmayhavetospecifythemachinethatyouwanttoconnectto
beforeyoucanlogin.
LoginNameandPasswordAreCaseSensitive
MakesuretheCAPSLOCKkeyisoffandthatyouenteryournameandpasswordexactlyas
specifiedorasyousetthemup.
MakeSureYourLoginNameIsValid
Thelogin/passwordcombinationmaynotbevalidifyouhavenotbeensetupasauser.
Referto"ChangingYourPassword"onpage37whenyouwanttochangeyourpassword.
LoggingOut
Tologoutfromacharacter-basedinterface,pressCONTROL-Dorgivethecommandexitinresponseto
theshellprompt.
UsingVirtualConsoles
WhenrunningLinuxonapersonalcomputer,youfrequentlyworkwiththedisplayandkeyboardattached
tothecomputer.Usingthisphysicalconsole,youcanaccessasmanyas63virtualconsoles(alsocalled
virtualterminals).Somearesetuptoallowlogins,whereasothersactasgraphicaldisplays.Toswitch
betweenvirtualconsoles,holddowntheCONTROLandALTkeysandpressthefunctionkeythat
correspondstotheconsoleyouwanttoview.Forexample,CONTROL-ALT-F5displaysthefifthvirtual
console.Thisbookreferstotheconsolethatyouseewhenyoufirstbootasystem(orpressCONTROL-
ALT-F1)asthesystemconsole(orjustconsole).
Typically,sixvirtualconsolesareactiveandhavetextloginsessionsrunning.Whenyouwanttouseboth
acharacter-basedinterfaceandaGUI,youcansetupacharacter-basedsessionononevirtualconsole
andagraphicalsessiononanother.Whichevervirtualconsoleyoustartagraphicalsessionfrom,the
graphicalsessionfindsthefirstunusedvirtualconsole(typicallynumberseven).
ChangingYourPassword
Ifsomeoneelseassignedyouapassword,itisagoodideatogiveyourselfanewone.Agoodpassword
issevenoreightcharacterslongandcontainsacombinationofnumbers,uppercaseandlowercaseletters,
andpunctuationcharacters.Avoidusingcontrolcharacters(suchasCONTROL-H)becausetheymay
haveaspecialmeaningtothesystem,makingitimpossibleforyoutologin.Donotusenames,words
fromEnglishorotherlanguages,orotherfamiliarwordsthatsomeonecaneasilyguess.
Forsecurityreasonsnoneofthepasswordsyouenteriseverdisplayedbyanyutility.
security:Protectyourpassword
Donotallowsomeonetofindoutyourpassword:Donotputyourpasswordinafilethatis
notencrypted,allowsomeonetowatchyoutypeyourpassword,giveittosomeoneyoudo
notknow(asystemadministratorneverneedstoknowyourpassword),orwriteitdown.
security:Chooseapasswordthatisdifficulttoguess
Donotusephonenumbers,namesofpetsorkids,birthdays,wordsfromadictionary(not
evenaforeignlanguage),andsoforth.Donotusepermutationsoftheseitems.
security:Differentiatebetweenimportantandlessimportantpasswords
Itisimportanttodifferentiatebetweenimportantandlessimportantpasswords.For
example,Websitepasswordsforblogsordownloadaccessarenotveryimportant;itisnot
badifyouchoosethesamepasswordforthesetypesofsites.However,yourlogin,mail

server,andbankaccountWebsitepasswordsarecritical:Neverusethesepasswordsfor
anunimportantWebsite.
Tochangeyourpassword,givethecommandpasswdfromacommandline:
$passwd
Changingpasswordforuserzach.
Changingpasswordforzach
(current)UNIXpassword:
NewUNIXpassword:
RetypenewUNIXpassword:
passwd:allauthenticationtokensupdatedsuccessfully.
Thefirstitemthesystemasksyouforisyourcurrent(old)password.Thispasswordisverifiedtoensure
thatanunauthorizeduserisnottryingtoalteryourpassword.Nextthesystemrequeststhenewpassword.
Apasswordshouldmeetthefollowingcriteriatoberelativelysecure.Onlythefirstitemismandatory.
Itmustbeatleastsixcharacterslong(orlongerifthesystemadministratorsetsitupthatway).
Itshouldnotbeawordinadictionaryofanylanguage,nomatterhowseeminglyobscure.
Itshouldnotbethenameofaperson,place,pet,orotherthingthatmightbediscoveredeasily.
Itshouldcontainatleasttwolettersandonedigit.
Itshouldnotbeyourloginname,thereverseofyourloginname,oryourloginnameshiftedbyoneor
morecharacters.
Ifyouarechangingyourpassword,thenewpasswordshoulddifferfromtheoldonebyatleastthree
characters.Changingthecaseofacharacterdoesnotmakeitcountasadifferentcharacter.
Afteryouenteryournewpassword,thesystemasksyoutoretypeittomakesureyoudidnotmakea
mistakewhenyouentereditthefirsttime.Ifthenewpasswordisthesamebothtimesyouenterit,your
passwordischanged.Ifthepasswordsdiffer,itmeansthatyoumadeanerrorinoneofthem,andthe
systemdisplaysanerrormessage:
Sorry,passwordsdonotmatch
Ifyourpasswordisnotlongenough,thesystemdisplaysthefollowingmessage:
BADPASSWORD:itistooshort
Whenitistoosimple,thesystemdisplaysthismessage:
BADPASSWORD:itistoosimplistic/systematic
Whenitisformedfromwords,thesystemdisplaysthismessage:
BADPASSWORD:itisbasedonadictionaryword
Ifyougetoneofthesemessagesyouneedtostartover.PressRETURNafewtimesuntiltheshell
displaysapromptandrunpasswdagain.
Whenyousuccessfullychangeyourpassword,youchangethewayyoulogin.Ifyouforgetyour
password,Superusercanchangeitandtellyouyournewpassword.
ChapterSummary
Aswithmanyoperatingsystems,youraccesstoaLinuxsystemisauthorizedwhenyoulogin.Youenter
yourusernameinresponsetothelogin:prompt,followedbyapassword.Youcanchangeyourpassword
anytimewhileyouareloggedin.Chooseapasswordthatisdifficulttoguessandthatconformstothe
criteriaimposedbytheutilitythatchangesyourpassword.
Thesystemadministratorisresponsibleformaintainingthesystem.Onasingle-usersystem,youarethe
systemadministrator.Onasmall,multiusersystem,youoranotheruseractasthesystemadministrator,or
thisjobmaybeshared.Onalarge,multiusersystemornetworkofsystems,thereisfrequentlyafull-time
systemadministrator.Whenextraprivilegesarerequiredtoperformcertainsystemtasks,thesystem
administratorlogsinastherootuserbyenteringtheusernamerootandtherootpassword;thisuseris
calledSuperuseroradministrator.Onamultiusersystem,severaltrustedusersmaybegiventheroot
password.
DonotworkasSuperuserasamatterofcourse.WhenyouhavetodosomethingthatrequiresSuperuser
privileges,workasSuperuserforonlyaslongasyouneedto;thenreverttoworkingasyourselfassoon
aspossible.
Themanutilityprovidesonlinedocumentationonsystemutilities.Thisutilityishelpfulbothtonew
Linuxusersandtoexperienceduserswhomustoftendelveintothesystemdocumentationforinformation
onthefinepointsofautility'sbehavior.Theinfoutilityhelpsthebeginnerandtheexpertalike.It
includesatutorialonitsuseanddocumentationonmanyLinuxutilities.
Exercises
1.
Thefollowingmessageisdisplayedwhenyouattempttologinwithanincorrectusernameoranincorrectpassword:
Loginincorrect
Thismessagedoesnotindicatewhetheryourusername,yourpassword,orbothareinvalid.Whydoesitnottellyouthisinformation?
2. Givethreeexamplesofpoorpasswordchoices.Whatiswrongwitheach?Includeonethatistooshort.Givetheerrormessagethe
systemdisplays.
3. Isfidoanacceptablepassword?Giveseveralreasonswhyorwhynot.
4. Whatwouldyoudoifyoucouldnotlogin?
5. Trytochangeyourpasswordtodog.Whathappens?Changeittoamoresecurepassword.Whatmakesthatpasswordrelatively
secure?
AdvancedExercises
6. Changeyourloginshelltotcshwithoutbecomingroot(Superuser).
7. HowmanymanpagesareintheDevicessubsectionofthesystemmanual?(Hint:DevicesisasubsectionofSpecialFiles.)
8. Theexampleonpage31showsthatmanpagesforwriteappearinsections1and2ofthesystemmanual.Explainhowyoucanuse
mantodeterminewhichsectionsofthesystemmanualcontainamanualpagewithagivenname.
9. HowwouldyoufindoutwhichLinuxutilitiescreateandworkwitharchivefiles?
Chapter3.CommandLineUtilities
INTHISCHAPTER
SpecialCharacters42
BasicUtilities43
lessIsmore:DisplayingaTextFileOneScreenataTime45
WorkingwithFiles45
lpr:PrintsaFile47
|(Pipe):CommunicatesBetweenProcesses52
CompressingandArchivingFiles56
ObtainingUserandSystemInformation63
WhenLinusTorvaldsintroducedLinuxandforalongtimethereafter,Linuxdidnothaveagraphicaluser
interface:Itranoncharacter-basedterminalsonly.Allthetoolsranfromacommandline.Todaythe
LinuxGUIisimportant,butmanypeopleespeciallysystemadministratorsrunmanycommandline
programs.Commandlineutilitiesareoftenfaster,morepowerful,ormorecompletethantheirGUI
counterparts.SometimesthereisnoGUIcounterparttoatext-basedutility;somepeoplejustpreferthe
hands-onfeelingofthecommandline.
Whenyouworkwithacommandlineinterface,youareworkingwithashell.Beforeyoustartworking
withashell,itisimportanttounderstandsomethingaboutthecharactersthatarespecialtotheshell,so
thischapterstartswithadiscussionofshellspecialcharacters.Thechapterthendescribesfourbasic
utilitiesyoucanusetocreateandmanipulatefiles(ls,cat,rm,andless)andoneutilitythattellsyou
thenameofthesystemyouareusing(hostname).Itcontinueswithasectiononadditionalfile
manipulationutilities(includinglpr,whichprintsfiles),followedbyabriefdiscussionofhowyoucan
useapipeonthecommandline.Thischapterthendescribesutilitiesthatcompressanddecompressfiles,
locateotherutilities,obtainuserandsysteminformation,andallowyoutocommunicatewithotherusers.
Itconcludeswithasectiononemail.
tip:Runtheseutilitiesfromacommandline
Thischapterdescribescommandline(i.e.,text-based)utilities.Youcanexperimentwith
theseutilitiesfromaterminal,aterminalemulatorwithinaGUI,oravirtualconsole(page
36).
SpecialCharacters
Specialcharacters,whichhaveaspecialmeaningtotheshell,arediscussedin"Filename
Generation/PathnameExpansion"onpage127.Thesecharactersarementionedheresothatyoucanavoid
accidentallyusingthemasregularcharactersuntilyouunderstandhowtheshellinterpretsthem.For
example,itisbesttoavoidusinganyofthefollowingcharactersinafilename(eventhoughemacsand
someotherprogramsdo)becausetheymakethefilehardertoreferenceonthecommandline:
&;|*?'"'[]()$<>{}^#/\%!~+
Whitespace
Althoughnotconsideredspecialcharacters,RETURN,SPACE,andTABalsohavespecialmeaningsto
theshell.RETURNusuallyendsacommandlineandinitiatesexecutionofacommand.TheSPACEand
TABcharactersseparateelementsonthecommandlineandarecollectivelyknownaswhitespaceor
blanks.
Ifyouneedtouseoneofthecharactersthathasaspecialmeaningtotheshellasaregularcharacter,you
canquote(orescape)it.Whenyouquoteaspecialcharacter,youkeeptheshellfromgivingitspecial
meaning.Theshelltreatsaquotedspecialcharacterasaregularcharacter.
Backslash
Toquoteacharacter,precedeitwithabackslash(\).Whenyouhavetwoormorespecialcharacters
together,youmustprecedeeachwithabackslash(forexample,enter**as\*\*).Youcanquotea
backslashjustasyouwouldquoteanyotherspecialcharacterbyprecedingitwithabackslash(\\).
Singlequotationmarks
Anotherwayofquotingspecialcharactersistoenclosethembetweensinglequotationmarks:'**'.You
canquotemanyspecialandregularcharactersbetweenapairofsinglequotationmarks:'Thisisaspecial
character:>'.Theregularcharactersremainregular,andtheshellalsointerpretsthespecialcharacters
asregularcharacters.
Theonlywaytoquotetheerasecharacter(CONTROL-H),thelinekillcharacter(CONTROL-U),and
othercontrolcharacters(tryCONTROL-M)isbyprecedingitwithaCONTROL-V.Singlequotation
marksandbackslashesdonotwork.Trythefollowing:
$echo'xxxxxxCONTROL-U'
$echoxxxxxxCONTROL-VCONTROL-U

optional
AlthoughyoucannotseetheCONTROL-Udisplayedbythesecondoftheprecedingpairofcommands,itisthere.Thefollowing
commandsendstheoutputofecho(page647)throughapipe(page52)tood(page737)todisplaytheCONTROL-Uasanoctal
25(025):
$echoxxxxxxCONTROL-VCONTROL-U|od-c
0000000xxxxxx025\n
0000010
The\nistheNEWLINEcharacterthatechosendsattheendofitsoutput.
BasicUtilities
OneoftheimportantadvantagesofLinuxisthatitcomeswiththousandsofutilitiesthatperformmyriad
functions.YouwilluseutilitieswheneveryouuseLinux,whetheryouusethemdirectlybynamefromthe
commandlineorindirectlyfromamenuoricon.Thefollowingsectionsdiscusssomeofthemostbasic
andimportantutilities;theseutilitiesareavailablefromacharacter-basedinterface.Someofthemore
importantutilitiesarealsoavailablefromaGUI,andsomeareavailableonlyfromaGUI.
Thetermdirectoryisusedextensivelyinthenextsections.Adirectoryisaresourcethatcanholdfiles.
Onotheroperatingsystems,includingWindows,Macintosh,andfrequentlyLinuxGUIs,adirectoryis
referredtoasafolder.Thatisagoodanalogy:Adirectoryisafolderthatcanholdfiles.
tip:Inthischapteryouworkinyourhomedirectory
Whenyouloginonthesystem,youareworkinginyourhomedirectory.Inthischapterthat
istheonlydirectoryyouuse:Allthefilesyoucreateinthischapterareinyourhome
directory.Chapter4goesintomoredetailaboutdirectories.
ls:ListstheNamesofFiles
Usingtheeditorofyourchoice,createasmallfilenamedpractice.(Atutorialonvimappearsonpage
141andatutorialonemacsappearsonpage198.)Afterexitingfromtheeditor,youcanusethels(list)
utilitytodisplayalistofthenamesofthefilesinyourhomedirectory.InthefirstcommandinFigure3-1
lsliststhenameofthepracticefile.(Youmayalsoseefilesthesystemoraprogramcreated
automatically.)SubsequentcommandsinFigure3-1displaythecontentsofthefileandremovethefile.
Thesecommandsaredescribednext.
Figure3-1.Usingls,cat,andrmonthefilenamedpractice
$ls
practice
$catpractice
ThisisasmallfilethatIcreated
withatexteditor.
$rmpractice
$ls
$catpractice
cat:practice:Nosuchfileordirectory
$
cat:DisplaysaTextFile
Thecatutilitydisplaysthecontentsofatextfile.Thenameofthecommandisderivedfromcatenate,
whichmeanstojointogether,oneaftertheother.(Figure5-8onpage118showshowtousecattostring
togetherthecontentsofthreefiles.)
Aconvenientwaytodisplaythecontentsofafiletothescreenisbygivingthecommandcat,followedby
aSPACEandthenameofafile.Figure3-1showscatdisplayingthecontentsofpractice.Thisfigure
showsthedifferencebetweenthelsandcatutilities:Thelsutilitydisplaysthenameofafile,
whereascatdisplaysthecontentsofafile.
rm:DeletesaFile
Therm(remove)utilitydeletesafile.Figure3-1showsrmdeletingthefilenamedpractice.Afterrm
deletesthefile,lsandcatshowthatpracticeisnolongerinthedirectory.Thelsutilitydoesnotlist
itsfilename,andcatsaysthatthereisnosuchfile.Usermcarefully.
tip:Asaferwayofremovingfiles
Youcanusetheinteractiveformofrmtomakesurethatyoudeleteonlythefile(s)you
intendtodelete.Whenyoufollowrmwiththeioption(seepage31foratiponoptions)
andthenameofthefileyouwanttodelete,rmdisplaysthenameofthefileandthenwaits
foryoutorespondwithy(yes)beforeitdeletesthefile.Itdoesnotdeletethefileifyou
respondwithastringthatdoesnotbeginwithy.
$rm-itoollist
rm:removeregularfile'toollist'?y
Optional:Youcancreateanalias(page312)andputitinyourstartupfile(page83)sothat
rmalwaysrunsininteractivemode.
lessIsmore:DisplayingaTextFileOneScreenataTime
Pagers
Whenyouwanttoviewafilethatislongerthanonescreen,youcanuseeitherthelessutilityorthe
moreutility.Eachoftheseutilitiespausesafterdisplayingascreenoftext.Becausetheseutilitiesshow
onepageatatime,theyarecalledpagers.Althoughtheyareverysimilar,theyhavesubtledifferences.At
theendofthefile,forexample,lessdisplaysanEOF(endoffile)messageandwaitsforyoutopressq
beforereturningyoutotheshell.Incontrast,morereturnsyoudirectlytotheshell.Inbothutilitiesyou
canpresshtodisplayahelpscreenthatlistscommandsyoucanusewhilepagingthroughafile.Replace
thecatcommandinFigure3-1withlesspracticeandmorepracticetoseehowthesecommandswork.
Usethecommandless/etc/termcapifyouwanttoexperimentwithalongfile.Refertopage697for
moreinformationonless.
tip:Filenamecompletion
Afteryouenteroneormorelettersofafilename(followingacommand)onacommand
line,pressTABandtheshellwillcompleteasmuchofthefilenameasitcan.Whenonly
onefilenamestartswiththecharactersyouentered,theshellcompletesthefilenameand
placesaSPACEafterit.YoucankeeptypingoryoucanpressRETURNtoexecutethe
commandatthispoint.Whenthecharactersyouentereddonotuniquelyidentifyafilename,
theshellcompleteswhatitcanandwaitsformoreinput.WhenpressingTABdoesnot
changethedisplay,pressTABagaintodisplayalistofpossiblecompletions.(Referto
"PathnameCompletion"onpage308.)
Theprecedingdescriptionassumesyouarerunningbash.Filenamecompletionworksa
littledifferentlyifyouarerunningtcsh;see"WordCompletion"onpage350.
hostname:DisplaystheSystemName
Thehostnamecommanddisplaysthenameofthesystemyouareworkingon.Usethiscommandifyou
arenotsurethatyouareloggedinontherightsystem.
$hostname
bravo.example.com
WorkingwithFiles
Thefollowingsectionsdescribeutilitiesthatcopy,move,andprintfiles.
cp:CopiesaFile
Thecp(copy)utility(Figure3-2)makesacopyofafile.Thisutilitycancopyanyfile,includingtextand
executableprogram(binary)files.Youcanusecptomakeabackupcopyofafileoracopyto
experimentwith.
Thecpcommandlineusesthefollowingsyntaxtospecifysourceanddestinationfiles:
cpsource-filedestination-file
Thesource-fileisthenameofthefilethatcpwillcopy.Thedestination-fileisthenamethatcpassigns
totheresulting(new)copyofthefile.
caution:cpcandestroyafile
Ifthedestination-fileexistsbeforeyougiveacpcommand,cpoverwritesit.Becausecp
overwrites(anddestroysthecontentsof)anexistingdestination-filewithoutwarning,take
carenottocausecptooverwriteafilethatyouneed.Thecpi(interactive)option(see
page31foratiponoptions)promptsyoubeforeitoverwritesafile.
Thefollowingexampleassumesthatthefilenamedorange.2existsbeforeyougivethecp
command.Theuseranswersytooverwritethefile:
$cpiorangeorange.2
cp:overwrite'orange.2'?y
ThecpcommandlineinFigure3-2copiesthefilenamedmemotomemo.copy.Theperiodispartofthe
filenamejustanothercharacter.Theinitiallscommandshowsthatmemoistheonlyfileinthedirectory.
Afterthecpcommand,asecondlsshowstwofilesinthedirectory,memoandmemo.copy.
Sometimesitisusefultoincorporatethedateinthenameofacopyofafile.Thefollowingexample
includesthedateJanuary30(0130)inthecopiedfile:
$cpmemomemo.0130
AlthoughithasnosignificancetoLinux,thedatecanhelpyoufindaversionofafilethatyoucreatedona
certaindate.Itcanalsohelpyouavoidoverwritingexistingfilesbyprovidingauniquefilenameeach
day.Referto"Filenames"onpage78.
Usescp(page758)orftp(page671)whenyouneedtocopyafilefromonesystemtoanotherona
commonnetwork.
mv:ChangestheNameofaFile
Themv(move)utilitycanrenameafilewithoutmakingacopyofit.Themvcommandlinespecifiesan
existingfileandanewfilenameusingthesamesyntaxascp:
mvexisting-filenamenew-filename
Figure3-2.cpcopiesafile
$ls
memo
$cpmemomemo.copy
$ls
memomemo.copy
Figure3-3.mvrenamesafile
$ls
memo
$mvmemomemo.0130
$ls
memo.0130
ThecommandlineinFigure3-3changesthenameofthefilememotomemo.0130.Theinitialls
commandshowsthatmemoistheonlyfileinthedirectory.Afteryougivethemvcommand,memo.0130
istheonlyfileinthedirectory.Comparethisresulttothatoftheearliercpexample.
Themvutilitycanbeusedformorethanchangingthenameofafile.Referto"mv,cp:MovesorCopiesa
File"onpage90.
caution:mvcandestroyafile
Justascpcandestroyafile,socanmv.Alsolikecp,mvhasai(interactive)option.See
thecautionboxlabeled"cpcandestroyafile"onpage46.
lpr:PrintsaFile
Thelpr(lineprinter)utilityplacesoneormorefilesinaprintqueueforprinting.Linuxprovidesprint
queuessothatonlyonejobisprintedonagivenprinteratatime.Aqueueallowsseveralpeopleorjobs
tosendoutputsimultaneouslytoasingleprinterwiththeexpectedresults.Onmachineswithaccessto
morethanoneprinter,youcanusethePoptiontoinstructlprtoplacethefileinthequeueforaspecific
printer,includingonethatisconnectedtoanothermachineonthenetwork.Thefollowingcommandprints
thefilenamedreport:
$lprreport
Becausethiscommanddoesnotspecifyaprinter,theoutputgoestothedefaultprinter,whichisthe
printerwhenyouhaveonlyoneprinter.
Thenextcommandlineprintsthesamefileontheprinternamedmailroom:
$lpr-Pmailroomreport
Youcanseewhatjobsareintheprintqueuebyusingthelpqutility:
$lpq
lpisreadyandprinting
RankOwnerJobFilesTotalSize
activealex86(standardinput)954061bytes
Inthisexample,Alexhasonejobthatisbeingprinted;nootherjobsareinthequeue.Youcanusethejob
number(86inthiscase)withthelprmutilitytoremovethejobfromtheprintqueueandstopitfrom
printing:
$lprm86
Youcansendmorethanonefiletotheprinterwithasinglecommand.Thefollowingcommandlineprints
threefilesontheprinternamedlaser1:
$lpr-Plaser105.txt108.txt12.txt
grep:FindsaString
Thegrep(globalregularexpressionprint[1])utilitysearchesthroughoneormorefilestoseewhether
anycontainaspecifiedstringofcharacters.Itdoesnotchangethefileitsearchesbutsimplydisplayseach
linethatcontainsthestring.
[1]Originallythisutility'snamewasaplayonanedanoriginalUNIXeditor,availableonLinuxcommand:g/re/p.Inthiscommandthe
gstandsforglobal,reisaregularexpressiondelimitedbyslashes,andpmeansprint.
ThegrepcommandinFigure3-4searchesthroughthefilememoforlinesthatcontainthestringcredit
anddisplaysasinglelinethatmeetsthiscriterion.Ifmemocontainedsuchwordsasdiscredit,creditor,
oraccreditation,grepwouldhavedisplayedthoselinesaswellbecausetheycontainthestringitwas
searchingfor.Thewoptioncausesgreptomatchonlywholewords.Youdonotneedtoenclosethe
stringyouaresearchingforinsinglequotationmarks,butdoingsoallowsyoutoputSPACEsandspecial
charactersinthesearchstring.
Thegreputilitycandomuchmorethansearchforasimplestringinasinglefile.Refertopage683for
moreinformationongrep.
Figure3-4.grepsearchesforastring
$catmemo
Helen:
InourmeetingonJune6we
discussedtheissueofcredit.
Haveyouhadanyfurtherthoughts
aboutit?
Alex
$grep'credit'memo
discussedtheissueofcredit.
head:DisplaystheBeginningofaFile
Bydefaulttheheadutilitydisplaysthefirsttenlinesofafile.Youcanuseheadtohelpyouremember
whataparticularfilecontains.Forexample,ifyouhaveafilenamedmonthsthatliststhe12monthsof
theyearinorder,onetoaline,headdisplaysJanthroughOct(Figure3-5).
Thisutilitycandisplayanynumberoflines,soyoucanuseittolookatonlythefirstlineofafile,atafull
screen,orevenmore.Tospecifythenumberoflinesheaddisplays,includeahyphenfollowedbythe
numberoflinesintheheadcommand.Forexample,thefollowingcommanddisplaysonlythefirstline
ofmonths:
$head-1months
Jan
Theheadutilitycanalsodisplaypartsofafilebasedonacountofblocksorcharactersratherthanlines.
Refertopage691formoreinformationonhead.
tail:DisplaystheEndofaFile
Thetailutilityissimilartoheadbutbydefaultdisplaysthelasttenlinesofafile.Dependingonhow
youinvokeit,thisutilitycandisplayfewerormorethantenlines,useacountofblocksorcharacters
ratherthanlinestodisplaypartsofafile,anddisplaylinesbeingaddedtoafilethatischanging.The
followingcommandcausestailtodisplaythelastfivelines,AugthroughDec,ofthemonthsfile
showninFigure3-5:
Figure3-5.headdisplaysthefirstlinesofafile
$catmonths
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
$headmonths
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Figure3-6.sortdisplaysafileinorder
$catdays
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
$sortdays
Friday
Monday
Saturday
Sunday
Thursday
Tuesday
Wednesday
$tail-5months
Aug
Sep
Oct
Nov
Dec
Youcanmonitorlinesastheyareaddedtotheendofthegrowingfilenamedlogfilewiththefollowing
command:
$tail-flogfile
Presstheinterruptkey(usuallyCONTROL-C)tostoptailanddisplaytheshellprompt.Refertopage
783formoreinformationontail.
sort:DisplaysaFileinOrder
Thesortutilitydisplaysthecontentsofafileinorderbylinesbutdoesnotchangetheoriginalfile.If
youhaveafilenameddaysthatcontainsthenameofeachdayoftheweekinorderonaseparateline,
sortdisplaysthefileinalphabeticalorder(Figure3-6).
Thesortutilityisusefulforputtinglistsinorder.Theuoptiongeneratesasortedlistinwhicheachline
isunique(noduplicates).Thenoptionputsalistofnumbersinorder.Refertopage762formore
informationonsort.
Figure3-7.uniqremovesduplicatelines
$catdups
Cathy
Fred
Joe
John
Mary
Mary
Paula
$uniqdups
Cathy
Fred
Joe
John
Mary
Paula
uniq:RemovesDuplicateLinesfromaFile
Theuniq(unique)utilitydisplaysafile,skippingadjacentduplicatelines,butdoesnotchangethe
originalfile.Ifafilecontainsalistofnamesandhastwosuccessiveentriesforthesameperson,uniq
skipstheextraline(Figure3-7).
Ifafileissortedbeforeitisprocessedbyuniq,thisutilityensuresthatnotwolinesinthefilearethe
same.(Ofcourse,sortcandothatallbyitselfwiththeuoption.)Refertopage812formore
informationonuniq.
diff:ComparesTwoFiles
Thediff(difference)utilitycomparestwofilesanddisplaysalistofthedifferencesbetweenthem.
Thisutilitydoesnotchangeeitherfile,soitisusefulwhenyouwanttocomparetwoversionsofaletter
orareportortwoversionsofthesourcecodeforaprogram.
Thediffutilitywiththeu(unifiedoutputformat)optionfirstdisplaystwolinesindicatingwhichofthe
filesyouarecomparingwillbedenotedbyaplussign(+)andwhichbyaminussign().InFigure3-8,a
minussignindicatesthecolors.1file;aplussignindicatesthecolors.2file.
Thediffucommandbreakslong,multilinetextintohunks.Eachhunkisprecededbyalinestartingand
endingwithtwoatsigns(@@).Thishunkidentifierindicatesthestartinglinenumberandthenumberof
linesfromeachfileforthishunk.InFigure3-8,the1,6indicatesthatthehunkcoversthesectionofthe
colors.1file(indicatedbyaminussign)fromthefirstlineandcontinuingforsixlines(foratotalofseven
lines).Similarlythe+1,5indicatesthatthehunkcoverscolors.2fromthefirstlinethroughfivesubsequent
lines.
Figure3-8.diffdisplayingtheunifiedoutputformat
$diff-ucolors.1colors.2
---colors.1FriNov2515:45:322005
+++colors.2FriNov2515:24:462005
@@-1,6+1,5@@
red
+blue
green
yellow
-pink
-purple
orange
Followingtheseheaderlines,diffudisplayseachlineoftextwithaleadingminussign,plussign,or
nothing.Theleadingminussignindicatesthatthelineoccursonlyinthefiledenotedbytheminussign.
Theleadingplussignindicatesthatthelinecomesfromthefiledenotedbytheplussign.Alinethat
beginswithneitheraplussignnoraminussignoccursinbothfilesinthesamelocation.Refertopage
638formoreinformationondiff.
file:TeststheContentsofaFile
YoucanusethefileutilitytolearnaboutthecontentsofanyfileonaLinuxsystemwithouthavingto
openandexaminethefileyourself.Inthefollowingexample,filereportsthatletter_e.bz2contains
datathatwascompressedbythebzip2utility(page56):
$fileletter_e.bz2
letter_e.bz2:bzip2compresseddata,blocksize=900k
Nextfilereportsontwomorefiles:
$filememozach.jpg
memo:ASCIItext
zach.jpg:JPEGimagedata,...resolution(DPI),72x72
Refertopage653formoreinformationonfile.
|(Pipe):CommunicatesBetweenProcesses
BecausepipesareintegraltothefunctioningofaLinuxsystem,theyareintroducedhereforusein
examples.Pipesarecoveredindetailonpage122.
AprocessistheexecutionofacommandbyLinux(page292).Communicationbetweenprocessesisone
ofthehallmarksofUNIX/Linux.Apipe(writtenasaverticalbar,|,onthecommandlineandappearingas
asolidorbrokenverticallineonkeyboards)providesthesimplestformofthiskindofcommunication.
Simplyput,apipetakestheoutputofoneutilityandsendsthatoutputasinputtoanotherutility.Using
UNIX/Linuxterminology,apipetakesstandardoutputofoneprocessandredirectsittobecomestandard
inputofanotherprocess.(Seepage113formoreinformationonstandardinputandoutput.)Mostofwhat
aprocessdisplaysonthescreenissenttostandardoutput.Ifyoudonotredirectit,thisoutputappearson
thescreen.Usingapipe,youcanredirecttheoutputsothatitbecomesinsteadstandardinputofanother
utility.Autilitysuchasheadcantakeitsinputfromafilewhosenameyouspecifyonthecommandline
followingthewordhead,oritcantakeitsinputfromstandardinput.Forexample,youcangivethe
commandshowninFigure3-5onpage49asfollows:
$catmonths|head
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Thenextcommanddisplaysthefirstlineofthemonthsfile:
$catmonths|head-1
Jan
Youcanuseapipetosendoutputofaprogramtotheprinter:
$tailmonths|lpr
FourMoreUtilities
TheechoanddateutilitiesaretwoofthemostfrequentlyusedfromthelargecollectionofLinux
utilities.Thescriptutilityhelpsyourecordpartofasessioninafile,andunix2dosmakesacopyof
atextfilethatcanbereadonaWindowsmachine.
echo:DisplaysText
Theechoutilitycopiesanythingyouputonthecommandline,afterecho,tothescreen.Someexamples
areshowninFigure3-9.Thelastexampleshowswhattheshelldoeswithanunquotedasterisk(*)onthe
commandline:Itexpandstheasteriskintoalistoffilenamesinthedirectory.
Figure3-9.echocopiesthecommandline(butnotthewordecho)tothescreen
$ls
memomemo.0714practice
$echoHi
Hi
$echoThisisasentence.
Thisisasentence.
$echostar:*
star:memomemo.0714practice
$
TheechoutilityisagoodtoolforlearningabouttheshellandotherLinuxprograms.Someexampleson
page129useechotoillustratehowspecialcharacters,suchastheasterisk,work.Throughoutthe
chaptersexplainingtheshells,echohelpsexplainhowshellvariablesworkandhowyoucansend
messagesfromshellscriptstothescreen.Refertopage647formoreinformationonecho.
date:DisplaystheTimeandDate
Thedateutilitydisplaysthecurrentdateandtime:
$date
ThuJan2010:24:00PST2005
Thefollowingexampleshowshowyoucanchoosetheformatandselectthecontentsoftheoutputof
date.Refertopage630formoreinformationondate.
$date+"%A%B%d"
ThursdayJanuary20
script:RecordsaLinuxSession
Thescriptutilityrecordsallorpartofaloginsession,includingyourinputandthesystem'sresponses.
Thisutilityisusefulonlyfromcharacter-baseddevices,suchasaterminaloraterminalemulator.Itdoes
captureasessionwithvim;however,becausevimusescontrolcharacterstopositionthecursorand
displaydifferenttypefaces,suchasbold,theoutputwillbedifficulttoreadandmaynotbeuseful.When
youcatafilethathascapturedavimsession,thesessionquicklypassesbeforeyoureyes.
Bydefaultscriptcapturesthesessioninafilenamedtypescript.Touseadifferentfilename,follow
thescriptcommandwithaSPACEandthenewfilename.Toappendtoafile,usetheaoptionafterscript
butbeforethefilename;otherwise,scriptoverwritesanexistingfile.Followingisasessionbeing
recordedbyscript:
$script
Scriptstarted,fileistypescript
$date
ThuJan2010:28:56PST2005
$whoami
alexpts/4Jan822:15
$
$aproposmtools
mtools(1)-utilitiestoaccessDOSdisksinUnix
mtools.conf[mtools](5)-mtoolsconfigurationfiles
mtoolstest(1)-testsanddisplaystheconfiguration
$exit
Scriptdone,fileistypescript
$
Usetheexitcommandtoterminateascriptsession.Youcanviewthefileyoucreatedwithcat,less,
more,oraneditor.Followingisthefilethatwascreatedbytheprecedingscriptcommand:
$cattypescript
ScriptstartedonThuJan2010:28:562005
$date
ThuJan2010:28:56PST2005
$whoami
alexpts/4Jan822:15
$
$aproposmtools
mtools(1)-utilitiestoaccessDOSdisksinUnix
mtools.conf[mtools](5)-mtoolsconfigurationfiles
mtoolstest(1)-testsanddisplaystheconfiguration
$exit
ScriptdoneonThuJan2010:29:582005
$
Ifyouwillbeeditingthefilewithvim,emacs,oranothereditor,youcanusedos2unixtoeliminate
fromthetypescriptfilethe^Mcharactersthatappearattheendsofthelines.
unix2dos:ConvertsLinuxFilestoWindowsFormat
IfyouwanttoshareatextfilethatyoucreatedonaLinuxsystemwithsomeoneonaWindowssystem,you
needtoconvertthefilebeforethepersonontheWindowssystemcanreaditeasily.Theunix2dos
utilityconvertsaLinuxtextfilesothatitcanbereadonaWindowssystem.Givethefollowingcommand
toconvertafilenamedmemo.txt(createdwithatexteditor)toaDOS-formatfile:
$unix2dosmemo.txt
Withoutanyoptionsunix2dosoverwritestheoriginalfile.Youcannowemailthefileasanattachment
tosomeoneonaWindowssystem.
dos2unix
Youcanusethedos2unixutilitytoconvertDOSfilessotheycanbereadonaLinuxsystem:
$dos2unixmemo.txt
Seetheunix2dosanddos2unixmanpagesformoreinformation.
YoucanalsouseTR(page804)tochangeaDOStextfileintoaLinuxtextfile.Inthefollowingexample,
thedoptioncausesTRtoremoveRETURNs(representedby\r)asitmakesacopyofthefile:
$catmemo|tr-d'\r'>memo.txt
Convertingafiletheotherwaywithoutunix2dosisnotaseasy.
CompressingandArchivingFiles
Largefilesusealotofdiskspaceandtakelongerthansmallerfilestotransferfromonesystemtoanother
overanetwork.Ifyoudonotneedtolookatthecontentsofalargefileveryoften,youmaywanttosave
itonaCD,DVD,orothermediumandremoveitfromtheharddisk.Ifyouhaveacontinuingneedforthe
file,retrievingacopyfromaCDmaybeinconvenient.Toreducetheamountofdiskspaceyouuse
withoutremovingthefileentirely,youcancompressthefilewithoutlosinganyoftheinformationitholds.
AlsoyoumayfrequentlydownloadcompressedfilesfromtheInternet.Theutilitiesdescribedinthis
sectioncompressanddecompressfiles.
bzip2:CompressesaFile
Thebzip2utility(sources.redhat.com/bzip2)compressesafilebyanalyzingitandrecodingitmore
efficiently.Thenewversionofthefilelookscompletelydifferent.Infact,becausethenewfilecontains
manynonprintingcharacters,youcannotviewitdirectly.Thebzip2utilityworksparticularlywellon
filesthatcontainalotofrepeatedinformation,suchastextandimagedata,althoughmostimagedatais
alreadyinacompressedformat.
Thefollowingexampleshowsaboringfile.Eachofthe8,000linesofthisfile,namedletter_e,contains
72e'sandaNEWLINEcharacterthatmarkstheendoftheline.Thefileoccupiesmorethanhalfa
megabyteofdiskstorage.
$ls-l
-rw-rw-r--1samsam584000Mar122:31letter_e
Thel(long)optioncauseslstodisplaymoreinformationaboutafile.Hereitshowsthatletter_eis
584,000byteslong.Theverbose(orv)optioncausesbzip2toreporthowmuchitwasabletoreduce
thesizeofthefile.Inthiscase,itshrankthefileby99.99percent:
$bzip2-vletter_e
letter_e:11680.00:1,0.001bits/byte,99.99%saved,584000in,50
out.
$ls-l
-rw-rw-r--1samsam50Mar122:31letter_e.bz2
.bz2filenameextension
Nowthefileisonly50byteslong.Thebzip2utilityalsorenamedthefile,appending.bz2toitsname.
Thisnamingconventionremindsyouthatthefileiscompressed;youwouldnotwanttodisplayorprintit,
forexample,withoutfirstdecompressingit.Thebzip2utilitydoesnotchangethemodificationdate
associatedwiththefile,eventhoughitcompletelychangesthefile'scontents.
Inthefollowing,morerealisticexample,thefilezach.jpgcontainsacomputergraphicsimage:
$ls-l
-rw-r--r--1samsam33287Mar122:40zach.jpg
Thegziputilitycanreducethesizeofthefilebyonly28percentbecausetheimageisalreadyina
compressedformat:
$bzip2-vzach.jpg
zach.jpg:1.391:1,5.749bits/byte,28.13%saved,33287in,23922
out.
$ls-l
-rw-r--r--1samsam23922Mar122:40zach.jpg.bz2
Refertopage596andtheBzip2mini-HOWTO(seepage34forhelpfindingit)formoreinformation.
bunzip2andbzcat:DecompressaFile
Youcanusethebunzip2utilitytorestoreafilethathasbeencompressedwithbzip2:
$bunzip2letter_e.bz2
$ls-l
-rw-rw-r--1samsam584000Mar122:31letter_e
$bunzip2zach.jpg.bz2
$ls-l
-rw-r--r--1samsam33287Mar122:40zach.jpg
Thebzcatutilitydisplaysafilethathasbeencompressedwithbzip2.Theequivalentofcatfor.bz2
files,bzcatdecompressesthecompresseddataanddisplaysthecontentsofthedecompressedfile.Like
cat,bzcatdoesnotchangethesourcefile.Thepipeinthefollowingexampleredirectstheoutputof
zcatsothatinsteadofbeingdisplayedonthescreenitbecomestheinputtohead,whichdisplaysthe
firsttwolinesofthefile:
$bzcatletter_e.bz2|head-2
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
Afterbzcatisrun,thecontentsofletter_e.bzisunchanged;thefileisstillstoredonthediskin
compressedform.
bzip2recover
Thebzip2recoverutilitysupportslimiteddatarecoveryfrommediaerrors.Givethecommand
bzip2recoverfollowedbythenameofthefilefromwhichyouwanttotrytorecoverdata.
gzip:CompressesaFile
gunzipandzcat
Thegzip(GNUzip)utilityisolderandlessefficientthanbzip2.Itsflagsandoperationarevery
similartothoseofbzip2.Afilecompressedbygzipismarkedbya.gzfilenameextension.Linux
storesmanualpagesingzipformattosavediskspace;likewise,filesyoudownloadfromtheInternet
arefrequentlyingzipformat.Usegzip,gunzip,andzcatjustasyouwouldusebzip2,
bunzip2,andbzcat.Refertopage688formoreinformationongzip.
compress
Thecompressutilitycanalsocompressfiles,albeitnotaswellasgzip.Thisutilitymarksafileithas
compressedbyadding.Ztoitsname.
tip:gzipversuszip
Donotconfusegzipandgunzipwiththezipandunziputilities.Theselasttwoare
usedtopackandunpackziparchivescontainingseveralfilescompressedintoasinglefile
thathasbeenimportedfromorisbeingexportedtoWindows.Theziputilityconstructsa
ziparchive,whereasunzipunpacksziparchives.Thezipandunziputilitiesare
compatiblewithPKZIP,aWindowscompressandarchiveprogram.
tar:PacksandUnpacksFiles
Thetarutilityperformsmanyfunctions.Itsnameisshortfortapearchive,asitsoriginalfunctionwasto
createandreadarchiveandbackuptapes.Todayitisusedtocreateasinglefile(calledatarfile)from
multiplefilesordirectoryhierarchiesandtoextractfilesfromatarfile.
Inthefollowingexample,thefirstlsshowstheexistenceandsizesofthefilesg,b,andd.Nexttar
usesc(create),v(verbose),andf(writetoorreadfromafile)options[2]tocreateanarchivenamed
all.tarfromthesefiles.Eachlineoftheoutputfromtarstartswiththeletteratoindicatethatitis
appendingtothearchive.Thisletterisfollowedbythenameofthefiletarisappending.
[2]AlthoughtheoriginalUNIXtardidnotusealeadinghyphentoindicateanoptiononthecommandline,itnowacceptshyphens.
TheGNUtardescribedherewillaccepttarcommandswithorwithoutaleadinghyphen.Thisbookusesthehyphenforconsistency
withmostotherutilities.
Thetarutilitydoesaddoverheadwhenitcreatesanarchive.Thenextcommandshowsthatthearchive
fileall.tarisabout9,700bytes,whereasthesumofthesizesofthethreefilesisabout6,000bytes.This
overheadismoreappreciableonsmallerfiles,suchastheonesinthisexample.
$ls-lgbd
-rw-r--r--1jennyjenny1302Aug2014:16g
-rw-r--r--1jennyother1178Aug2014:16b
-rw-r--r--1jennyjenny3783Aug2014:17d
$tar-cvfall.targbd
ag
ab
ad
$ls-lall.tar
-rw-r--r--1jennyjenny9728Aug2014:17all.tar
$tar-tvfall.tar
-rw-r--r--jenny/jenny13022003-08-2014:162005g
-rw-r--r--jenny/other11782003-08-2014:162005b
-rw-r--r--jenny/jenny37832003-08-2014:172005d
Thefinalcommandintheprecedingexampleusesthetoptiontodisplayatableofcontentsforthe
archive.Usexinsteadofttoextractfilesfromatararchive.Omitthevoptionifyouwanttartodo
itsworksilently.
Youcanusebzip2,compress,orgziptocompresstarfilesandmakethemeasiertostoreand
handle.ManyfilesyoudownloadfromtheInternetareinoneoftheseformats.Filesthathavebeen
processedbytarandcompressedbybzip2frequentlyhaveafilenameextensionof.tar.bz2.Those
processedbytarandgziphaveanextensionof.tzor.tar.gz,whilefilesprocessedbytarand
compressuse.tar.Zastheextension.
Youcanunpackatarredandgzippedfileintwosteps.(Followthesameprocedureifthefilewas
compressedbybzip2,butusebunzip2insteadofgunzip.)Thenextexampleshowshowtounpack
theGNUmakeutilityafterithasbeendownloaded(ftp.gnu.org/pub/gnu/make/make-3.80.tar.gz):
$ls-lmak*
-rw-rw-r--1samsam1211924Jan2011:49make-3.80.tar.gz
$gunzipmak*
$ls-lmak*
-rw-rw-r--1samsam4823040Jan2011:49make-3.80.tar
$tar-xvfmak*
make-3.80/
make-3.80/po/
make-3.80/po/Makefile.in.in
...
make-3.80/tests/run_make_tests.pl
make-3.80/tests/test_driver.pl
Thefirstcommandliststhedownloadedtarredandgzippedfile:make-3.80.tar.gz(about1.2
megabytes).Theasterisk(*)inthefilenamematchesanycharactersinanyfilenames(page129),soyou
endupwithalistoffileswhosenamesbeginwithmak;inthiscasethereisonlyone.Usinganasterisk
savestypingandcanimproveaccuracywithlongfilenames.Thegunzipcommanddecompressesthe
fileandyieldsmake-3.80.tar(no.gzextension),whichisabout4.8megabytes.Thetarcommand
createsthemake-3.80directoryintheworkingdirectoryandunpacksthefilesintoit.
$ls-ldmak*
drwxrwxr-x8samsam4096Oct32002make-3.80
-rw-rw-r--1samsam4823040Jan2011:49make-3.80.tar
$ls-lmake-3.80
total1816
-rw-r--r--1samsam24687Oct32002ABOUT-NLS
-rw-r--r--1samsam1554Jul82002AUTHORS
-rw-r--r--1samsam18043Dec101996COPYING
...
-rw-r--r--1samsam16520Jan212000vmsify.c
-rw-r--r--1samsam16409Aug92002vpath.c
drwxrwxr-x5samsam4096Oct32002w32
AftertarexTRactsthefilesfromthearchive,theworkingdirectorycontainstwofileswhosenames
startwithmak:make-3.80.tarandmake-3.80.Thed(directory)optioncauseslstodisplayonlyfile
anddirectorynames,notthecontentsofdirectoriesasitnormallydoes.Thefinallscommandshowsthe
filesanddirectoriesinthemake-3.80directory.Refertopage786formoreinformationontar.
caution:tar:thexoptionmayextractalotoffiles
Sometararchivescontainmanyfiles.Runtarwiththetoptionandthenameofthetar
filetolistthefilesinthearchivewithoutunpackingthem.Insomecasesyoumaywantto
createanewdirectory(mkdir[page80]),movethetarfileintothatdirectory,and
expanditthere.Thatwaytheunpackedfilesdonotminglewithyourexistingfiles,and
thereisnoconfusion.Thisstrategyalsomakesiteasiertodeletetheextractedfiles.Some
tarfilesautomaticallycreateanewdirectoryandputthefilesintoit.Refertothe
precedingexample.
caution:tar:thexoptioncanoverwritefiles
Thexoptiontotaroverwritesafilethathasthesamefilenameasafileyouare
extracting.Followthesuggestionintheprecedingcautionboxtoavoidoverwritingfiles.

optional
Youcancombinethegunzipandtarcommandsononecommandlinewithapipe(|),whichredirectstheoutputofgunzip
sothatitbecomestheinputtotar:
$gunzip-cmake-3.80.tar.gz|tar-xvf-
Thecoptioncausesgunziptosenditsoutputthroughthepipeinsteadofcreatingafile.Referto"Pipes"(page122),gzip
(page688),andtar(page786)formoreinformationabouthowthiscommandlineworks.
Asimplersolutionistousethezoptiontotar.Thisoptioncausestartocallgunzip(orgzipwhenyouarecreatingan
archive)directlyandsimplifiestheprecedingcommandlineto
$tar-xvzfmake-3.80.tar.gz
Inasimilarmanner,thejoptioncallsbzip2orbunzip2.
LocatingCommands
Thewhereisandaproposutilitieshelpyoufindacommandwhosenameyouhaveforgottenor
whoselocationyoudonotknow.Whentherearemultiplecopiesofautilityorprogram,whichcantell
youwhichcopyyouwillrun.Theslocateutilitysearchesforfilesonthelocalsystem.
whichandwhereis:LocateaUtility
WhenyougiveLinuxacommand,theshellsearchesalistofdirectoriesforaprogramwiththatnameand
runsthefirstoneitfinds.Thislistofdirectoriesiscalledasearchpath.Forinformationonhowto
changethesearchpath,referto"PATH:WheretheShellLooksforPrograms"onpage284.Ifyoudonot
changethesearchpath,theshellsearchesonlyastandardsetofdirectoriesandthenstopssearching.
Otherdirectoriesonthesystemmayalsocontainusefulutilities,however.
which
Thewhichutilitylocatesutilities(commands)bydisplayingthefullpathnametothefilefortheutility.
(Chapter4containsmoreinformationonpathnamesandthestructureoftheLinuxfilesystem.)Thelocal
systemmayincludeseveralcommandsthathavethesamename.Whenyoutypethenameofacommand,
theshellsearchesforthecommandinyoursearchpathandrunsthefirstoneitfinds.Youcanfindout
whichcopyoftheprogramtheshellwillrunbyusingwhich.Inthefollowingexample,whichreports
thelocationofthetarcommand:
$whichtar
/bin/tar
Thewhichutilitycanbehelpfulwhenacommandseemstobeworkinginunexpectedways.Byrunning
which,youmaydiscoverthatyouarerunninganonstandardversionofatooloradifferentonethanyou
expected.(Referto"ImportantStandardDirectoriesandFiles"onpage86foralistofstandardlocations
forexecutablefiles.)Forexample,iftarisnotworkingproperlyandyoufindthatyouarerunning
/usr/local/bin/tarinsteadof/bin/tar,youmightsuspectthatthelocalversionisbroken.
whereis

Thewhereisutilitysearchesforfilesrelatedtoautilitybylookinginstandardlocationsinsteadof
usingyoursearchpath.Forexample,youcanfindthelocationsforfilesrelatedtotar:
$whereistar
tar:/bin/tar/usr/include/tar.h/usr/share/man/man1/tar.1.gz
Inthisexamplewhereisfindsthreereferencestotar:thetarutilityfile,atarheaderfile,andthe
tarmanpage.
caution:which,whereis,andbuiltincommands
Boththewhichandwhereisutilitiesreportonlythenamesforcommandsastheyare
foundondiskanddonotreportshellbuiltins(utilitiesthatarebuiltintoashell;seepage
132).Whenyouusewhereistotrytofindoutwheretheechocommand(whichexists
asbothautilityprogramandashellbuiltin)iskept,yougetthefollowingresult:
$whereisecho
echo:/bin/echo/usr/share/man/man1/echo.1.gz
/usr/share/man/man1p/echo.1p.gz/usr/share
/man/man3/echo.3x.gz
Thewhereisutilitydoesnotdisplaytheechobuiltin.Eventhewhichutilityreports
thewronginformation:
$whichecho
/bin/echo
Underbashyoucanusethetypebuiltin(page487)todeterminewhetheracommandis
abuiltin.
$typeecho
echoisashellbuiltin
tip:whichversuswhereis
Giventhenameofaprogram,whichlooksthroughthedirectoriesinyoursearchpath,in
order,andlocatestheprogram.Ifmorethanoneprogramwiththespecifiednameisinthe
searchpath,whichdisplaysthenameofonlythefirstone(theoneyouwouldrun).
Thewhereisutilitylooksthroughalistofstandarddirectoriesandworksindependently
ofyoursearchpath.Usewhereistolocateabinary(executable)file,anymanualpages,
andsourcecodeforaprogramyouspecify;whereisdisplaysallthefilesitfinds.
apropos:SearchesforaKeyword
Whenyoudonotknowthenameofthecommandyouneedtocarryoutaparticulartask,youcanusea
keywordandtheaproposutilitytosearchforit.(Thewhatisdatabasehastobesetupandregularly
maintainedwithmakewhatisforapropostowork;thistaskistypicallyhandledbycron.Referto
crontabonpage624formoreinformation.)Thisutilitysearchesforthekeywordintheshort
descriptionline(thetopline)ofallofthemanpagesanddisplaysthosethatcontainamatch.Theman
utility,whencalledwiththek(keyword)option,displaysthesameoutputasapropos(itisactuallythe
samecommand).
Thefollowingexampleshowstheoutputofaproposwhenyoucallitwiththewhokeyword.Theoutput
includesthenameofeachcommand,thesectionofthemanualthatcontainsit,andthebriefdescription
fromthetopofthemanpage.Thislistincludestheutilitythatyouneed(who)andidentifiesother,related
toolsthatyoumightfinduseful:
$aproposwho
at.allow[at](5)-determinewhocansubmitjobsviaator
batch
at.deny[at](5)-determinewhocansubmitjobsviaator
batch
jwhois(1)-clientforthewhoisservice
ldapwhoami(1)-LDAPwhoami?tool
w(1)-Showwhoisloggedonandwhattheyare
doing
who(1)-showwhoisloggedon
whoami(1)-printeffectiveuserid
whatis
Thewhatisutilityissimilartoaproposbutfindsonlycompletewordmatchesforthenameofthe
utility.
$whatiswho
who(1)-showwhoisloggedon
slocate:SearchesforaFile
Theslocateutility,asecureversionoflocate,searchesforfilesonthelocalsystem:
$slocatemotd
/lib/security/pam_motd.so

ObtainingUserandSystemInformation
tip:Ifyouarenotonanetwork,skiptherestofthischapter
Ifyouaretheonlyuseronasystemthatisnotconnectedtoanetwork,youmaywanttoskip
therestofthischapter.Ifyouarenotonanetworkbutaresetuptosendandreceiveemail,
read"Email"onpage69.
Thissectioncoversutilitiesthatdisplaywhoisusingthesystem,whatthoseusersaredoing,andhowthe
systemisrunning.Tofindoutwhoisusingthelocalsystem,youcanemployseveralutilitiesthatvaryin
thedetailstheyprovideandtheoptionstheysupport.Theoldestutility,who,producesalistofuserswho
areloggedinonthelocalsystem,thedeviceeachpersonisusing,andthetimethepersonloggedin.
Thewandfingerutilitiesshowmoredetail,suchaseachuser'sfullnameandthecommandlineeach
userisrunning.Youcanusethefingerutilitytoretrieveinformationaboutusersonremotesystemsif
yourcomputerisattachedtoanetwork.Table3-1onpage67summarizestheoutputoftheseutilities.
Figure3-10.wholistswhoisloggedin
$who
rootconsoleMar2705:00
alexpts/4Mar2712:23
alexpts/5Mar2712:33
jennypts/7Mar2608:45
Table3-1.Comparisonofw,who,andfinger
InformationDisplayed w who finger
Userloginname x x x
Terminal-lineidentification(tty) x x x

Logindayandtime x x
Logindateandtime x
Idletime x x
Whatprogramtheuserisexecuting x
Wheretheuserloggedinfrom x
CPUtimeused x
Fullname(orotherinformationfrom/etc/passwd) x
User-suppliedvanityinformation x
Systemuptimeandloadaverage x
who:ListsUsersontheSystem
Thewhoutilitydisplaysalistofuserswhoareloggedin.InFigure3-10,thefirstcolumnshowsAlex
andJennyloggedin.(Alexisloggedinfromtwolocations.)Thesecondcolumnshowsthedevicethat
eachperson'sterminal,workstation,orterminalemulatorisconnectedto.Thethirdcolumnshowsthe
dateandtimethepersonloggedin.
Theinformationthatwhodisplaysisusefulwhenyouwanttocommunicatewithauseratyour
installation.Whentheuserisloggedin,youcanusewrite(page67)toestablishcommunication
immediately.Ifwhodoesnotlisttheuserorifyoudonotneedtocommunicateimmediately,youcansend
emailtothatperson(page69).
Iftheoutputofwhoscrollsoffthescreen,youcanredirecttheoutputthroughapipesothatitbecomesthe
inputtoless,whichdisplaystheoutputonepageatatime.Youcanalsouseapipetoredirecttheoutput
throughgreptolookforaspecificname.
Ifyouneedtofindoutwhichterminalyouareusingorwhattimeyouloggedin,youcanusethecommand
whoami:
$whoami
alexpts/5Mar2712:33
finger:ListsUsersontheSystem
security:fingercanbeasecurityrisk
Onsystemswheresecurityisaconcern,thesystemadministratormaydisablefinger.
Thisutilitycangiveinformationthatcanhelpamalicioususerbreakintothesystem.
Youcanusefingertodisplayalistoftheuserswhoareloggedinonthesystem.Inadditiontologin
names,fingersupplieseachuser'sfullnamealongwithinformationaboutwhichdevicetheperson's
terminalisconnectedto,howrecentlytheusertypedsomethingonthekeyboard,whentheuserloggedin,
andwheretheuserislocated(ifthedeviceappearsinasystemdatabase).Iftheuserhasloggedinover
thenetwork,thenameoftheremotesystemisshownastheuser'slocation.Forexample,inFigure3-11
jennyandhlsareloggedinfromtheremotesystemnamedbravo.Theasterisk(*)infrontofthenameof
Helen'sdevice(TTY)indicatesthatshehasblockedothersfromsendingmessagesdirectlytoher
terminal(referto"mesg:DeniesorAcceptsMessages"onpage68).
Figure3-11.fingerI:listswhoisloggedin
$finger
LoginNameTtyIdleLoginTimeOfficeOffice
Phone
rootroot11:35May2408:38
alexAlexWatson/0Jun712:46(:0)
alexAlexWatson/119Jun712:47(:0)
jennyJennyChen/22:24Jun205:33
(bravo.example.com)
hlsHelenSimpson*/22Jun205:33
(bravo.example.com)
Youcanusefingertolearnmoreaboutaparticularindividualbyspecifyingthatuseronthecommand
line.InFigure3-12,fingerdisplaysdetailedinformationaboutAlex.Alexisloggedinandactively
usingoneofhisterminals(pts/1);hehasnotusedhisotherterminal(pts/0)for5minutesand52seconds.
YoualsolearnfromfingerthatifyouwanttosetupameetingwithAlex,youshouldcontactJennyat
extension1693.
.planand.project
MostoftheinformationinFigure3-12wascollectedbyfingerfromsystemfiles.Theinformation
shownaftertheheadingPlan:,however,wassuppliedbyAlex.Thefingerutilitysearchedforafile
named.planinAlex'shomedirectoryanddisplayeditscontents.(Filenamesthatbeginwithaperiod,
suchas.plan,arenotnormallylistedbylsandarecalledinvisiblefilenames[page80].)Youmayfindit
helpfultocreatea.planfileforyourself;itcancontainanyinformationyouchoose,suchasyourtypical
schedule,interests,phonenumber,oraddress.Inasimilarmannerfingerdisplaysthecontentsofthe
.projectfileinyourhomedirectory.IfAlexhadnotbeenloggedin,fingerwouldhavereportedonly
hisuserinformation,thelasttimeheloggedin,thelasttimehereadhisemail,andhisplan.
Figure3-12.fingerII:listsdetailsaboutoneuser
$fingeralex
Login:alexName:AlexWatson
Directory:/home/alexShell:/bin/tcsh
OnsinceWedJun712:46(PDT)onpts/0from:0
5minutes52secondsidle
OnsinceWedJun712:47(PDT)onpts/1frombravo
LastloginWedJun712:47(PDT)on1frombravo
NewmailreceivedWedJun713:162006(PDT)
UnreadsinceFriMay2615:322006(PDT)

Plan:
IwillbeataconferenceinHawaiiallnextweek.Ifyouneedto
seeme,contactJenny
Chen,x1693.
Youcanusefingertodisplayauser'sloginname.Forexample,youmightknowthatHelen'slastname
isSimpsonbutmightnotguessthatherloginnameishls.Thefingerutility,whichisnotcasesensitive,
cansearchforinformationonHelenusingherfirstorlastname.Thefollowingcommandsfindthe
informationyouseekaswellasinformationonotheruserswhosenamesareHelenorSimpson.
$fingerHELEN
Login:hlsName:HelenSimpson.
...
$fingersimpson
Login:hlsName:HelenSimpson.
...
w:ListsUsersontheSystem
Thewutilitydisplaysalistoftheuserswhoareloggedin.Asdiscussedinthesectiononwho,the
informationthatwdisplaysisusefulwhenyouwanttocommunicatewithsomeoneatyourinstallation.
ThefirstcolumninFigure3-13showsthatAlex,Jenny,andScottareloggedin.Thesecondcolumn
showsthedevicenumberthateachperson'sterminalisconnectedto.Thethirdcolumnshowsthesystem
thataremoteuserisloggedinfrom.Thefourthcolumnshowsthetimeeachpersonloggedin.Thefifth
columnindicateshowlongeachpersonhasbeenidle(howmuchtimehaselapsedsincetheuserpressed
akeyonthekeyboard).Thenexttwocolumnsgivemeasuresofhowmuchcomputerprocessortimeeach
personhasusedduringthisloginsessionandonthetaskthatisrunning.Thelastcolumnshowsthe
commandeachpersonisrunning.
Thefirstlinethatthewutilitydisplaysincludesthetimeofday,theperiodoftimethecomputerhasbeen
running(indays,hours,andminutes),thenumberofusersloggedin,andtheloadaverage(howbusythe
systemis).Thethreeloadaveragenumbersrepresentthenumberofjobswaitingtorun,averagedoverthe
past1,5,and15minutes.Usetheuptimeutilitytodisplayjustthisline.Table3-1comparesthew,
who,andfingerutilities.
Figure3-13.Thewutility
$w
8:20amup4days,2:28,3users,loadaverage:0.04,0.04,0.00
USERTTYFROMLOGIN@IDLEJCPUPCPUWHAT
alexpts/4:05:55am13:450.15s0.07sw
alexpts/5:05:55am272:551:01bash
jennypts/7bravo5:56am13:440.51s30svim
3.txt
scottpts/12bravo7:17pm1.00s0:14srun_bdgt
CommunicatingwithOtherUsers
Theutilitiesdiscussedinthissectionexchangemessagesandfileswithotheruserseitherinteractivelyor
throughemail.
write:SendsaMessage
Thewriteutilitysendsamessagetoanotheruserwhoisloggedin.Whenyouandanotheruseruse
writetosendmessagestoeachother,youestablishtwo-waycommunication.Initiallyawrite
command(Figure3-14)displaysabannerontheotheruser'sterminal,sayingthatyouareabouttosenda
message.
Thesyntaxofawritecommandlineis
writeusername[terminal]
Figure3-14.ThewriteutilityI
$writealex
HiAlex,areyouthere?o
Figure3-15.ThewriteutilityII
$writealex
HiAlex,areyouthere?o
Messagefromalex@bravo.example.comonpts/0at16:23...
YesJenny,I'mhere.o
Theusernameistheloginnameoftheuseryouwanttocommunicatewith.Theterminalisanoptional
terminalnamethatisusefuliftheuserisloggedinmorethanonce.Youcandisplaytheloginandterminal
namesoftheuserswhoareloggedinonyoursystembyusingwho,w,orfinger.
Toestablishtwo-waycommunicationwithanotheruser,youandtheotherusermusteachexecutewrite,
specifyingtheother'sloginnameastheusername.Thewriteutilitythencopiestext,linebyline,from
onekeyboard/displaytotheother(Figure3-15).Sometimesithelpstoestablishaconvention,suchas
typingo(forover)whenyouarereadyfortheotherpersontotypeandtypingoo(foroverandout)when
youarereadytoendtheconversation.Whenyouwanttostopcommunicatingwiththeotheruser,press
CONTROL-Datthebeginningofaline.PressingCONTROL-Dtellswritetoquit,displaysEOF(end
offile)ontheotheruser'sterminal,andreturnsyoutotheshell.Theotherusermustdothesame.
IftheMessagefrom...bannerappearsonyourscreenandobscuressomethingyouareworkingon,press
CONTROL-LorCONTROL-Rtorefreshthescreenandremovethebanner.Thenyoucancleanup,exit
fromyourwork,andrespondtothepersonwhoiswritingtoyou.Youjusthavetorememberwhois
writingtoyou,becausethebannerwillnolongerappearonthescreen.
mesg:DeniesorAcceptsMessages
Givethefollowingcommandwhenyoudonotwishtoreceivemessagesfromanotheruser:
$mesgn
IfAlexhadgiventhiscommandbeforeJennytriedtosendhimamessage,shewouldhaveseenthe
following:
$writealex
Permissiondenied
Youcanallowmessagesagainbyenteringmesgy.Givethecommandmesgbyitselftodisplayisy(for
yes,messagesareallowed)orisn(forno,messagesarenotallowed).
Email
Youcanuseemail,orelectronicmail,tosendandreceiveletters,memos,reminders,invitations,and
evenjunkmail(unfortunately).Emailcanalsotransmitbinarydata,suchaspicturesorcompiledcode,as
attachments.Anattachmentisafilethatisattachedto,butisnotpartof,apieceofemail.Attachments
arefrequentlyopenedbyprogramsthatarecalledbyyourmailprogram,soyoumaynotbeawarethat
theyarenotanintegralpartofanemailmessage.
Youcanuseemailtocommunicatewithusersonyoursystemand,ifyourinstallationispartofanetwork,
withotherusersonthenetwork.IfyouareconnectedtotheInternet,youcancommunicateelectronically
withusersaroundtheworld.
Emailutilitiesdifferfromwriteinthatemailutilitiescansendamessagewhentherecipientisnot
loggedin.Theseutilitiescanalsosendthesamemessagetomorethanoneuseratatime.
ManymailprogramsareavailableforLinux,includingtheoriginalcharacter-basedmailprogram,
Netscape/Mozillamail,pine,mailthroughemacs,Kmail,evolution,andexmh,whichare
suppliedwithmanyLinuxdistributions.Anotherpopulargraphicalmailprogramissylpheed
(sylpheed.good-day.net).
Youcanusetwoprogramstomakeanymailprogrameasiertouseandmoresecure.Theprocmail
program(www.procmail.org)createsandmaintainsmailserversandmailinglists;preprocessesmailby
sortingitintoappropriatefilesanddirectories;startsvariousprogramsdependingonthecharacteristics
ofincomingmail;forwardsmail;andsoon.TheGNUPrivacyGuard(gpgorGNUpg)encryptsand
decryptsemailandmakesitalmostimpossibleforanunauthorizedpersontoread.
Networkaddresses
IfyoursystemispartofaLAN,youcangenerallysendmailtoandreceivemailfromusersonother
systemsontheLANbyusingtheirloginnames.SomeonesendingAlexemailontheInternetwouldneed
tospecifyhisdomainname(page873)alongwithhisloginname.Usethefollowingaddresstosend
emailtotheauthorofthisbook:mgs@sobell.com.

ChapterSummary
TheutilitiesintroducedinthischapterandChapter2constituteasmallbutpowerfulsubsetofthemany
utilitiesavailableonatypicalLinuxsystem.Becauseyouwillusethemfrequentlyandbecausetheyare
integraltothefollowingchapters,itisimportantthatyoubecomecomfortableusingthem.
TheutilitieslistedinTable3-2manipulate,display,compare,andprintfiles.
Table3-2.Fileutilities
Utility Function
cp Copiesoneormorefiles(page45)
diff Displaysthedifferencesbetweentwofiles(page51)
file Displaysinformationaboutthecontentsofafile(page52)
grep Searchesfile(s)forastring(page48)
head Displaysthelinesatthebeginningofafile(page49)
lpq Displaysalistofjobsintheprintqueue(page47)
lpr Placesfile(s)intheprintqueue(page47)
lprm Removesajobfromtheprintqueue(page48)
mv Renamesafileormovesfile(s)toanotherdirectory(page46)
sort Putsafileinorderbylines(page50)
tail Displaysthelinesattheendofafile(page49)
uniq Displaysthecontentsofafile,skippingsuccessiveduplicatelines(page51)
Toreducetheamountofdiskspaceafileoccupies,youcancompressitwiththebzip2utility.The
compressionworksespeciallywellonfilesthatcontainpatterns,suchasmosttextfiles,butreducesthe
sizeofalmostallfiles.Theinverseofbzip2bunzip2restoresafiletoitsoriginal,decompressed
form.Table3-3listsutilitiesthatcompressanddecompressfiles.Thebzip2utilityisthemostefficient
ofthese.

Table3-3.(De)compressionutilities
Utility Function
bunzip2 Returnsafilecompressedwithbzip2toitsoriginalsizeandformat(page
57)
bzcat Displaysafilecompressedwithbzip2(page57)
bzip2 Compressesafile(page56)
compress Compressesafile(notaswellasgzip)(page58)
gunzip Returnsafilecompressedwithgziporcompresstoitsoriginalsizeand
format(page58)
gzip Compressesafile(page58)
zcat Displaysafilecompressedwithgzip(page58)
Anarchiveisafile,usuallycompressed,thatcontainsagroupoffiles.Thetarutility(Table3-4)packs
andunpacksarchives.Thefilenameextensions.tar.bz2,.tar.gz,and.tgzidentifycompressedtar
archivefilesandareoftenseenonsoftwarepackagesobtainedovertheInternet.
Table3-4.Archiveutility
Utility Function
tar Createsorextractsfilesfromanarchivefile(page58)
TheutilitieslistedinTable3-5determinethelocationofautilityonthelocalsystem.Forexample,they
candisplaythepathnameofautilityoralistofC++compilersavailableonthesystem.
Table3-5.Locationutilities
Utility Function
apropos Searchesthemanpageone-linedescriptionsforakeyword(page62)
slocate Searchesforfilesonthelocalsystem(page63)
whereis Displaysthefullpathnamesofautility,sourcecode,ormanpage(page61)

which Displaysthefullpathnameofacommandyoucanrun(page61)
Table3-6listsutilitiesthatdisplayinformationaboutotherusers.Youcaneasilylearnauser'sfullname,
theuser'sloginstatus,theloginshelloftheuser,andotherinformationmaintainedbythesystem.
Table3-6.Userandsysteminformationutilities
Utility Function
finger Displaysdetailedinformationaboutusers,includingtheirfullnames(page
64)
wDisplaysdetailedinformationaboutuserswhoareloggedin(page66)
who Displaysinformationaboutuserswhoareloggedin(page64)
TheutilitiesshowninTable3-7canhelpyoustayintouchwithotherusersonthelocalnetwork.
Table3-7.Usercommunicationutilities
mesg Permitsordeniesmessagessentbywrite(page68)
write Sendsamessagetoanotheruserwhoisloggedin(page67)
Table3-8listsmiscellaneousutilities.
Table3-8.Miscellaneousutilities
date Displaysthecurrentdateandtime(page54)
echo Copiesitsarguments(page861)tothescreen(page53)
Exercises
1. Whatcommandscanyouusetodeterminewhoisloggedinonaspecificterminal?
2. Howcanyoukeepotherusersfromusingwritetocommunicatewithyou?Whywouldyouwantto?
3.
Whathappenswhenyougivethefollowingcommandsifthefilenameddonealreadyexists?
$cpto_dodone
$mvto_dodone
4. Howcanyoufindoutwhichutilitiesareavailableonyoursystemforeditingfiles?Whichutilitiesareavailableforeditingonyour
system?
5.
HowcanyoufindthephonenumberforAceElectronicsinafilenamedphonethatcontainsalistofnamesandphonenumbers?Which
commandcanyouusetodisplaytheentirefileinalphabeticalorder?Howcanyouremoveadjacentduplicatelinesfromthefile?How
canyouremoveallduplicates?
6. Whathappenswhenyouusedifftocomparetwobinaryfilesthatarenotidentical?(Youcanusegziptocreatethebinaryfiles.)
ExplainwhythediffoutputforbinaryfilesisnotthesameasthediffoutputforASCIIfiles.
7. Createa.planfileinyourhomedirectory.Doesfingeronyoursystemdisplaythecontentsofyour.planfile?
8. Whatistheresultofgivingthewhichutilitythenameofacommandthatresidesinadirectorythatisnotinyoursearchpath?
9. Areanyoftheutilitiesdiscussedinthischapterfoundinmorethanonedirectoryonyoursystem?Ifso,whichones?
10. Experimentbycallingthefileutilitywithnamesoffilesin/usr/bin.Howmanydifferenttypesoffilesarethere?
11. Whichcommandcanyouusetolookatthefirstfewlinesofafilenamedstatus.report?Whichcommandcanyouusetolookatthe
endofthefile?
AdvancedExercises
12. Re-createthecolors.1andcolors.2filesusedinFigure3-8onpage52.Testyourfilesbyrunningdiffuonthem,andseewhetheryou
getthesameresultsasinthefigure.
13.
Trygivingthesetwocommands.
$echocat
$catecho
Explainthedifferencesbetweenthem.
14. Repeatexercise5usingthefilephone.gz,acompressedversionofthelistofnamesandphonenumbers.Trytoconsidermorethanone
approachtoanswereachquestion,andexplainhowyoumadeyourchoices.
15.
Findexistingfilesorcreatefilesthat
1. gzipcompressesbymorethan80percent
2. gzipcompressesbylessthan10percent
3. getlargerwhencompressedwithgzip
Uselsltodeterminethesizesofthefilesinquestion.Canyoucharacterizethefilesina,b,andc?
16.
Somemailersparticularlyolderonesarenotabletohandlebinaryfiles.Supposethatyouaremailingafilethathasbeencompressedwith
gzip,whichproducesabinaryfile,andyoudonotknowwhatmailertherecipientisusing.Refertothemanpageforuuencode,
whichconvertsabinaryfiletoanASCIIfile.Learnabouttheutilityandhowtouseit.
1. ConvertacompressedfiletoASCII,usinguuencode.Istheencodedfilelargerorsmallerthanthecompressedfile?Explain.(If
uuencodeisnotonyoursystem,youcandownloaditfromrpmfind.net;itispartoftheGNUsharutilspackage.)
2. Woulditevermakesensetouseuuencodeonafilebeforecompressingit?Explain.
Chapter4.TheLinuxFilesystem
INTHISCHAPTER
TheHierarchicalFilesystem76
DirectoryandOrdinaryFiles77
AbsolutePathnames83
RelativePathnames84
WorkingwithDirectories88
AccessPermissions91
HardLinks97
SymbolicLinks99
AFilesystemisadatastructure(870)thatusuallyresidesonpartofadiskandthatholdsdirectoriesof
files.Filesystemsstoreuserandsystemdatathatarethebasisofusers'workonthesystemandthe
system'sexistence.ThischapterdiscussestheorganizationandterminologyoftheLinuxfilesystem,
definesordinaryanddirectoryfiles,andexplainstherulesfornamingthem.Italsoshowshowtocreate
anddeletedirectories,movethroughthefilesystem,andusepathnamestoaccessfilesinvarious
directories.Itincludesadiscussionofimportantfilesanddirectoriesaswellasvarioustypesoffilesand
waystoworkwiththem.Inaddition,thischaptercoversfileaccesspermissions,whichallowyouto
shareselectedfileswithotherusers,andlinks,whichcanmakeasinglefileappearinmorethanone
directory.
Inadditiontoreadingthischapter,youmaywanttorefertothedf,fsck,mkfs,andtune2fsutilities
inPartVformoreinformationonfilesystems.

TheHierarchicalFilesystem
Familytree
Ahierarchical(878)structurefrequentlytakestheshapeofapyramid.Oneexampleofthistypeof
structureisfoundbytracingafamily'slineage:Acouplehasachild,whomayinturnhaveseveral
children,eachofwhommayhavemorechildren.Thishierarchicalstructure(showninFigure4-1)is
calledafamilytree.
Figure4-1.Afamilytree
Directorytree
Likethefamilytreeitresembles,theLinuxfilesystemiscalledatree.Itconsistsofasetofconnected
files.Thisstructureallowsyoutoorganizefilessoyoucaneasilyfindanyparticularone.Onastandard
Linuxsystem,eachuserstartswithonedirectory,towhichtheusercanaddsubdirectoriestoanydesired
level.Bycreatingmultiplelevelsofsubdirectories,ausercanexpandthestructureasneeded.
Subdirectories
Typicallyeachsubdirectoryisdedicatedtoasinglesubject,suchasaperson,project,orevent.The
subjectdictateswhetherasubdirectoryshouldbesubdividedfurther.Forexample,Figure4-2showsa
secretary'ssubdirectorynamedcorrespond.Thisdirectorycontainsthreesubdirectories:business,
memos,andpersonal.Thebusinessdirectorycontainsfilesthatstoreeachletterthesecretarytypes.If
youexpectmanyletterstogotooneclient,asisthecasewithmilk_co,youcandedicateasubdirectoryto

thatclient.
Figure4-2.Asecretary'sdirectories
OnemajorstrengthoftheLinuxfilesystemisitsabilitytoadapttousers'needs.Youcantakeadvantageof
thisstrengthbystrategicallyorganizingyourfilessotheyaremostconvenientandusefulforyou.

DirectoryandOrdinaryFiles
Likeafamilytree,thetreerepresentingthefilesystemisusuallypicturedupsidedown,withitsrootatthe
top.Figures4-2and4-3showthatthetree"grows"downwardfromtheroot,withpathsconnectingthe
roottoeachoftheotherfiles.Attheendofeachpathiseitheranordinaryfileoradirectoryfile.
Ordinaryfiles,orsimplyfiles,appearattheendsofpathsthatcannotsupportotherpaths.Directoryfiles,
usuallyreferredtoasdirectoriesorfolders,arepointsthatotherpathscanbranchofffrom.(Figures4-2
and4-3showsomeemptydirectories.)Whenyourefertothetree,upistowardtherootanddownis
awayfromtheroot.Directoriesdirectlyconnectedbyapatharecalledparents(closertotheroot)or
children(fartherfromtheroot).Apathnameisaseriesofnamesthattracesapathalongbranchesfrom
onefiletoanother.
Figure4-3.Directoriesandordinaryfiles
Filenames
Everyfilehasafilename.Themaximumlengthofafilenamevarieswiththetypeoffilesystem;Linux
includessupportforseveraltypesoffilesystems.Mostoftoday'sfilesystemsallowyoutocreatefiles
withnamesupto255charactersinlength,butsomeolderfilesystemsmayrestrictyouto14-character
names.Althoughyoucanusealmostanycharacterinafilename,youwillavoidconfusionifyouchoose
charactersfromthefollowinglist:
Uppercaseletters(AZ)
Lowercaseletters(az)

Numbers(09)
Underscore(_)
Period(.)
Comma(,)
/orroot
Therootdirectoryisalwaysnamed/(slash)andreferredtobythissinglecharacter.Nootherfilecanuse
thisnameorhavea/initsname.However,inapathname,whichisastringoffilenamesincluding
directorynames,theslashseparatesfilenames(page83).
Likethechildrenofoneparent,notwofilesinthesamedirectorycanhavethesamename.(Parentsgive
theirchildrendifferentnamesbecauseitmakesgoodsense,butLinuxrequiresit.)Filesindifferent
directories,likechildrenofdifferentparents,canhavethesamename.
Thefilenamesyouchooseshouldmeansomething.Toooftenadirectoryisfilledwithimportantfileswith
suchunhelpfulnamesashold1,wombat,andjunk,nottomentionfooandfoobar.Suchnamesarepoor
choicesbecausetheydonothelpyourecallwhatyoustoredinafile.Thefollowingfilenamesconformto
thesuggestedsyntaxandconveyinformationaboutthecontentsofthefile:
correspond
january
davis
reports
2001
acct_payable
Filenamelength
Whenyousharefileswithusersonothersystems,youmayneedtomakelongfilenamesdifferwithinthe
first14characters.Ifyoukeepthefilenamesshort,theyareeasytotype;lateryoucanaddextensionsto
themwithoutexceedingthe14-characterlimitimposedbysomefilesystems.Thedisadvantageofshort
filenamesisthattheyaretypicallylessdescriptivethanlongfilenames.Whenyousharefileswith

systemsrunningDOSorolderversionsofWindows,youmustrespectthe8-characterfilenamebody
lengthand3-characterfilenameextensionlengthimposedbythosesystems.
Longfilenamesenableyoutoassigndescriptivenamestofiles.Tohelpyouselectamongfileswithout
typingentirefilenames,shellssupportfilenamecompletion.Formoreinformationaboutthisfeature,see
the"Filenamecompletion"tiponpage45.
Youcanuseuppercaseand/orlowercaseletterswithinfilenames.Linuxiscasesensitive,sofilesnamed
JANUARY,January,andjanuaryrepresentthreedistinctfiles.
caution:DonotuseSPACEswithinfilenames
AlthoughyoucanuseSPACEswithinfilenames,itisapooridea.BecauseaSPACEisa
specialcharacter,youmustquoteitonacommandline.Quotingacharacteronacommand
linecanbedifficultforanoviceuserandcumbersomeforanexperienceduser.Use
periodsorunderscoresinsteadofSPACEs:joe.05.04.26,new_stuff.
FilenameExtensions
InthefilenameslistedinTable4-1,filenameextensionshelpdescribethecontentsofthefile.Afilename
extensionisthepartofthefilenamefollowinganembeddedperiod.Someprograms,suchastheC
programminglanguagecompiler,dependonspecificfilenameextensions.Inmostcases,however,
filenameextensionsareoptional.Useextensionsfreelytomakefilenameseasytounderstand.Youcanuse
severalperiodswithinthesamefilenameforexample,notes.4.10.01orfiles.tar.gz.
Table4-1.Filenameextensions
compute.c ACprogramminglanguagesourcefile
compute.o Theobjectcodefortheprogram
compute Thesameprogramasanexecutablefile
memo.0410.txt Atextfile
memo.pdf APDFfile;viewwithxpdfunderaGUI
memo.ps APostScriptfile;viewwithgsunderaGUI
memo.Z Afilecompressedwithcompress(page58);useuncompressor
gunzip(page58)todecompress
memo.tgzor

memo.tar.gz Atar(page58)archiveoffilescompressedwithgzip(page58)
memo.gz Afilecompressedwithgzip(page58);viewwithzcator
decompresswithgunzip(bothonpage58)
memo.bz2 Afilecompressedwithbzip2(page56);viewwithbzcator
decompresswithbunzip2(bothonpage57)
memo.html AfilemeanttobeviewedusingaWebbrowser,suchasMozilla
photo.jpgorphoto.gif Afilecontaininggraphicalinformation,suchasapicture(also.jpeg)
InvisibleFilenames
Afilenamethatbeginswithaperiodiscalledaninvisiblefilename(oraninvisiblefileorsometimesa
hiddenfile)becauselsdoesnotnormallydisplayit.Thecommandlsadisplaysallfilenames,even
invisibleones.Namesofstartupfiles(page83)usuallybeginwithaperiodsothattheyareinvisibleand
donotclutteradirectorylisting.The.planfile(page65)isalsoinvisible.Twospecialinvisibleentriesa
singleanddoubleperiod(.and..)appearineverydirectory(page85).
mkdir:CreatesaDirectory
Themkdirutilitycreatesadirectory.Theargument(861)tomkdirbecomesthepathnameofthenew
directory.ThefollowingexamplesdevelopthedirectorystructureshowninFigure4-4.Inthefigurethe
directoriesthatareaddedarealightershadethantheothersandareconnectedbydashes.
Figure4-4.Thefilestructuredevelopedintheexamples
InFigure4-5,lsshowsthenamesofthefilesAlexhasbeenworkingwithinhishomedirectory:demo,
names,andtemp.Usingmkdir,Alexthencreatesadirectorynamedliteratureasachildofthe
/home/alexdirectory.Whenyouusemkdir,enterthepathnameofyourhomedirectory(page82)in
placeof/home/alex.Thesecondlsverifiesthepresenceofthenewdirectory.
Figure4-5.Themkdirutility
$ls
demonamestemp
$mkdir/home/alex/literature
$ls
demoliteraturenamestemp
$ls-F
demoliterature/namestemp
$lsliterature
$
YoucanusetheFoptionwithlstodisplayaslashafterthenameofeachdirectoryandanasteriskafter
eachexecutablefile(shellscript,utility,orprogram).Whenyoucallitwithanargumentthatisthename
ofadirectory,lsliststhecontentsofthedirectory.Ifthedirectoryisempty,lsdoesnotdisplay
anything.
Theworkingdirectory
pwd
Whileyouareloggedinonacharacter-basedinterfacetoaLinuxsystem,youarealwaysassociatedwith
adirectory.Thedirectoryyouareassociatedwith,orareworkingin,iscalledtheworkingdirectoryor

currentdirectory.Sometimesthisassociationisreferredtoinaphysicalsense:"Youarein(orworking
in)thejennydirectory."Thepwdcommanddisplaysthepathnameoftheworkingdirectory.
Toaccessanyfileintheworkingdirectory,youneedonlyasimplefilename.Toaccessafileinanother
directory,youmustuseapathname.
SignificanceoftheWorkingDirectory
Typingalongpathnameistediousandincreasesthechanceofmakingamistake.Thispossibilityisless
likelyunderaGUI,whereyouclickfilenamesoricons.Youcanchooseaworkingdirectoryforany
particulartasktoreducetheneedforlongpathnames.Yourchoiceofaworkingdirectorydoesnotallow
youtodoanythingyoucouldnotdootherwise.Instead,itsimplymakessomeoperationseasier.
RefertoFigure4-6asyoureadthisparagraph.Filesthatarechildrenoftheworkingdirectorycanbe
referencedbysimplefilenames.Grandchildrenoftheworkingdirectorycanbereferencedbyshort
relativepathnames:twofilenamesseparatedbyaslash.Whenyoumanipulatefilesinalargedirectory
structure,shortrelativepathnamescansavetimeandaggravation.Ifyouchooseaworkingdirectorythat
containsthefilesusedmostoftenforaparticulartask,youneedtousefewerlong,cumbersome
pathnames.
Figure4-6.Relativepathnames
Homedirectory
WhenyoufirstloginonaLinuxsystem,yourworkingdirectoryisyourhomedirectory.Todisplaythe
pathnameofyourhomedirectory,usepwdjustafteryoulogin(seeFigure4-7).
Whenusedwithoutanyarguments,thelsutilitydisplaysalistofthefilesintheworkingdirectory.
Becauseyourhomedirectoryhasbeentheonlyworkingdirectoryyouhaveusedsofar,lshasalways
displayedalistoffilesinyourhomedirectory.(Allthefilesyouhavecreateduptothispointwere
createdinyourhomedirectory.)
cd:ChangestoAnotherWorkingDirectory
Thecd(changedirectory)utilitymakesanotherdirectorytheworkingdirectorybutdoesnotchangethe
contentsoftheworkingdirectory.ThefirstcdcommandinFigure4-8makesthe/home/alex/literature
directorytheworkingdirectory,asverifiedbypwd.
Whenusedwithoutanargument,cdmakesyourhomedirectorytheworkingdirectory,asitwaswhenyou
firstloggedin.ThesecondcdcommandinFigure4-8doesnothaveanargumentandmakesAlex'shome
directorytheworkingdirectory.
Figure4-7.Logginginanddisplayingthepathnameofyourhomedirectory
login:alex
Password:
Lastlogin:WedOct2011:14:21frombravo
$pwd
/home/alex
Figure4-8.cdchangesyourworkingdirectory
$cd/home/alex/literature
$pwd
/home/alex/literature
$cd
$pwd
/home/alex
tip:Theworkingdirectoryversusyourhomedirectory
Theworkingdirectoryisnotthesameasyourhomedirectory.Yourhomedirectoryremains
thesameforthedurationofyoursessionandusuallyfromsessiontosession.Eachtime
immediatelyafteryoulogin,youareworkinginthesamedirectory:yourhomedirectory.
Unlikeyourhomedirectory,theworkingdirectorycanchangeasoftenasyoulike.You
havenosetworkingdirectory,whichiswhysomepeoplerefertoitasthecurrent
directory.Whenyouloginanduntilyouchangedirectoriesbyusingcd,yourhome
directoryisyourworkingdirectory.IfyouweretochangedirectoriestoScott'shome
directory,thenScott'shomedirectorywouldbeyourworkingdirectory.
Startupfiles
Startupfiles,whichappearinyourhomedirectory,givetheshellandotherprogramsinformationabout
youandyourpreferences.Frequently,oneofthesefilestellstheshellwhatkindofterminalyouareusing
andexecutesthestty(setterminal)utilitytoestablishyourlinekillanderasekeys.
Eitheryouorthesystemadministratorcanputashellstartupfilecontainingshellcommandsinyourhome
directory.Theshellexecutesthecommandsinthisfileeachtimeyoulogin.Becausethestartupfileshave
invisiblefilenames,youmustusethelsacommandtoseewhetheroneisinyourhomedirectory.See
pages257and342formoreinformationaboutstartupfiles.
AbsolutePathnames
Everyfilehasapathname.Figure4-9showsthepathnamesofdirectoriesandordinaryfilesinpartofa
filesystemhierarchy.Anabsolutepathnamealwaysstartswithaslash(/),thenameoftherootdirectory.
Youcanbuildtheabsolutepathnameofafilebytracingapathfromtherootdirectorythroughallthe
intermediatedirectoriestothefile.Stringallthefilenamesinthepathtogether,separatingeachfromthe
nextwithaslash(/)andprecedingtheentiregroupoffilenameswithaslash(/).Thispathoffilenames
iscalledanabsolutepathnamebecauseitlocatesafileabsolutelybytracingapathfromtheroot
directorytothefile.Thepartofapathnamefollowingthefinalslashiscalledasimplefilenameorjust
filename.

Figure4-9.Absolutepathnames
Anotherformofabsolutepathnamebeginswithatilde(~),whichrepresentsahomedirectory.Formore
informationreferto"~(Tilde)inPathnames"onpage89.
RelativePathnames
Arelativepathnametracesapathfromtheworkingdirectorytoafile.Thepathnameisrelativetothe
workingdirectory.Anypathnamethatdoesnotbeginwiththerootdirectory(/)oratilde(~)isarelative
pathname.Likeabsolutepathnames,relativepathnamescandescribeapaththroughmanydirectories.
AlexcouldhavecreatedtheliteraturedirectoryinFigure4-5moreeasilybyusingarelativepathname:
$pwd
/home/alex
$mkdirliterature
ThepwdcommandshowsthatAlex'shomedirectory(/home/alex)istheworkingdirectory.Themkdir
utilitydisplaysanerrormessageifadirectoryorfilenamedliteratureexists:Youcannothavetwofiles
ordirectorieswiththesamenameinthesamedirectory.Thepathnameusedinthisexampleisasimple
filenameakindofrelativepathnamethatspecifiesafileintheworkingdirectory.
Thefollowingcommandsshowtwowaystocreatethepromodirectoryasachildofthenewlycreated
literaturedirectory.Thefirstwayworkswhen/home/alexistheworkingdirectoryandusesarelative
pathname.
$pwd
/home/alex
$mkdirliterature/promo
caution:Whenusingarelativepathname,knowwhichdirectoryisthe
workingdirectory
Thelocationofthefilethatyouareaccessingwitharelativepathnamedependson(is
relativeto)theworkingdirectory.Alwaysmakesureyouknowwhichdirectoryisthe
workingdirectorybeforeyouusearelativepathname.Usepwdtoverifythedirectory.If
youareusingmkdirandyouarenotwhereyouthinkyouareinthefilehierarchy,thenew
directorywillendupinanunexpectedlocation.
Itdoesnotmatterwhichdirectoryistheworkingdirectorywhenyouuseanabsolute
pathname.
Thesecondwayusesanabsolutepathname:
$mkdir/home/alex/literature/promo
Usethep(parents)optiontomkdirtocreateboththeliteratureandpromodirectorieswithasingle
command.
$pwd
/home/alex
$ls
demonamestemp
$mkdir-pliterature/promo
or
$mkdir-p/home/alex/literature/promo
The.and..Directoryentries
Themkdirutilityautomaticallyputstwoentriesineachdirectoryitcreates:asingleperiod(.)anda
doubleperiod(..),representingthedirectoryitselfandtheparentdirectory,respectively.Theseentries
areinvisiblebecauseeachoftheirfilenamesbeginswithaperiod.
Becausemkdirautomaticallyplacestheseentriesineverydirectory,youcanrelyontheirpresence.The
.issynonymouswiththepathnameoftheworkingdirectoryandcanbeusedinitsplace;..issynonymous
withthepathnameoftheparentoftheworkingdirectory.
Withtheliteraturedirectoryastheworkingdirectory,thefollowingexampleuses..threetimes:firstto
listthecontentsoftheparentdirectory(/home/alex),secondtocopythememoAfiletotheparent
directory,andthirdtolistthecontentsoftheparentdirectoryagain.
$pwd
/home/alex/literature
$ls..
demoliteraturenamestemp
$cpmemoA..
$ls..
demoliteraturememoAnamestemp
Whileworkinginthepromodirectory,Alexcanusearelativepathnametoeditafileinhishome
directory.Beforecallingtheeditor,Alexcheckswhichdirectoryheisin:

$pwd
/home/alex/literature/promo
$vim../../names
Virtuallyanywherethatautilityorprogramrequiresafilenameorpathname,youcanuseanabsoluteor
relativepathnameorasimplefilename.Thisusageholdstrueforls,vim,mkdir,rm,andotherLinux
utilities.
ImportantStandardDirectoriesandFiles
OriginallyfilesonaLinuxsystemwerenotlocatedinstandardplaces.Thescatteredfilesmadeit
difficulttodocumentandmaintainaLinuxsystemandjustaboutimpossibleforsomeonetoreleasea
softwarepackagethatwouldcompileandrunonallLinuxsystems.ThefirststandardfortheLinux
filesystem,theFSSTND(LinuxFilesystemStandard),wasreleasedonFebruary14,1994.Inearly1995
workwasstartedonabroaderstandardcoveringmanyUNIX-likesystems:FHS(LinuxFilesystem
HierarchyStandardwww.pathname.com/fhs).Morerecently,FHShasbeenincorporatedinLSB(Linux
StandardBasewww.linuxbase.org),aworkgroupofFSG(FreeStandardsGroupwww.freestandards.org).
Figure4-10showsthelocationsofsomeimportantdirectoriesandfilesasspecifiedbyFHS.The
significanceofmanyofthesedirectorieswillbecomeclearasyoucontinuereading.
Figure4-10.AtypicalFHS-basedLinuxsystemfilestructure
ThefollowinglistdescribesthedirectoriesshowninFigure4-10,someofthedirectoriesspecifiedby
FHS,andsomeotherdirectories.MostLinuxdistributionsdonotuseallthedirectoriesspecifiedby
FHS.Youcannotalwaysdeterminethefunctionofadirectorybyitsname.Forexample,although/opt
storesadd-onsoftware,/etc/optstoresconfigurationfilesforthesoftwarein/opt.
/RootTherootdirectory,presentinallLinuxsystemfilestructures,isthe
ancestorofallfilesinthefilesystem.
/bin EssentialcommandbinariesHoldsthefilesneededtobringthesystemupand
runitwhenitfirstcomesupinsingle-usermode.
/boot StaticfilesofthebootloaderContainsmostofthefilesneededtobootthe
system.
/dev DevicefilesContainsallfilesthatrepresentperipheraldevices,suchasdisk
drives,terminals,andprinters.
/etc
MachinelocalsystemconfigurationHoldsadministrative,configuration,and
othersystemfiles.Oneofthemostimportantis/etc/passwd,whichcontainsa
listofalluserswhohavepermissiontousethesystem.
/etc/X11 MachinelocalconfigurationfortheXWindowSystem
/etc/opt Configurationfilesforadd-onsoftwarepackageskeptin/opt
/home
UserhomedirectoriesEachuser'shomedirectoryistypicallyoneofmany
subdirectoriesofthe/homedirectory.Asanexample,assumingthatusers'
directoriesareunder/home,theabsolutepathnameofJenny'shomedirectoryis
/home/jenny.Onsomesystemstheusers'directoriesmaynotbeunder/home
butinsteadmightbespreadamong/inhouseand/clients.
/lib Sharedlibrariesandkernelmodules
/lib/modules Loadablekernelmodules
/mnt Mountpointfortemporarymountingoffilesystems
/opt Add-onsoftwarepackages(optionalpackages)
/proc Kernelandprocessinformationvirtualfilesystem
/root Homedirectoryforroot
/sbin
EssentialsystembinariesUtilitiesusedforsystemadministrationarestoredin
/sbinand/usr/sbin.The/sbindirectoryincludesutilitiesneededduringthe
bootingprocess,and/usr/sbinholdsutilitiesusedafterthesystemisupand
running.InolderversionsofLinux,manysystemadministrationutilitieswere
scatteredthroughseveraldirectoriesthatoftenincludedothersystemfiles(/etc,
/usr/bin,/usr/adm,/usr/include).
/tmp TemporaryfilesUsedtoholdtemporaryfiles.
/usr
SecondmajorhierarchyTraditionallyincludessubdirectoriesthatcontain
informationusedbythesystem.Filesin/usrsubdirectoriesdonotchangeoften
andmaybesharedbymultiplesystems.
/usr/bin MostusercommandsContainsthestandardLinuxutilityprogramsthatis,
binariesthatarenotneededinsingle-usermode.
/usr/bin/X11 Symboliclinkto/usr/X11R6/bin
/usr/games Gamesandeducationalprograms
/usr/include HeaderfilesincludedbyCprograms
/usr/include/X11 Symboliclinkto/usr/X11R6/include/X11
/usr/lib Libraries
/usr/lib/X11 Symboliclinkto/usr/X11R6/lib/X11
/usr/local
LocalhierarchyHoldslocallyimportantfilesanddirectoriesthatareaddedtothe
system.Subdirectoriescanincludebin,games,include,lib,sbin,share,and
src.
/usr/man Onlinemanuals
/usr/sbin NonvitalsystemadministrationbinariesSee/sbin.
/usr/share Architecture-independentdataSubdirectoriescanincludedict,doc,games,
info,locale,man,misc,terminfo,andzoneinfo.
/usr/share/doc Miscellaneousdocumentation
/usr/share/info GNUinfosystem'sprimarydirectory
/usr/src Sourcecode
/usr/X11R6 XWindowSystem,version11release6
/var
VariabledataFileswithcontentsthatvaryasthesystemrunsarefoundin
subdirectoriesunder/var.Themostcommonexamplesaretemporaryfiles,
systemlogfiles,spooledfiles,andusermailboxfiles.Subdirectoriescaninclude
cache,lib,lock,log,opt,run,spool,tmp,andyp.OlderversionsofLinux
scatteredsuchfilesthroughseveralsubdirectoriesof/usr(/usr/adm,/usr/mail,
/usr/spool,/usr/tmp).
/var/log LogfilesContainslastlog(arecordofthelastloginbyeachuser),messages
(systemmessagesfromsyslogd),andwtmp(arecordofalllogins/logouts).
/var/spool
SpooledapplicationdataContainsanacron,at,cron,lpd,mail,mqueue,
news,samba,anduucp.Thefile/var/spool/mailtypicallyhasasymboliclinkin
/var.
WorkingwithDirectories
Thissectioncoversdeletingdirectories,copyingandmovingfilesbetweendirectories,andmoving
directories.ItalsodescribeshowtousepathnamestomakeyourworkwithLinuxeasier.
rmdir:Deletesadirectory
Thermdir(removedirectory)utilitydeletesadirectory.Youcannotdeletetheworkingdirectoryora
directorythatcontainsfilesotherthan.and..entries.Ifyouneedtodeleteadirectorywithfilesinit,
firstusermtodeletethefilesandthendeletethedirectory.Youdonothaveto(norcanyou)deletethe.
and..entries;rmdirremovesthemautomatically.Thefollowingcommanddeletesthedirectorythat
wascreatedinFigure4-5onpage81:
$rmdir/home/alex/literature
Thermutilityhasaroption(rmrfilename)thatrecursivelydeletesfiles,includingdirectories,withina
directoryaswellasthedirectoryitself.
caution:Usermrcarefully,ifatall
Althoughrmrisahandycommand,youmustuseitcarefully.Donotuseitwithan
ambiguousfilereferencesuchas*.Itisquiteeasytowipeoutyourentirehomedirectory
withasingleshortcommand.
Pathnames
touch
Useatexteditortocreateafilenamedletterifyouwanttoexperimentwiththeexamplesthatfollow.Or
youcanusetouchtocreateanemptyfile:
$touchletter
With/home/alexastheworkingdirectory,thefollowingexampleusescpwitharelativepathnameto
copythefilelettertothe/home/alex/literature/promodirectory.Thecopyofthefilehasthesimple
filenameletter.0610:
$pwd
/home/alex
$cpletterliterature/promo/letter.0610
IfAlexdoesnotchangetoanotherdirectory,hecanusevimtoeditthecopyofthefilehejustmade:
$vimliterature/promo/letter.0610
IfAlexdoesnotwanttousealongpathnametospecifythefile,hecanusecdtomakepromotheworking
directorybeforecallingvim:
$cdliterature/promo
$pwd
/home/alex/literature/promo
$vimletter.0610
Tomaketheparentoftheworkingdirectory(named/home/alex/literature)becomethenewworking
directory,Alexcangivethefollowingcommand,whichtakesadvantageofthe..directoryentry:
$cd..
$pwd
/home/alex/literature
~(Tilde)inpathnames
Theshellexpandsthecharacters~/(atildefollowedbyaslash)atthestartofapathnameintothe
pathnameofyourhomedirectory.Usingthisshortcut,youcandisplayyour.bashrcstartupfile(page258)
withthefollowingcommand,nomatterwhichdirectoryisyourworkingdirectory:
$less~/.bashrc
Atildequicklyreferencespathsthatstartwithyourorsomeoneelse'shomedirectory.Theshellexpandsa
tildefollowedbyaloginnameatthebeginningofapathnameintothepathnameofthatuser'shome
directory.Assuminghehaspermissiontodoso,AlexcanexamineScott's~/.bashrcfilewiththe
followingcommand:
$less~scott/.bashrc
Referto"Tildeexpansion"onpage326formoreinformation.
mv,cp:MovesorCopiesaFile
Chapter3discussedtheuseofmvtorenamefiles.However,mvismoregeneralthanthat:Youcanuse
thisutilitytomovefilesfromonedirectorytoanother(changethepathnameofafile)aswellastochange
asimplefilename.Whenusedtomoveoneormorefilestoanewdirectory,themvcommandhasthis
syntax:

mvexisting-file-listdirectory
Iftheworkingdirectoryis/home/alex,Alexcanusethefollowingcommandtomovethefilesnamesand
tempfromtheworkingdirectorytotheliteraturedirectory:
$mvnamestempliterature
Thiscommandchangestheabsolutepathnamesofthenamesandtempfilesfrom/home/alex/namesand
/home/alex/tempto/home/alex/literature/namesand/home/alex/literature/temp,respectively(Figure
4-11).LikemostLinuxcommands,mvacceptseitherabsoluteorrelativepathnames.
Figure4-11.Usingmvtomovenamesandtemp
AsyouworkwithLinuxandcreatemoreandmorefiles,youwillneedtocreatedirectoriesusingmkdir
tokeepthefilesorganized.Themvutilityisausefultoolformovingfilesfromonedirectorytoanotheras
youdevelopyourfiletree.Thecputilityworksinthesamewaythatmvdoes,butitmakescopiesofthe
existing-file-listinthespecifieddirectory.
mv:MovesaDirectory
Justasitmovesordinaryfilesfromonedirectorytoanother,somvcanmovedirectories.Thesyntaxis
similarexceptthatyouspecifyoneormoredirectories,notordinaryfiles,tomove:
mvexisting-directory-listnew-directory
Ifnew-directorydoesnotexist,theexisting-directory-listmustcontainjustonedirectoryname,which
mvchangestonew-directory(mvrenamesthedirectory).Althoughdirectoriescanberenamedusingmv,
theircontentscannotbecopiedwithcpunlessyouusetheroption.Refertotheexplanationsoftar
(page786)andcpio(page619)forotherwaystocopyand/ormovedirectories.

Accessperemissions
Threetypesofuserscanaccessafile:theownerofthefile(owner),amemberofagrouptowhichthe
ownerbelongs(group),andeveryoneelse(other).Ausercanattempttoaccessanordinaryfileinthree
ways:bytryingtoreadfrom,writeto,orexecuteit.Threetypesofusers,eachofwhomisabletoaccess
afileinthreeways,equalsatotalofninepossiblewaystoaccessanordinaryfile.
lsl:DisplaysPermissions
Whenyoucalllswiththeloptionandthenameofanordinaryfile,lsdisplaysalineofinformation
aboutthefile.Thefollowingexampledisplaysinformationfortwofiles.Thefileletter.0610containsthe
textofaletter,andcheck_spellcontainsashellscript,aprogramwritteninahigh-levelshell
programminglanguage:
$ls-lletter.0610check_spell
-rw-r--r--1alexpubs3355May210:52letter.0610
-rwxr-xr-x2alexpubs852May514:03check_spell
Fromlefttoright,thelinesthatanlslcommanddisplayscontainthefollowinginformation(referto
Figure4-12):
Thetypeoffile(firstcharacter)
Thefile'saccesspermissions(thenextninecharacters)
Thenumberoflinkstothefile(page96)
Thenameofthefile'sowner(usuallythepersonwhocreatedthefile)
Thenameofthegroupthathasgroupaccesstothefile
Thesizeofthefileincharacters(bytes)
Thedateandtimethefilewascreatedorlastmodified

Thenameofthefile
Figure4-12.Thecolumnsdisplayedbythelslcommand
Thetypeoffile(firstcolumn)forletter.0610isahyphen()becauseitisanordinaryfile(directoryfiles
haveadinthiscolumn).
Thenextthreecharactersrepresenttheaccesspermissionsfortheownerofthefile:rindicatesread
permissionandwindicateswritepermission.Theinthenextcolumnindicatesthattheownerdoesnot
haveexecutepermission;otherwise,anxwouldappearhere.
Inasimilarmannerthenextthreecharactersrepresentpermissionsforthegroup,andthefinalthree
charactersrepresentpermissionsforother(everyoneelse).Intheprecedingexample,theownerof
letter.0610canreadfromandwritetothefile,whereasthegroupandotherscanonlyreadfromthefile
andnooneisallowedtoexecuteit.Althoughexecutepermissioncanbeallowedforanyfile,itdoesnot
makesensetoassignexecutepermissiontoafilethatcontainsadocument,suchasaletter.The
check_spellfileisanexecutableshellscript,andexecutepermissionisappropriate.(Theowner,the
group,andothersallhaveexecuteaccesspermission.)
chmod:ChangesAccessPermissions
Theownerofafilecontrolswhichusershavepermissiontoaccessthefileandhowtheycanaccessit.
Whenyouownafile,youcanusethechmod(changemode)utilitytochangeaccesspermissionsforthat
file.Inthefollowingexample,chmodadds(+)readandwritepermission(rw)forall(a)users:
$chmoda+rwletter.0610
$ls-lletter.0610
-rw-rw-rw-1alexpubs3355May210:52letter.0610
tip:Youmusthavereadpermissiontoexecuteashellscript
Becauseashellneedstoreadashellscript(anASCIIfilecontainingshellcommands)
beforeitcanexecutethecommandswithinthescript,youmusthavereadpermissiontothe
filecontainingthescripttoexecuteit.Youalsoneedexecutepermissiontoexecuteashell
scriptdirectlyonthecommandline.Binary(program)filesdonotneedtoberead;theyare
executeddirectly.Youneedonlyexecutepermissiontorunabinary(nonshell)program.
Inthenextexample,chmodremoves()readandexecute(rx)permissionsforusersother(o)thanthe
ownerofthefile(Alex)andmembersofthegroupassociatedwiththefile(pubs):
$chmodo-rxcheck_spell
$ls-lcheck_spell
-rwxr-x---2alexpubs852May514:03check_spell
Inadditiontoa(forall)ando(forother),youcanuseg(forgroup)andu(foruser,althoughuserrefers
totheownerofthefile,whomayormaynotbetheuserofthefileatanygiventime)intheargumentto
chmod.Refertopage263formoreinformationonusingchmodtomakeafileexecutable.
Inadditiontothesymbolicargumentsdescribedinthissection,youcanuseabsolute,ornumeric,
argumentswithchmod.Seepage604forinformationonabsoluteargumentsandchmodingeneral.
TheLinuxfileaccesspermissionschemeletsyougiveotherusersaccesstothefilesyouwanttoshareyet
keepyourprivatefilesconfidential.Youcanallowotheruserstoreadfromandwritetoafile(youmay
beoneofseveralpeopleworkingonajointproject).Youcanallowothersonlytoreadfromafile
(perhapsaprojectspecificationyouareproposing).Oryoucanallowothersonlytowritetoafile
(similartoaninboxormailbox,whereyouwantotherstobeabletosendyoumailbutdonotwantthem
toreadyourmail).Similarly,youcanprotectentiredirectoriesfrombeingscanned(coveredshortly).
Thereisanexceptiontotheaccesspermissionsjustdescribed.Anyonewhoknowstherootpassword
canloginasSuperuserandhavefullaccesstoallfiles,regardlessofowneroraccesspermissions.
tip:chmod:oforother,uforowner
Whenusingchmod,manypeopleassumethattheostandsforowner;itdoesnot.Theo
standsforother,whereasustandsforowner(user).
Setuidandsetgidpermissions
Whenyouexecuteafilethathassetuid(setuserID)permission,theprocessexecutingthefiletakesonthe
privilegesofthefile'sowner.Forexample,ifyourunasetuidprogramthatremovesallfilesina
directory,youcanremovefilesinanyofthefileowner'sdirectories,evenifyoudonotnormallyhave
permissiontodoso.
Inasimilarmanner,setgid(setgroupID)permissionmeansthattheprocessexecutingthefiletakesonthe
privilegesofthegroupthefileisassociatedwith.Thelsutilityshowssetuidpermissionbyplacingans
intheowner'sexecutablepositionandsetgidbyplacingansinthegroup'sexecutableposition:
$ls-lprogram1
-rwxr-xr-x1alexpubs15828Nov506:28program1
$chmodu+sprogram1
$ls-lprogram1
-rwsr-xr-x1alexpubs15828Nov506:28program1
$chmodg+sprogram1
$ls-lprogram1
-rwsr-sr-x1alexpubs15828Nov506:28program1
security:Minimizeuseofsetuidandsetgidprogramsownedbyroot
ExecutablefilesthataresetuidandownedbyroothaveSuperuserprivilegeswhentheyare
run,eveniftheyarenotrunbyroot.Thistypeofprogramisverypowerfulbecauseitcan
doanythingthatSuperusercando(thattheprogramisdesignedtodo).Similarly,
executablefilesthataresetgidandbelongtothegrouproothaveextensiveprivileges.
Becauseofthepowertheyholdandtheirpotentialfordestruction,youshouldavoid
creatingandusingsetuidandsetgidprogramsownedbyrootorbelongingtothegrouproot
indiscriminately.Becauseoftheirinherentdangers,manysitesdonotallowtheseprograms
ontheirsystems.
security:Donotwritesetuidshellscripts
Nevergiveshellscriptssetuidpermission.Severaltechniquesforsubvertingthemarewell
known.
Directoryaccesspermissions
Accesspermissionshaveslightlydifferentmeaningswhentheyareusedwithdirectories.Althoughthe
threetypesofuserscanreadfromorwritetoadirectory,thedirectorycannotbeexecuted.Execute
accesspermissionisredefinedforadirectory:Itmeansthatyoucancdintothedirectoryand/orexamine
filesthatyouhavepermissiontoreadinthedirectory.Ithasnothingtodowithexecutingafile.
Whenyouhaveonlyexecutepermissionforadirectory,youcanuselstolistafileinthedirectoryifyou
knowitsname.Youcannotuselswithoutanargumenttolisttheentirecontentsofthedirectory.Inthe
followingexchange,Jennyfirstverifiesthatsheisloggedonasherself.Thenshechecksthepermissions
onAlex'sinfodirectoryandcdsintoit.Youcanviewtheaccesspermissionsassociatedwithadirectory
byrunninglswiththed(directory)andl(long)options:
$whoami
jennypts/7Aug2110:02
$ls-ld/home/alex/info
drwx-----x2alexpubs512Aug2109:31/home/alex/info
$ls-l/home/alex/info
ls:/home/alex/info:Permissiondenied
Thedattheleftendofthelinedisplayedbylsindicatesthat/home/alex/infoisadirectory.Alexhas
read,write,andexecutepermissions;membersofthepubsgrouphavenoaccesspermissions;andother
usershaveexecutepermissiononlyasindicatedbythexattherightendofthepermissions.Because
Jennydoesnothavereadpermissionforthedirectory,thelslcommandreturnsanerror.
WhenJennyspecifiesthenamesofthefilesshewantsinformationabout,sheisnotreadingnewdirectory
informationbutsearchingforspecificinformation,whichsheisallowedtodowithexecuteaccesstothe
directory.Shehasreadaccesstonotes,soshehasnoproblemusingcattodisplaythefile.Shecannot
displayfinancialbecauseshedoesnothavereadaccesstoit:
$ls-l/home/alex/info/financial/home/alex/info/notes
-rw-------1alexpubs34Aug2109:31/home/alex/info/financial
-rw-r--r--1alexpubs30Aug2109:32/home/alex/info/notes
$cat/home/alex/info/notes
Thisisthefilenamednotes.
$cat/home/alex/info/financial
cat:/home/alex/info/financial:Permissiondenied
NextAlexgivesothersreadaccesstohisinfodirectory:
$chmodo+r/home/alex/info
WhenJennychecksheraccesspermissionsoninfo,shefindsthatshehasbothreadandexecuteaccessto
thedirectory.Nowlslworksjustfinewithoutarguments,butshestillcannotreadfinancial.(Thisisan
issueoffilepermissions,notdirectorypermissions.)
Finally,Jennytriestocreateafilenamednewfilebyusingtouch.IfAlexweretogiveherwrite
permissiontotheinfodirectory,shewouldbeabletocreatenewfilesinit:
$ls-ld/home/alex/info
drwx---r-x2alexpubs512Aug2109:31/home/alex/info
$ls-l/home/alex/info
total8
-rw-------1alexpubs34Aug2109:31financial
-rw-r--r--1alexpubs30Aug2109:32notes
$catfinancial
cat:financial:Permissiondenied
$touch/home/alex/info/newfile
touch:cannottouch'/home/alex/info/newfile':Permissiondenied

Links
Alinkisapointertoafile.Eachtimeyoucreateafileusingvim,touch,cp,oranyothermeans,you
areputtingapointerinadirectory.Thispointerassociatesafilenamewithaplaceonthedisk.Whenyou
specifyafilenameinacommand,youareindirectlypointingtotheplaceonthediskthatholdsthe
informationyouwant.
Sharingfilescanbeusefulwhentwoormorepeopleareworkingonthesameprojectandneedtoshare
information.Youcanmakeiteasyforotheruserstoaccessoneofyourfilesbycreatingadditionallinksto
thefile.
Toshareafilewithanotheruser,firstgivetheuserpermissiontoreadfromandwritetothefile.(You
mayalsohavetochangetheaccesspermissionoftheparentdirectoryofthefiletogivetheuserread,
write,and/orexecutepermission.)Oncethepermissionsaresetappropriately,theusercancreatealink
tothefilesothateachofyoucanaccessthefilefromyourseparatefiletrees.
Alinkcanalsobeusefultoasingleuserwithalargefiletree.Youcancreatelinkstocross-classifyfiles
inyourfiletree,usingdifferentclassificationsfordifferenttasks.Forexample,ifyourfiletreeistheone
depictedinFigure4-2,youmighthaveafilenamedto_doineachsubdirectoryofthecorrespond
directorythatis,inpersonal,memos,andbusiness.Ifyoulaterfinditdifficulttokeeptrackofeverything
youneedtodo,youcancreateaseparatedirectorynamedto_dointhecorresponddirectoryandlink
eachsubdirectory'sto-dolistintothatdirectory.Forexample,youcouldlinkthefilenamedto_dointhe
memosdirectorytoafilenamedmemosintheto_dodirectory.ThissetoflinksisshowninFigure4-13.
Figure4-13.Usinglinkstocross-classifyfiles
Althoughitmaysoundcomplicated,thistechniquekeepsallyourto-dolistsconvenientlyinoneplace.
Theappropriatelistiseasilyaccessibleinthetask-relateddirectorywhenyouarebusycomposing
letters,writingmemos,orhandlingpersonalbusiness.
tip:Aboutthediscussionofhardlinks

optional:HardLinks
Ahardlinktoafileappearsasanotherfileinthefilestructure.Ifthelinkappearsinthesamedirectoryasthelinked-tofile,the
linksmusthavedifferentfilenamesbecausetwofilesinthesamedirectorycannothavethesamename.
ln:CREAT ESAHARDLINK
Theln(link)utility(withoutthesorsymbolicoption)createsanadditionalhardlinktoanexistingfileusingthefollowingsyntax:
lnexisting-filenew-link
ThenextcommandmakesthelinkshowninFigure4-14bycreatinganewlinknamed/home/alex/lettertoanexistingfilenamed
draftinJenny'shomedirectory:
$pwd
/home/jenny
$lndraft/home/alex/letter
Figure4-14.Twolinkstothesamefile:/home/alex/letterand/home/jenny/draft
Thenewlinkappearsinthe/home/alexdirectorywiththefilenameletter.InpracticeAlexmayneedto
changedirectoryandfilepermissionsasshownintheprevioussectionforJennytobeabletoaccessthe
file.
Thelnutilitycreatesanadditionalpointertoanexistingfilebutdoesnotmakeanothercopyofthefile.
Becausethereisonlyonefile,thefilestatusinformationsuchasaccesspermissions,owner,andthetime
thefilewaslastmodifiedisthesameforalllinks.Onlythefilenamesdiffer.WhenJennymodifies
/home/jenny/draft,Alexseesthechangesin/home/alex/letter.
cpVERSUSln
Thefollowingcommandsverifythatlndoesnotmakeanadditionalcopyofafile.Createafile,useln
tomakeanadditionallinktothefile,changethecontentsofthefilethroughonelink,andverifythechange
throughtheotherlink:
$catfile_a
ThisisfileA.
$lnfile_afile_b
$catfile_b
ThisisfileA.
$vimfile_b
...
$catfile_b
ThisisfileBafterthechange.
$catfile_a
ThisisfileBafterthechange.
Ifyoutrythesameexperimentusingcpinsteadoflnandchangeacopyofthefile,thedifference
betweenthetwoutilitieswillbecomeclearer.Onceyouchangeacopyofafile,thetwofilesare
different:
$catfile_c
ThisisfileC.
$cpfile_cfile_d
$catfile_d
ThisisfileC.
$vimfile_d
...
$catfile_d
ThisisfileDafterthechange.
$catfile_c
ThisisfileC.
lsandlinkcounts
Youcanuselswiththeloption,followedbythenamesofthefilesyouwanttocompare,toseethatthe
statusinformationisthesamefortwolinkstothesamefileandisdifferentforfilesthatarenotlinked.In
thefollowingexample,the2inthelinksfield(justtotheleftofalex)showstherearetwolinkstofile_a
andfile_b:
$ls-lfile_afile_bfile_cfile_d
-rw-r--r--2alexpubs33May2410:52file_a
-rw-r--r--2alexpubs33May2410:52file_b
-rw-r--r--1alexpubs16May2410:55file_c
-rw-r--r--1alexpubs33May2410:57file_d
Althoughitiseasytoguesswhichfilesarelinkedtooneanotherinthisexample,lsdoesnotexplicitly
tellyou.
lsandinodes
Uselswiththeioptiontodeterminedefinitivelywhichfilesarelinked.Theioptionliststheinode
(page880)numberforeachfile.Aninodeisthecontrolstructureforafile.Iftwofilenameshavethe
sameinodenumber,theysharethesamecontrolstructureandarelinkstothesamefile.Conversely,when
twofilenameshavedifferentinodenumbers,theyaredifferentfiles.Thefollowingexampleshowsthat
file_aandfile_bhavethesameinodenumberandthatfile_candfile_dhavedifferentinodenumbers:
$ls-ifile_afile_bfile_cfile_d
3534file_a3534file_b5800file_c7328file_d
Alllinkstoafileareofequalvalue:Theoperatingsystemcannotdistinguishtheorderinwhichmultiple
linkswerecreated.Whenafilehastwolinks,youcanremoveeitheroneandstillaccessthefilethrough
theremaininglink.Youcanremovethelinkusedtocreatethefileand,aslongasonelinkremains,still
accessthefilethroughthatlink.
SYMBOLICLINKS
Inadditiontohardlinks,Linuxsupportslinkscalledsymboliclinks,softlinks,orsymlinks.Ahardlinkis
apointertoafile(thedirectoryentrypointstotheinode),whereasasymboliclinkisanindirectpointer
toafile(thedirectoryentrycontainsthepathnameofthepointed-tofileapointertothehardlinktothe
file).
Limitationsofhardlinks
Symboliclinksweredevelopedbecauseofthelimitationsinherentinhardlinks.Youcannotcreateahard
linktoadirectory,butyoucancreateasymboliclinktoadirectory.Asymboliclinkcanpointtoanyfile,
regardlessofwhereitislocatedinthefilestructure,butahardlinktoafilemustbeinthesame
filesystemastheotherhardlink(s)tothefile.
OftentheLinuxfilehierarchyiscomposedofseveralfilesystems.Becauseeachfilesystemkeepsseparate
controlinformation(thatis,separateinodetables)forthefilesitcontains,itisnotpossibletocreatehard
linksbetweenfilesindifferentfilesystems.Whenyoucreatelinksonlyamongfilesinyourown
directories,youwillnotnoticetheselimitations.
Oneofthebigadvantagesofasymboliclinkisthatitcanpointtoanonexistentfile.Thisabilityisuseful
ifyouneedalinktoafilethatisperiodicallyremovedandre-created.Ahardlinkkeepspointingtoa
"removed"file,whichthehardlinkkeepsaliveevenafteranewfileiscreated.Asymboliclinkalways
pointstothenewlycreatedfileanddoesnotinterferewithdeletingtheoldfile.Forexample,asymbolic
linkcouldpointtoafilethatgetscheckedinandoutunderasourcecodecontrolsystem,a.ofilethatis
re-createdbytheCcompilereachtimeyourunmake,oralogfilethatisperiodicallyarchived.
Althoughtheyaremoregeneralthanhardlinks,symboliclinkshavesomedisadvantages.Whereasall
hardlinkstoafilehaveequalstatus,symboliclinksdonothavethesamestatusashardlinks.Whenafile
hasmultiplehardlinks,itisanalogoustoapersonhavingmultiplefulllegalnames,asmanymarried
womendo.Incontrast,symboliclinksareanalogoustonicknames.Anyonecanhaveoneormore
nicknamesbutthesenicknameshavealesserstatusthanlegalnames.Thefollowingsectionsdescribe
someofthepeculiaritiesofsymboliclinks.
ln:CreatesaSymbolicLink
Uselnwiththesymbolic(ors)optiontocreateasymboliclink.Thefollowingexamplecreatesthe
symboliclink/tmp/s3tothefilesuminAlex'shomedirectory.Whenyouusethelslcommandtolookat
thesymboliclink,lsdisplaysthenameofthelinkandthenameofthefileitpointsto.Thefirstcharacter
ofthelistingisl(forlink):
$ln--symbolic/home/alex/sum/tmp/s3
$ls-l/home/alex/sum/tmp/s3
-rw-rw-r--1alexalex38Jun1209:51/home/alex/sum
lrwxrwxrwx1alexalex14Jun1209:52/tmp/s3->/home/alex/sum
$cat/tmp/s3
Thisissum.
Thesizesandtimesofthelastmodificationofthetwofilesaredifferent.Unlikeahardlink,asymbolic
linktoafiledoesnothavethesamestatusinformationasthefileitself.
Similarlyyoucanuselntocreateasymboliclinktoadirectory.Whenyouusethesymbolicoption,ln
doesnotcarewhetherthefileyouarecreatingalinktoisaregularfileoradirectory.
tip:Useabsolutepathnameswithsymboliclinks
Symboliclinksareliteralandarenotawareofdirectories.Alinkthatpointstoarelative
pathname,whichincludessimplefilenames,assumesthattherelativepathnameisrelative
tothedirectorythatthelinkwascreatedin(notthedirectorythelinkwascreatedfrom).In
thefollowingexample,thelinkpointstothefilenamedsuminthe/tmpdirectory.Because
nosuchfileexists,catgivesanerrormessage:
$pwd
/home/alex
$ln--symbolicsum/tmp/s4
$ls-lsum/tmp/s4
lrwxrwxrwx1alexalex3Jun1210:13
/tmp/s4->sum
-rw-rw-r--1alexalex38Jun1209:51sum
$cat/tmp/s4
cat:/tmp/s4:Nosuchfileordirectory

optional:cdANDSYMBOLICLINKS
Whenyouuseasymboliclinkasanargumenttocdtochangedirectories,theresultscanbeconfusing,particularlyifyoudidnot
realizethatyouwereusingasymboliclink.
Ifyouusecdtochangetoadirectorythatisrepresentedbyasymboliclink,thepwdbuiltinliststhenameofthesymboliclink.
Thepwdutility(/bin/pwd)liststhenameofthelinked-todirectory,notthelink,regardlessofhowyougotthere:
$ln-s/home/alex/grades/tmp/grades.old
$pwd
/home/alex
$cd/tmp/grades.old
$pwd
/tmp/grades.old
$/bin/pwd
$/home/alex/grades
Whenyouchangedirectoriesbacktotheparent,youendupinthedirectoryholdingthesymboliclink:
$cd..
$pwd
/tmp
$/bin/pwd
/tmp
rm:RemovesaLink
Whenyoucreateafile,thereisonehardlinktoit.Youcandeletethefileor,usingLinuxterminology,
removethelinkwiththermutility.Whenyouremovethelasthardlinktoafile,youcannolongeraccess
theinformationstoredthereandtheoperatingsystemreleasesforusebyotherfilesthespacethefile
occupiedonthedisk.Thespaceisreleasedevenifsymboliclinkstothefileremain.Whenthereismore
thanonehardlinktoafile,youcanremoveahardlinkandstillaccessthefilefromanyremaininglink.
UnlikeinDOSandWindows,thereisnoeasywayinLinuxtoundeleteafileonceyouhaveremovedit.A
skilledhackercansometimespiecethefiletogetherwithtimeandeffort.
Whenyouremoveallthehardlinkstoafile,youwillnotbeabletoaccessthefilethroughasymbolic
link.Inthefollowingexample,catreportsthatthefiletotaldoesnotexistbecauseitisasymboliclink
toafilethathasbeenremoved:
$ls-lsum
-rw-r--r--1alexpubs981May2411:05sum
$ln-ssumtotal
$rmsum
$cattotal
cat:total:Nosuchfileordirectory
$ls-ltotal
lrwxrwxrwx1alexpubs6May2411:09total->sum
Whenyouremoveafile,besuretoremoveallsymboliclinkstoit.Removeasymboliclinkthesameway
youremoveotherfiles:
$rmtotal
Chaptersummary
Linuxhasahierarchical,ortreelike,filestructurethatmakesitpossibletoorganizefilessothatyoucan
findthemquicklyandeasily.Thisfilestructurecontainsdirectoryfilesandordinaryfiles.Directories
containotherfiles,includingotherdirectories;ordinaryfilesgenerallycontaintext,programs,orimages.
Theancestorofallfilesistherootdirectorynamed/.
Thischapterintroducedmanyimportantsystemfilesanddirectories,explainingwhateachdoes.The
sectiononfiletypesexplainedthedifferencebetweenordinaryanddirectoryfilesandtheinodesthat
holdeach.Italsocoveredtheuseofhardandsymboliclinks.
MostLinuxfilesystemssupport255-characterfilenames.Nonetheless,itisagoodideatokeepfilenames
simpleandintuitive.Filenameextensionscanhelpmakefilenamesmoremeaningful.
Anabsolutepathnamestartswiththerootdirectoryandcontainsallthefilenamesthattraceapathtoa
givenfile.Suchapathnamestartswithaslashrepresentingtherootdirectoryandcontainsadditional
slashesbetweentheotherfilenamesinthepath.
Arelativepathnameissimilartoanabsolutepathnamebutstartsthepathtracingfromtheworking
directory.Asimplefilenameisthelastelementofapathnameandisaformofarelativepathname.
Whenyouareloggedin,youarealwaysassociatedwithaworkingdirectory.Yourhomedirectoryisyour
workingdirectoryfromthetimeyoufirstloginuntilyouusecdtochangedirectories.
ALinuxfilesystemcontainsmanyimportantdirectories,including/usr/bin,whichstoresmostoftheLinux
utilitycommands,and/dev,whichstoresdevicefiles,manyofwhichrepresentphysicalpiecesof
hardware.Animportantstandardfileis/etc/passwd;itcontainsinformationaboutusers,suchastheuser
IDandfullname.
Amongtheattributesassociatedwitheachfileareaccesspermissions.Theydeterminewhocanaccess
thefileandthemannerinwhichthefilemaybeaccessed.Threegroupsofuser(s)canaccessthefile:the
owner,membersofagroup,andallotherusers.Aregularfilecanbeaccessedinthreeways:read,write,
andexecute.Thelsutilitywiththeloptiondisplaysthesepermissions.Fordirectories,executeaccessis
redefinedtomeanthatthedirectorycanbesearched.
TheownerofafileorSuperusercanusethechmodutilitytochangetheaccesspermissionsofafile.
Thisutilitydefinesread,write,andexecutepermissionsforthefile'sowner,thegroup,andallotherusers
onthesystem.
Alinkisapointertoafile.Youcancreateseverallinkstoasinglefilesothatyoucansharethefilewith
otherusersorhavethefileappearinmorethanonedirectory.Becauseonlyonecopyofafilewith
multiplelinksexists,changingthefilethroughanyonelinkcausesthechangestoappearinallthelinks.
Hardlinkscannotlinkdirectoriesorspanfilesystems,whereassymboliclinkscan.
Table4-2liststheutilitiesintroducedinthischapter.

Table4-2.UtilitiesintroducedinChapter4
cd Associatesyouwithanotherworkingdirectory(page82)
chmod Changestheaccesspermissionsonafile(page92)
ln Makesalinktoanexistingfile(page97)
mkdir Createsadirectory(page80)
pwd Displaysthepathnameoftheworkingdirectory(page81)
rmdir Deletesadirectory(page88)
Exercises
1.
Iseachofthefollowinganabsolutepathname,arelativepathname,orasimplefilename?
1. milk_co
2. correspond/business/milk_co
3. /home/alex
4. /home/alex/literature/promo
5. ..
6. letter.0610
2.
Listthecommandsyoucanuseto
1. Makeyourhomedirectorytheworkingdirectory
2. Identifytheworkingdirectory
3.
Ifyourworkingdirectoryis/home/alexwithasubdirectorynamedliterature,givethreesetsofcommandsthatyoucanusetocreate
asubdirectorynamedclassicsunderliterature.Alsogiveseveralsetsofcommandsyoucanusetoremovetheclassicsdirectoryand
itscontents.
4.
Thedfutilitydisplaysallmountedfilesystemsalongwithinformationabouteach.Usethedfutilitywiththeh(humanlyreadable)
optiontoanswerthefollowingquestions.
1. HowmanyfilesystemsareonyourLinuxsystem?
2. Whichfilesystemstoresyourhomedirectory?
3. Assumingthatyouranswertoexercise4aistwoorgreater,attempttocreateahardlinktoafileonanotherfilesystem.What
errormessagedoyouget?Whathappenswhenyouattempttocreateasymboliclinktothefileinstead?
5. Supposethatyouhaveafilethatislinkedtoafileownedbyanotheruser.Whatcanyoudosothatchangestothefilearenolonger
shared?
6.
Youshouldhavereadpermissionforthe/etc/passwdfile.Toanswerthefollowingquestions,usecatorlesstodisplay/etc/passwd.
Lookatthefieldsofinformationin/etc/passwdfortheusersonyoursystem.
1. Whichcharacterisusedtoseparatefieldsin/etc/passwd?
2. Howmanyfieldsareusedtodescribeeachuser?
3. Howmanyusersareonyoursystem?
4. Howmanydifferentloginshellsareinuseonyoursystem?(Hint:Lookatthelastfield.)
5. Thesecondfieldof/etc/passwdstoresuserpasswordsinencodedform.Ifthepasswordfieldcontainsanx,yoursystemuses
shadowpasswordsandstorestheencodedpasswordselsewhere.Doesyoursystemuseshadowpasswords?
7.
If/home/jenny/draftand/home/alex/letterarelinkstothesamefileandthefollowingsequenceofeventsoccurs,whatwillbethe
dateintheopeningoftheletter?
1. Alexgivesthecommandvimletter.
2. Jennygivesthecommandvimdraft.
3. JennychangesthedateintheopeningofthelettertoJanuary31,2006,writesthefile,andexitsfromvim.
4. AlexchangesthedatetoFebruary1,2006,writesthefile,andexitsfromvim.
8.
Supposethatauserbelongstoagroupthathasallpermissionsonafilenamedjobs_list,buttheuser,astheownerofthefile,hasno
permissions.Describewhatoperations,ifany,theuser/ownercanperformonjobs_list.
Whichcommandcantheuser/ownergivethatwillgranttheuser/ownerallpermissionsonthefile?
9. Doestherootdirectoryhaveanysubdirectoriesthatyoucannotsearch?Doestherootdirectoryhaveanysubdirectoriesthatyoucannot
read?Explain.
10.
AssumethatyouaregiventhedirectorystructureshowninFigure4-2onpage77andthefollowingdirectorypermissions:
d--x--x---3jennypubs512Mar1015:16business
drwxr-xr-x2jennypubs512Mar1015:16business/milk_co
Foreachcategoryofpermissionsowner,group,andotherwhathappenswhenyouruneachofthefollowingcommands?Assumethat
theworkingdirectoryistheparentofcorrespondandthatthefilecheese_coisreadablebyeveryone.
1. cdcorrespond/business/milk_co
2. lslcorrespond/business
3. catcorrespond/business/cheese_co
ADVANCEDEXERCISES
11. Whatisaninode?Whathappenstotheinodewhenyoumoveafilewithinafilesystem?
12. Whatdoesthe..entryinadirectorypointto?Whatdoesthisentrypointtointheroot(/)directory?
13. Howcanyoucreateafilenamedi?Whichtechniquesdonotwork,andwhydotheynotwork?Howcanyouremovethefilenamedi?
14.
Supposethattheworkingdirectorycontainsasinglefilenamedandor.Whaterrormessagedoyougetwhenyourunthefollowing
commandline?
$mvandorand\/or
Underwhatcircumstancesisitpossibletorunthecommandwithoutproducinganerror?
15. Thelsicommanddisplaysafilenameprecededbytheinodenumberofthefile(page99).Writeacommandtooutputinode/filename
pairsforthefilesintheworkingdirectory,sortedbyinodenumber.(Hint:Useapipe.)
16. Doyouthinkthatthesystemadministratorhasaccesstoaprogramthatcandecodeuserpasswords?Whyorwhynot(seeexercise6)?
17. Isitpossibletodistinguishafilefromahardlinktoafile?Thatis,givenafilename,canyoutellwhetheritwascreatedusinganln
command?Explain.
18.
Explaintheerrormessagesdisplayedinthefollowingsequenceofcommands:
$ls-l
total1
drwxrwxr-x2alexpubs1024Mar217:57dirtmp
$lsdirtmp
$rmdirdirtmp
rmdir:dirtmp:Directorynotempty
$rmdirtmp/*
rm:Nomatch.
Chapter5.TheShell
INTHISCHAPTER
TheCommandLine108
StandardInputandStandardOutput113
Redirection116
Pipes122
RunningaProgramintheBackground125
kill:AbortingaBackgroundJob127
FilenameGeneration/PathnameExpansion127
Builtins132
Thischaptertakesacloselookattheshellandexplainshowtousesomeofitsfeatures.Forexample,it
discussescommandlinesyntaxandalsodescribeshowtheshellprocessesacommandlineandinitiates
executionofaprogram.Thechapteralsoexplainshowtoredirectinputtoandoutputfromacommand,
constructpipesandfiltersonthecommandline,andrunacommandinthebackground.Thefinalsection
coversfilenameexpansionandexplainshowyoucanusethisfeatureinyoureverydaywork.
ExceptasnotedeverythinginthischapterappliestotheBourneAgain(bash)andTC(tcsh)Shells.
Theexactwordingoftheshelloutputdiffersfromshelltoshell:Whatyourshelldisplaysmaydiffer
slightlyfromwhatappearsinthisbook.Forshell-specificinformation,refertoChapters8(bash)and9
(tcsh).Chapter11coverswritingandexecutingbashshellscripts.
TheCommandLine
Theshellexecutesaprogramwhenyougiveitacommandinresponsetoitsprompt.Forexample,when
yougivethelscommand,theshellexecutestheutilityprogramnamedls.Youcancausetheshellto
executeothertypesofprogramssuchasshellscripts,applicationprograms,andprogramsyouhave
writteninthesameway.Thelinethatcontainsthecommand,includinganyarguments,iscalledthe
commandline.Inthisbookthetermcommandreferstothecharactersyoutypeonthecommandlineas
wellastotheprogramthatactioninvokes.
Syntax
Commandlinesyntaxdictatestheorderingandseparationoftheelementsonacommandline.Whenyou
presstheRETURNkeyafterenteringacommand,theshellscansthecommandlineforpropersyntax.The
syntaxforabasiccommandlineis
command[arg1][arg2]...[argn]RETURN
OneormoreSPACEsmustseparateelementsonthecommandline.Thecommandisthenameofthe
command,arg1throughargnarearguments,andRETURNisthekeystrokethatterminatesallcommand
lines.Thebracketsinthecommandlinesyntaxindicatethattheargumentstheyencloseareoptional.Not
allcommandsrequirearguments:Somecommandsdonotallowarguments;othercommandsallowa
variablenumberofarguments;andothersrequireaspecificnumberofarguments.Options,aspecialkind
ofargument,areusuallyprecededbyoneortwohyphens(alsocalledadashorminussign:).
CommandName
Usagemessage
SomeusefulLinuxcommandlinesconsistofonlythenameofthecommandwithoutanyarguments.For
example,lsbyitselfliststhecontentsoftheworkingdirectory.Mostcommandsacceptoneormore
arguments.Commandsthatrequireargumentstypicallygiveashorterrormessage,calledausage
message,whenyouusethemwithoutarguments,withincorrectarguments,orwiththewrongnumberof
arguments.
Arguments
Onthecommandlineeachsequenceofnonblankcharactersiscalledatokenorword.Anargumentisa
token,suchasafilename,stringoftext,number,orotherobjectthatacommandactson.Forexample,the
argumenttoavimoremacscommandisthenameofthefileyouwanttoedit.
Thefollowingcommandlineshowscpcopyingthefilenamedtemptotempcopy:
$cptemptempcopy
Argumentsarenumberedstartingwiththecommanditselfasargumentzero.Inthisexamplecpis
argumentzero,tempisargumentone,andtempcopyisargumenttwo.Thecputilityrequirestwo
argumentsonthecommandline.(Theutilitycantakemoreargumentsbutnotfewer;seepage616.)
Argumentoneisthenameofanexistingfile.Argumenttwoisthenameofthefilethatcpiscreatingor
overwriting.Heretheargumentsarenotoptional;bothargumentsmustbepresentforthecommandto
work.Whenyoudonotsupplytherightnumberorkindofarguments,cpdisplaysausagemessage.Try
typingcpandthenpressingRETURN.
Options
Anoptionisanargumentthatmodifiestheeffectsofacommand.Youcanfrequentlyspecifymorethan
oneoption,modifyingthecommandinseveraldifferentways.Optionsarespecifictoandinterpretedby
theprogramthatthecommandlinecalls,nottheshell.
Byconventionoptionsareseparateargumentsthatfollowthenameofthecommandandusuallyprecede
otherarguments,suchasfilenames.Mostutilitiesrequireyoutoprefixoptionswithasinglehyphen.
However,thisrequirementisspecifictotheutilityandnottheshell.GNUprogramoptionsarefrequently
precededbytwohyphensinarow.Forexample,helpgeneratesa(sometimesextensive)usagemessage.
Figure5-1firstshowswhathappenswhenyougiveanlscommandwithoutanyoptions.Bydefaultls
liststhecontentsoftheworkingdirectoryinalphabeticalorder,verticallysortedincolumns.Nextther
(reverseorder;becausethisisaGNUutility,youcanalsousereverse)optioncausesthelsutilityto
displaythelistoffilesinreversealphabeticalorder,stillsortedincolumns.Thexoptioncauseslsto
displaythelistoffilesinhorizontallysortedrows.
Combiningoptions
Whenyouneedtouseseveraloptions,youcanusuallygroupmultiplesingle-letteroptionsintoone
argumentthatstartswithasinglehyphen;donotputSPACEsbetweentheoptions.Youcannotcombine
optionsthatareprecededbytwohyphensinthisway,however.Specificrulesforcombiningoptions
dependontheprogramyouarerunning.Figure5-1showsboththerandxoptionswiththelsutility.
Togethertheseoptionsgeneratealistoffilenamesinhorizontallysortedcolumns,inreversealphabetical
order.Mostutilitiesallowyoutolistoptionsinanyorder;thuslsxrproducesthesameresultsaslsrx.
Thecommandlsxralsogeneratesthesamelist.
Figure5-1.Usingoptions
$ls
alexhousemarkofficepersonaltest
holdjennynamesoldstufftemp
$ls-r
testpersonalofficemarkhousealex
tempoldstuffnamesjennyhold
$ls-x
alexholdhousejennymarknames
officeoldstuffpersonaltemptest
$ls-rx
testtemppersonaloldstuffofficenames
markjennyhouseholdalex
tip:Displayingreadablefilesizes:thehoption
Mostutilitiesthatreportonfilesizesspecifythesizeofafileinbytes.Bytesworkwell
whenyouaredealingwithsmallerfiles,butthenumberscanbedifficulttoreadwhenyou
areworkingwithfilesizesthataremeasuredinmegabytesorgigabytes.Usetheh(or
human-readable)optiontodisplayfilesizesinkilo-,mega-,andgigabytes.Experiment
withdfh(diskfree)andlslhcommands.
Optionarguments
Someutilitieshaveoptionsthatthemselvesrequirearguments.Forexample,thegccutilityhasao
optionthatmustbefollowedbythenameyouwanttogivetheexecutablefilethatgccgenerates.
TypicallyanargumenttoanoptionisseparatedfromitsoptionletterbyaSPACE:
$gcc-oprogprog.c
Argumentsthatstartwithahyphen
Anotherconventionallowsutilitiestoworkwitharguments,suchasfilenames,thatstartwithahyphen.If
afile'snameisl,thefollowingcommandisambiguous:
$ls-l
Thiscommandcouldmeanalonglistingofallfilesintheworkingdirectoryoralistingofthefilenamed
l.Itisinterpretedastheformer.Youshouldavoidcreatingfileswhosenamesbeginwithhyphens.Ifyou
docreatethem,manyutilitiesfollowtheconventionthataargument(twoconsecutivehyphens)indicates
theendoftheoptions(andthebeginningofthearguments).Todisambiguatethecommand,youcantype
$ls---l
Youcanuseanalternativeformatinwhichtheperiodreferstotheworkingdirectoryandtheslash
indicatesthatthenamereferstoafileintheworkingdirectory:
$ls./-l
Assumingthatyouareworkinginthe/home/alexdirectory,theprecedingcommandisfunctionally
equivalentto
$ls/home/alex/-l
Youcangivethefollowingcommandtogetalonglistingofthisfile:
$ls-l---l
Theseareconventions,nothard-and-fastrules,andanumberofutilitiesdonotfollowthem(e.g.,find).
Followingsuchconventionsisagoodidea;itmakesitmucheasierforuserstoworkwithyourprogram.
Whenyouwriteshellprogramsthatrequireoptions,followtheLinuxoptionconventions.
tip:Thehelpoption
Manyutilitiesdisplaya(sometimesextensive)helpmessagewhenyoucallthemwithan
argumentofhelp.AllGNUutilitiesacceptthisoption.Anexamplefollows.
$bzip2--help
bzip2,ablock-sortingfilecompressor.Version1.0.2,30-
Dec-2001.
usage:bzip2[flagsandinputfilesinanyorder]
-h--helpprintthismessage
-d--decompressforcedecompression
-z--compressforcecompression
-k--keepkeep(don'tdelete)inputfiles
-f--forceoverwriteexistingoutputfiles
-t--testtestcompressedfileintegrity
-c--stdoutoutputtostandardout
-q--quietsuppressnoncriticalerrormessages
-v--verbosebeverbose(a2nd-vgivesmore)
...
ProcessingtheCommandLine
Asyouenteracommandline,theLinuxttydevicedriver(partoftheLinuxoperatingsystemkernel)
examineseachcharactertoseewhetheritmusttakeimmediateaction.WhenyoupressCONTROL-H(to
eraseacharacter)orCONTROL-U(tokillaline),thedevicedriverimmediatelyadjuststhecommand
lineasrequired;theshellneverseesthecharacter(s)youerasedorthelineyoukilled.Oftenasimilar
adjustmentoccurswhenyoupressCONTROL-W(toeraseaword).Whenthecharacteryouentereddoes
notrequireimmediateaction,thedevicedriverstoresthecharacterinabufferandwaitsforadditional
characters.WhenyoupressRETURN,thedevicedriverpassesthecommandlinetotheshellfor
processing.
Parsingthecommandline
Whentheshellprocessesacommandline,itlooksatthelineasawholeandparses(breaks)itintoits
componentparts(Figure5-2).Nexttheshelllooksforthenameofthecommand.Usuallythenameofthe
commandisthefirstitemonthecommandlineaftertheprompt(argumentzero).Theshelltakesthefirst
charactersonthecommandlineuptothefirstblank(TABorSPACE)andthenlooksforacommandwith
thatname.Thecommandname(thefirsttoken)canbespecifiedonthecommandlineeitherasasimple
filenameorasapathname.Forexample,youcancallthelscommandineitherofthefollowingways:
$ls
$/bin/ls
Figure5-2.Processingthecommandline


optional
Theshelldoesnotrequirethatthenameoftheprogramappearfirstonthecommandline.Thusyoucanstructureacommandline
asfollows:
$>bb<aacat
Thiscommandrunscatwithstandardinputcomingfromthefilenamedaaandstandardoutputgoingtothefilenamedbb.When
theshellrecognizestheredirectsymbols(page116),itrecognizesandprocessesthemandtheirargumentsbeforefindingthename
oftheprogramthatthecommandlineiscalling.Thisisaproperlystructuredalbeitrarelyencounteredandpossibly
confusingcommandline.
Absoluteversusrelativepathnames
Whenyougiveanabsolutepathnameonthecommandlineorarelativepathnamethatisnotasimple
filename(i.e.,anypathnamethatincludesatleastoneslash),theshelllooksinthespecifieddirectory
(/bininthecaseofthe/bin/lscommand)forafilethathasthenamelsandthatyouhavepermissionto
execute.Whenyougiveasimplefilename,theshellsearchesthroughalistofdirectoriesforafilename
thatmatchesthespecifiednameandthatyouhaveexecutepermissionfor.Theshelldoesnotlookthrough
alldirectoriesbutonlytheonesspecifiedbythevariablenamedPATH.Refertopage284(bash)or
page363(tcsh)formoreinformationonPATH.Alsorefertothediscussionofthewhichandwhereis
utilitiesonpage61.
Whenitcannotfindtheexecutablefile,theBourneAgainShell(bash)displaysamessagesuchasthe
following:
$abc
bash:abc:commandnotfound
Onereasontheshellmaynotbeabletofindtheexecutablefileisthatitisnotinadirectoryinyour
PATH.Underbashthefollowingcommandtemporarilyaddstheworkingdirectory(.)toyourPATH:
$PATH=$PATH:.
Forsecurityreasons,youmaynotwanttoaddtheworkingdirectorytoPATHpermanently;seethetipon
page285.
Whentheshellfindstheprogrambutcannotexecuteit(youdonothaveexecutepermissionforthefile
thatcontainstheprogram),itdisplaysamessagesimilarto
$def
bash:./def:Permissiondenied
See"lsl:DisplaysPermissions"onpage91forinformationondisplayingaccesspermissionsforafile
and"chmod:ChangesAccessPermissions"onpage92forinstructionsonhowtochangefileaccess
permissions.
ExecutingtheCommandLine
Process
Ifitfindsanexecutablefilewiththesamenameasthecommand,theshellstartsanewprocess.Aprocess
istheexecutionofacommandbyLinux(page292).Theshellmakeseachcommandlineargument,
includingoptionsandthenameofthecommand,availabletothecalledprogram.Whilethecommandis
executing,theshellwaitsfortheprocesstofinish.Atthispointtheshellisinaninactivestatecalled
sleep.Whentheprogramfinishesexecution,itpassesitsexitstatus(page479)totheshell.Theshellthen
returnstoanactivestate(wakesup),issuesaprompt,andwaitsforanothercommand.
Theshelldoesnotprocessarguments
Becausetheshelldoesnotprocesscommandlineargumentsbutonlyhandsthemtothecalledprogram,
theshellhasnowayofknowingwhetheraparticularoptionorotherargumentisvalidforagiven
program.Anyerrororusagemessagesaboutoptionsorargumentscomefromtheprogramitself.Some
utilitiesignorebadoptions.

StandardInputandStandardOutput
Standardoutputisaplacethataprogramcansendinformation,suchastext.Theprogramnever"knows"
wheretheinformationitsendstostandardoutputisgoing(Figure5-3).Theinformationcangotoa
printer,anordinaryfile,orthescreen.
Figure5-3.Thecommanddoesnotknowwherestandardinputcomesfromorwhere
standardoutputandstandarderrorgo
Thefollowingsectionsshowthatbydefaulttheshelldirectsstandardoutputfromacommandtothe
screen[1]anddescribehowyoucancausetheshelltoredirectthisoutputtoanotherfile.
[1]Thetermscreenisusedthroughoutthisbooktomeanscreen,terminalemulatorwindow,orworkstation.Screenreferstothe
devicethatyouseethepromptandmessagesdisplayedon.
Standardinputisaplacethataprogramgetsinformationfrom.Aswithstandardoutputtheprogram
never"knows"wheretheinformationcamefrom.Thefollowingsectionsalsoexplainhowtoredirect
standardinputtoacommandsothatitcomesfromanordinaryfileinsteadoffromthekeyboard(the
default).
Inadditiontostandardinputandstandardoutput,arunningprogramnormallyhasaplacetosenderror
messages:standarderror.Refertopage260(bash)andpage349(tcsh)formoreinformationon
handlingstandarderror.
tip:chsh:changesyourloginshell
Thepersonwhosetsupyouraccountdetermineswhichshellyouwillusewhenyoufirst
loginonthesystemorwhenyouopenaterminalemulatorwindowinaGUIenvironment.
Youcanrunanyshellyoulikeonceyouareloggedin.Enterthenameoftheshellyouwant
touse(bashortcsh)andpressRETURN;thenextpromptwillbethatofthenewshell.
Giveanexitcommandtoreturntothepreviousshell.Becauseshellsyoucallinthis
mannerarenested(onerunsontopoftheother),youwillbeabletologoutonlyfromyour
originalshell.Whenyouhavenestedseveralshells,keepgivingexitcommandsuntilyou
reachyouroriginalshell.Youwillthenbeabletologout.
Usethechshutilitywhenyouwanttochangeyourloginshellpermanently.Firstgivethe

commandchsh.Theninresponsetothepromptsenteryourpasswordandtheabsolute
pathnameoftheshellyouwanttouse(/bin/bashor/bin/tcsh).Whenyouchangeyourlogin
shellinthismannerusingaterminalemulatorPAGEunderaGUI,subsequentterminal
emulatorwindowswillnotreflectthechangeuntilyoulogoutthesystemandlogbackin.
TheScreenasaFile
Chapter4introducedordinaryfiles,directoryfiles,andhardandsoftlinks.Linuxhasanadditionaltype
offile:adevicefile.AdevicefileresidesintheLinuxfilestructure,usuallyinthe/devdirectory,and
representsaperipheraldevice,suchasaterminalemulatorwindow,screen,printer,ordiskdrive.
Thedevicenamethatthewhoutilitydisplaysafteryourloginnameisthefilenameofyourscreen.For
example,whenwhodisplaysthedevicenamepts/4,thepathnameofyourscreenis/dev/pts/4.Whenyou
workwithmultiplewindows,eachwindowhasitsowndevicename.Youcanalsousethettyutilityto
displaythenameofthedevicethatyougivethecommandfrom.Althoughyouwouldnotnormallyhave
occasiontodoso,youcanreadfromandwritetothisfileasthoughitwereatextfile.Writingtoit
displayswhatyouwroteonthescreen;readingfromitreadswhatyouenteredonthekeyboard.
TheKeyboardandScreenasStandardInputandStandard
Output
Whenyoufirstlogin,theshelldirectsstandardoutputofyourcommandstothedevicefilethatrepresents
yourscreen(Figure5-4).Directingoutputinthismannercausesittoappearonyourscreen.Theshell
alsodirectsstandardinputtocomefromthesamefile,sothatyourcommandsreceiveasinputanything
youtypeonyourkeyboard.
Figure5-4.Bydefault,standardinputcomesfromthekeyboardandstandardoutput
goestothescreen
cat
Thecatutilityprovidesagoodexampleofthewaythekeyboardandthescreenfunctionasstandard
inputandstandardoutput,respectively.Whenyouusecat,itcopiesafiletostandardoutput.Becausethe
shelldirectsstandardoutputtothescreen,catdisplaysthefileonthescreen.
Uptothispointcathastakenitsinputfromthefilename(argument)youspecifiedonthecommandline.
Whenyoudonotgivecatanargument(thatis,whenyougivethecommandcatfollowedimmediately
byRETURN),cattakesitsinputfromstandardinput.Thus,whencalledwithoutanargument,cat
copiesstandardinputtostandardoutput,onelineatatime.
Toseehowcatworks,typecatandpressRETURNinresponsetotheshellprompt.Nothinghappens.
EnteralineoftextandpressRETURN.Thesamelineappearsjustundertheoneyouentered.Thecat
utilityisworking.Becausetheshellassociatescat'sstandardinputwiththekeyboardandcat's
standardoutputwiththescreen,whenyoutypealineoftextcatcopiesthetextfromstandardinput(the
keyboard)tostandardoutput(thescreen).ThisexchangeisshowninFigure5-5.
Figure5-5.Thecatutilitycopiesstandardinputtostandardoutput
$cat
Thisisalineoftext.
Thisisalineoftext.
Catkeepscopyinglinesoftext
Catkeepscopyinglinesoftext
untilyoupressCONTROL-Datthebeginning
untilyoupressCONTROL-Datthebeginning
ofaline.
ofaline.
CONTROL-D
$

CONTROL-DsignalsEOF
ThecatutilitykeepscopyingtextuntilyouenterCONTROL-Donalinebyitself.PressingCONTROL-
DsendsanEOF(endoffile)signaltocattoindicatethatithasreachedtheendofstandardinputand
thereisnomoretextforittocopy.Thecatutilitythenfinishesexecutionandreturnscontroltotheshell,
whichdisplaysaprompt.
Redirection
Thetermredirectionencompassesthevariouswaysyoucancausetheshelltoalterwherestandardinput
ofacommandcomesfromandwherestandardoutputgoesto.Bydefaulttheshellassociatesstandard
inputandstandardoutputofacommandwiththekeyboardandthescreenasmentionedearlier.Youcan
causetheshelltoredirectstandardinputorstandardoutputofanycommandbyassociatingtheinputor
outputwithacommandorfileotherthanthedevicefilerepresentingthekeyboardorthescreen.This
sectiondemonstrateshowtoredirectinputfromandoutputtoordinarytextfilesandutilities.
RedirectingStandardOutput
Theredirectoutputsymbol(>)instructstheshelltoredirecttheoutputofacommandtothespecifiedfile
insteadoftothescreen(Figure5-6).Theformatofacommandlinethatredirectsoutputis
command[arguments]>filename
Figure5-6.Redirectingstandardoutput
wherecommandisanyexecutableprogram(suchasanapplicationprogramorautility),argumentsare
optionalarguments,andfilenameisthenameoftheordinaryfiletheshellredirectstheoutputto.
Figure5-7usescattodemonstrateoutputredirection.ThisfigurecontrastswithFigure5-3onpage114,
wherebothstandardinputandstandardoutputareassociatedwiththekeyboardandthescreen.Theinput
inFigure5-7comesfromthekeyboard.Theredirectoutputsymbolonthecommandlinecausestheshell
toassociatecat'sstandardoutputwiththesample.txtfilespecifiedonthecommandline.
AftergivingthecommandandtypingthetextshowninFigure5-7,thesample.txtfilecontainsthetextyou
entered.Youcanusecatwithanargumentofsample.txttodisplaythisfile.Thenextsectionshows
anotherwaytousecattodisplaythefile.
caution:RedirectingoutputcandestroyafileI
Usecautionwhenyouredirectoutputtoafile.Ifthefileexists,theshellwilloverwriteit
anddestroyitscontents.Formoreinformation,seethe"Redirectingoutputcandestroya
fileII"cautiononpage120.
Figure5-7showsthatredirectingtheoutputfromcatisahandywaytocreateafilewithoutusingan
editor.ThedrawbackisthatonceyouenteralineandpressRETURN,youcannoteditthetext.Whileyou
areenteringaline,theeraseandkillkeysworktodeletetext.Thisprocedureisusefulformakingshort,
simplefiles.
Figure5-7.catwithitsoutputredirected
$cat>sample.txt
Thistextisbeingenteredatthekeyboardand
catiscopyingittoafile.
PressCONTROL-Dtoindicatethe
endoffile.
CONTROL-D
$
Figure5-8.Usingcattocatenatefiles
$catstationery
2,000sheetsletterheadordered:10/7/05
$cattape
1boxmaskingtapeordered:10/14/05
5boxesfilamenttapeordered:10/28/05
$catpens
12doz.blackpensordered:10/4/05
$catstationerytapepens>supply_orders
$catsupply_orders
2,000sheetsletterheadordered:10/7/05
1boxmaskingtapeordered:10/14/05
5boxesfilamenttapeordered:10/28/05
12doz.blackpensordered:10/4/05
$
Figure5-8showshowtousecatandtheredirectoutputsymboltocatenate(joinoneaftertheotherthe
derivationofthenameofthecatutility)severalfilesintoonelargerfile.Thefirstthreecommands
displaythecontentsofthreefiles:stationery,tape,andpens.Thenextcommandshowscatwiththree
filenamesasarguments.Whenyoucallitwithmorethanonefilename,catcopiesthefiles,oneatatime,
tostandardoutput.Inthiscasestandardoutputisredirectedtothefilesupply_orders.Thefinalcat
commandshowsthatsupply_orderscontainsthecontentsofallthreefiles.
RedirectingStandardInput
Justasyoucanredirectstandardoutput,soyoucanredirectstandardinput.Theredirectinputsymbol(<)
instructstheshelltoredirectacommand'sinputtocomefromthespecifiedfileinsteadoffromthe
keyboard(Figure5-9).Theformatofacommandlinethatredirectsinputis
command[arguments]<filename
Figure5-9.Redirectingstandardinput

wherecommandisanyexecutableprogram(suchasanapplicationprogramorautility),argumentsare
optionalarguments,andfilenameisthenameoftheordinaryfiletheshellredirectstheinputfrom.
Figure5-10showscatwithitsinputredirectedfromthesupply_ordersfilethatwascreatedinFigure
5-8andstandardoutputgoingtothescreen.Thissetupcausescattodisplaythesamplefileonthe
screen.ThesystemautomaticallysuppliesanEOF(endoffile)signalattheendofanordinaryfile.
Figure5-10.catwithitsinputredirected
$cat<supply_orders
2,000sheetsletterheadordered:10/7/05
1boxmaskingtapeordered:10/14/05
5boxesfilamenttapeordered:10/28/05
12doz.blackpensordered:10/4/05
Utilitiesthattakeinputfromafileorstandardinput
Givingacatcommandwithinputredirectedfromafileyieldsthesameresultasgivingacatcommand
withthefilenameasanargument.ThecatutilityisamemberofaclassofLinuxutilitiesthatfunctionin
thismanner.Othermembersofthisclassofutilitiesincludelpr,sort,andgrep.Theseutilitiesfirst
examinethecommandlinethatyouusetocallthem.Ifyouincludeafilenameonthecommandline,the
utilitytakesitsinputfromthefileyouspecify.Ifyoudonotspecifyafilename,theutilitytakesitsinput
fromstandardinput.Itistheutilityorprogramnottheshelloroperatingsystemthatfunctionsinthis
manner.
noclobber:AvoidsOverwritingFiles
Theshellprovidesafeaturecallednoclobberthatstopsyoufrominadvertentlyoverwritinganexisting
fileusingredirection.Whenyouenablethisfeaturebysettingthenoclobbervariableandthenattemptto
redirectoutputtoanexistingfile,theshelldisplaysanerrormessageanddoesnotexecutethecommand.
Iftheprecedingexamplesresultinoneofthefollowingmessages,thenoclobberfeaturehasbeenset.The
followingexamplessetnoclobber,attempttoredirecttheoutputfromechointoanexistingfile,andthen
unsetnoclobberunderbashandtcsh:
bash$set-onoclobber
$echo"hithere">tmp
bash:tmp:Cannotoverwriteexistingfile
$set+onoclobber
$echo"hithere">tmp
$
tcshtcsh$setnoclobber
tcsh$echo"hithere">tmp
tmp:Fileexists.
tcsh$unsetnoclobber
tcsh$echo"hithere">tmp
$
Youcanoverridenoclobberbyputtingapipesymbol(tcshusesanexclamationpoint)afterthesymbol
youuseforredirectingoutput(>|).
Inthefollowingexample,theuserfirstcreatesafilenamedabyredirectingtheoutputofdatetothe
file.Nexttheusersetsthenoclobbervariableandtriesredirectingoutputtoaagain.Theshellreturnsan
errormessage.Thentheusertriesthesamethingbutusingapipesymbolaftertheredirectsymbol.This
timetheshellallowstheusertooverwritethefile.Finally,theuserunsetsnoclobber(usingaplussignin
placeofthehyphen)andverifiesthatitisnolongerset.
$date>a
$set-onoclobber
$date>a
bash:a:Cannotoverwriteexistingfile
$date>|a
$set+onoclobber
$date>a
Formoreinformationonusingnoclobberundertcsh,refertopage367.
caution:RedirectingoutputcandestroyafileII
Dependingonwhichshellyouareusingandhowyourenvironmenthasbeensetup,a
commandsuchasthefollowingmaygiveyouundesiredresults:
$catorangepear>orange
cat:orange:inputfileisoutputfile
Althoughcatdisplaysanerrormessage,theshellgoesaheadanddestroysthecontentsof
theexistingorangefile.Theneworangefilewillhavethesamecontentsaspearbecause
thefirstactiontheshelltakeswhenitseestheredirectionsymbol(>)istoremovethe
contentsoftheoriginalorangefile.Ifyouwanttocatenatetwofilesintoone,usecatto
putthetwofilesintoatemporaryfileandthenusemvtorenamethisthirdfile:
$catorangepear>temp
$mvtemporange
Whathappensinthenextexamplecanbeevenworse.Theusergivingthecommandwants
tosearchthroughfilesa,b,andcforthewordappleandredirecttheoutputfromgrep
(page48)tothefilea.output.Unfortunatelytheuserentersthefilenameasaoutput,
omittingtheperiodandinsertingaSPACEinitsplace:
$grepappleabc>aoutput
grep:output:Nosuchfileordirectory
Theshellobedientlyremovesthecontentsofaandthencallsgrep.Theerrormessage
maytakeamomenttoappear,givingyouasensethatthecommandisrunningcorrectly.
Evenafteryouseetheerrormessage,itmaytakeawhiletorealizethatyoudestroyedthe
contentsofa.
AppendingStandardOutputtoaFile
Theappendoutputsymbol(>>)causestheshelltoaddnewinformationtotheendofafile,leavingany
existinginformationintact.Thissymbolprovidesaconvenientwayofcatenatingtwofilesintoone.The
followingcommandsdemonstratetheactionoftheappendoutputsymbol.Thesecondcommand
accomplishesthecatenationdescribedintheprecedingcautionbox:
$catorange
thisisorange
$catpear>>orange
$catorange
thisisorange
thisispear
Youfirstseethecontentsoftheorangefile.Nextthecontentsofthepearfileisaddedtotheendof
(catenatedwith)theorangefile.Thefinalcatshowstheresult.
caution:Donottrustnoclobber
Appendingoutputissimplerthanthetwo-stepproceduredescribedinthepreceding
cautionboxbutyoumustbecarefultoincludebothgreaterthansigns.Ifyouaccidentally
useonlyoneandthenoclobberfeatureisnoton,youwilloverwritetheorangefile.Even
ifyouhavethenoclobberfeatureturnedon,itisagoodideatokeepbackupcopiesoffiles
youaremanipulatinginthesewaysincaseyoumakeamistake.
Althoughitprotectsyoufrommakinganerroneousredirection,noclobberdoesnotstop
youfromoverwritinganexistingfileusingcpormv.Theseutilitiesincludethei
(interactive)optionthathelpsprotectyoufromthistypeofmistakebyverifyingyour
intentionswhenyoutrytooverwriteafile.Formoreinformation,seethe"cpcandestroya
file"tiponpage46.
Thenextexampleshowshowtocreateafilethatcontainsthedateandtime(theoutputfromdate),
followedbyalistofwhoisloggedin(theoutputfromwho).ThefirstlineinFigure5-11redirectsthe
outputfromdatetothefilenamedwhoson.Thencatdisplaysthefile.Nexttheexampleappendsthe
outputfromwhotothewhosonfile.Finallycatdisplaysthefilecontainingtheoutputofbothutilities.
Figure5-11.Redirectingandappendingoutput
$date>whoson
$catwhoson
ThuMar2414:31:18PST2005
$who>>whoson
$catwhoson
ThuMar2414:31:18PST2005
rootconsoleMar2405:00(:0)
alexpts/4Mar2412:23(:0.0)
alexpts/5Mar2412:33(:0.0)
jennypts/7Mar2308:45(bravo.example.com)
/dev/null:MakingDataDisappear
The/dev/nulldeviceisadatasink,commonlyreferredtoasabitbucket.Youcanredirectoutputthat
youdonotwanttokeeporseeto/dev/null.Theoutputdisappearswithoutatrace:
$echo"hithere">/dev/null
$
Whenyoureadfrom/dev/null,yougetanullstring.Givethefollowingcatcommandtotruncateafile
namedmessagestozerolengthwhilepreservingtheownershipandpermissionsofthefile:
$ls-lmessages
-rw-r--r--1alexpubs25315Oct2410:55messages
$cat/dev/null>messages
$ls-lmessages
-rw-r--r--1alexpubs0Oct2411:02messages
Pipes
Theshellusesapipetoconnectstandardoutputofonecommanddirectlytostandardinputofanother
command.Apipe(sometimesreferredtoasapipeline)hasthesameeffectasredirectingstandardoutput
ofonecommandtoafileandthenusingthatfileasstandardinputtoanothercommand.Apipedoesaway
withseparatecommandsandtheintermediatefile.Thesymbolforapipeisaverticalbar(|).Thesyntax
ofacommandlineusingapipeis
command_a[arguments]|command_b[arguments]
Theprecedingcommandlineusesapipetogeneratethesameresultasthefollowinggroupofcommand
lines:
command_a[arguments]>temp
command_b[arguments]<temp
rmtemp
Intheprecedingsequenceofcommands,thefirstlineredirectsstandardoutputfromcommand_atoan
intermediatefilenamedtemp.Thesecondlineredirectsstandardinputforcommand_btocomefrom
temp.Thefinallinedeletestemp.Thecommandusingapipeisnotonlyeasiertotype,butisgenerally
moreefficientbecauseitdoesnotcreateatemporaryfile.
tr
YoucanuseapipewithanyoftheLinuxutilitiesthatacceptinputeitherfromafilespecifiedonthe
commandlineorfromstandardinput.Youcanalsousepipeswithcommandsthatacceptinputonlyfrom
standardinput.Forexample,thetr(translate)utility(page804)takesitsinputfromstandardinputonly.
Initssimplestusagetrhasthefollowingformat:
trstring1string2
Thetrutilityacceptsinputfromstandardinputandlooksforcharactersthatmatchoneofthecharacters
instring1.Uponfindingamatch,trtranslatesthematchedcharacterinstring1tothecorresponding
characterinstring2.(Thefirstcharacterinstring1translatesintothefirstcharacterinstring2,andso
forth.)Thetrutilitysendsitsoutputtostandardoutput.Inbothofthefollowingexamples,trdisplays
thecontentsoftheabstractfilewiththelettersa,b,andctranslatedintoA,B,andC,respectively:
$catabstract|trabcABC
$trabcABC<abstract
TheTRutilitydoesnotchangethecontentsoftheoriginalfile;itcannotchangetheoriginalfilebecauseit
doesnot"know"thesourceofitsinput.
lpr
Thelpr(lineprinter)utilityalsoacceptsinputfromeitherafileorstandardinput.Whenyoutypethe
nameofafilefollowinglpronthecommandline,itplacesthatfileintheprintqueue.Whenyoudonot
specifyafilenameonthecommandline,lprtakesinputfromstandardinput.Thisfeatureenablesyouto
useapipetoredirectinputtolpr.ThefirstsetofcommandsinFigure5-12showshowyoucanusels
andlprwithanintermediatefile(temp)tosendalistofthefilesintheworkingdirectorytotheprinter.
Ifthetempfileexists,thefirstcommandoverwritesitscontents.Thesecondsetofcommandssendsthe
samelist(withtheexceptionoftemp)totheprinterusingapipe.
ThecommandsinFigure5-13redirecttheoutputfromthewhoutilitytotempandthendisplaythisfilein
sortedorder.Thesortutility(page50)takesitsinputfromthefilespecifiedonthecommandlineor,
whenafileisnotspecified,fromstandardinputandsendsitsoutputtostandardoutput.Thesort
commandlineinFigure5-13takesitsinputfromstandardinput,whichisredirected(<)tocomefrom
temp.Theoutputthatsortsendstothescreenliststheusersinsorted(alphabetical)order.
Becausesortcantakeitsinputfromstandardinputorfromafilenameonthecommandline,omittingthe
<symbolfromFigure5-13yieldsthesameresult.
Figure5-12.Apipe
$ls>temp
$lprtemp
$rmtemp
or
$ls|lpr
Figure5-13.Usingatemporaryfiletostoreintermediateresults
$who>temp
$sort<temp
alexpts/4Mar2412:23
alexpts/5Mar2412:33
jennypts/7Mar2308:45
rootconsoleMar2405:00
$rmtemp
Figure5-14achievesthesameresultwithoutcreatingthetempfile.Usingapipetheshellredirectsthe
outputfromwhototheinputofsort.Thesortutilitytakesinputfromstandardinputbecauseno
filenamefollowsitonthecommandline.
Whenmanypeopleareusingthesystemandyouwantinformationaboutonlyoneofthem,youcansend
theoutputfromwhotogrep(page48)usingapipe.Thegreputilitydisplaysthelinecontainingthe
stringyouspecifyrootinthefollowingexample:
$who|grep'root'
rootconsoleMar2405:00
Anotherwayofhandlingoutputthatistoolongtofitonthescreen,suchasalistoffilesinacrowded
directory,istouseapipetosendtheoutputthroughlessormore(bothonpage45).
$ls|less
Thelessutilitydisplaystextonescreenatatime.Toviewanotherscreen,presstheSPACEbar.To
viewonemoreline,pressRETURN.Presshforhelpandqtoquit.
Filters
Afilterisacommandthatprocessesaninputstreamofdatatoproduceanoutputstreamofdata.A
commandlinethatincludesafilterusesapipetoconnectstandardoutputofonecommandtothefilter's
standardinput.Anotherpipeconnectsthefilter'sstandardoutputtostandardinputofanothercommand.
Notallutilitiescanbeusedasfilters.
Inthefollowingexample,sortisafilter,takingstandardinputfromstandardoutputofwhoandusinga
pipetoredirectstandardoutputtostandardinputoflpr.Thiscommandlinesendsthesortedoutputof
whototheprinter:
$who|sort|lpr
TheprecedingexampledemonstratesthepoweroftheshellcombinedwiththeversatilityofLinux
utilities.Thethreeutilitieswho,sort,andlprwerenotspecificallydesignedtoworkwitheachother,
buttheyallusestandardinputandstandardoutputintheconventionalway.Byusingtheshelltohandle
inputandoutput,youcanpiecestandardutilitiestogetheronthecommandlinetoachievetheresultsyou
want.
Figure5-14.Apipedoingtheworkofatemporaryfile
$who|sort
alexpts/4Mar2412:23
alexpts/5Mar2412:33
jennypts/7Mar2308:45
rootconsoleMar2405:00
tee:SendsOutputinTwoDirections
Theteeutilitycopiesitsstandardinputbothtoafileandtostandardoutput.Theutilityisaptlynamed:It
takesasingleinputandsendstheoutputintwodirections.InFigure5-15theoutputofwhoissentviaa
pipetostandardinputoftee.Theteeutilitysavesacopyofstandardinputinafilenamedwho.outand
alsosendsacopytostandardoutput.Standardoutputofteegoesviaapipetostandardinputofgrep,
whichdisplayslinescontainingthestringroot.
RunningaProgramintheBackground
Foreground
Inalltheexamplessofarinthisbook,commandswererunintheforeground.Whenyourunacommandin
theforeground,theshellwaitsforittofinishbeforegivingyouanotherpromptandallowingyouto
continue.Whenyourunacommandinthebackground,youdonothavetowaitforthecommandtofinish
beforeyoustartrunninganothercommand.
Jobs
Ajobisaseriesofoneormorecommandsthatcanbeconnectedbypipes.Youcanhaveonlyone
foregroundjobinawindoworonascreen,butyoucanhavemanybackgroundjobs.Byrunningmorethan
onejobatatime,youareusingoneofLinux'simportantfeatures:multitasking.Runningacommandinthe
backgroundcanbeusefulwhenthecommandwillrunforalongtimeanddoesnotneedsupervision.It
leavesthescreenfreesothatyoucanuseitforotherwork.Ofcourse,whenyouareusingaGUI,youcan
openanotherwindowtorunanotherjob.
Jobnumber,PIDnumber
Torunacommandinthebackground,typeanampersand(&)justbeforetheRETURNthatendsthe
commandline.Theshellassignsasmallnumbertothejobanddisplaysthisjobnumberbetween
brackets.Followingthejobnumber,theshelldisplaystheprocessidentification(PID)numberalarger
numberassignedbytheoperatingsystem.Eachofthesenumbersidentifiesthecommandrunninginthe
background.Thentheshelldisplaysanotherpromptandyoucanenteranothercommand.Whenthe
backgroundjobfinishesrunning,theshelldisplaysamessagegivingboththejobnumberandthe
commandlineusedtorunthecommand.
Figure5-15.Usingtee
$who|teewho.out|greproot
rootconsoleMar2405:00
$catwho.out
rootconsoleMar2405:00
alexpts/4Mar2412:23
alexpts/5Mar2412:33
jennypts/7Mar2308:45
ThefollowingexamplesusetheBourneAgainShell.TheTCShellproducesalmostidenticalresults.The
nextexamplerunsinthebackgroundandsendsitsoutputthroughapipetolpr,whichsendsittothe
printer.
$ls-l|lpr&
[1]22092
$
The[1]followingthecommandlineindicatesthattheshellhasassignedjobnumber1tothisjob.The
22092isthePIDnumberofthefirstcommandinthejob.(TheTCShellshowsPIDnumbersforall
commandsinthejob.)Whenthisbackgroundjobcompletesexecution,youseethemessage
[1]+Donels-l|lpr
(Inplaceoflsl,theshellmaydisplaysomethingsimilartolscolor=ttyl.Thisdifferenceisduetothe
factthatlsisaliased[page312]tolscolor=tty.)
MovingaJobfromtheForegroundtotheBackground
CONTROL-Z
Youcansuspendaforegroundjob(stopitfromrunning)bypressingthesuspendkey,usuallyCONTROL-
Z.Theshellthenstopstheprocessanddisconnectsstandardinputfromthekeyboard.Youcanputa
suspendedjobinthebackgroundandrestartitbyusingthebgcommandfollowedbythejobnumber.You
donotneedtousethejobnumberwhenthereisonlyonestoppedjob.
Onlytheforegroundjobcantakeinputfromthekeyboard.Toconnectthekeyboardtoaprogramrunning
inthebackground,youmustbringitintotheforeground.Typefgwithoutanyargumentswhenonlyonejob
isinthebackground.Whenmorethanonejobisinthebackground,typefg,orapercentsign(%),
followedbythenumberofthejobyouwanttobringintotheforeground.Theshelldisplaysthecommand
youusedtostartthejob(promptmeinthefollowingexample),andyoucanenteranyinputtheprogram
requirestocontinue:
bash$fg1
promptme
Redirecttheoutputofajobyouruninthebackgroundtokeepitfrominterferingwithwhateveryouare
doingonthescreen.Referto"SeparatingandGroupingCommands"onpage267formoredetailabout
backgroundtasks.
kill:AbortingABackgroundJob
Theinterruptkey(usuallyCONTROL-C)cannotabortaprocessyouarerunninginthebackground;you
mustusekill(page693)forthispurpose.FollowkillonthecommandlinewitheitherthePIDnumber
oftheprocessyouwanttoabortorapercentsign(%)followedbythejobnumber.
DeterminingaPIDnumberwithps
IfyouforgetthePIDnumber,youcanusetheps(processstatus)utility(page293)todisplayit.Usingthe
TCShell,thefollowingexamplerunsatailfoutfilecommand(thefoptioncausestailtowatchoutfile
anddisplaynewlinesastheyarewrittentothefile)asabackgroundjob,usespstodisplaythePID
numberoftheprocess,andabortsthejobwithkill.Thesamecommandsworkunderbash.Sothatit
doesnotinterferewithanythingonthescreen,themessagesayingthatthejobisterminateddoesnot
appearuntilyoupressRETURNaftertheRETURNthatendsthekillcommand:
tcsh$tail-foutfile&
[1]22170
tcsh$ps|greptail
22170pts/700:00:00tail
tcsh$kill22170
tcsh$RETURN
[1]Terminatedtail-foutfile
tcsh$
Ifyouforgetthejobnumber,youcanusethejobscommandtodisplayalistofjobnumbers.Thenext
exampleissimilartothepreviousonebutusesthejobnumberinsteadofthePIDnumbertokillthejob:
tcsh$tail-foutfile&
[1]3339
tcsh$bigjob&
[2]3340
tcsh$jobs
[1]+Runningtail-foutfile
[2]-Runningbigjob
tcsh$kill%1[1]Terminatedtail-foutfile
tcsh$
FilenameGeneration/PathnameExpansion
Wildcards,globbing
Whenyougivetheshellabbreviatedfilenamesthatcontainspecialcharacters,alsocalled
metacharacters,theshellcangeneratefilenamesthatmatchthenamesofexistingfiles.Thesespecial
charactersarealsoreferredtoaswildcardsbecausetheyactasthejokersdoinadeckofcards.When
oneofthesecharactersappearsinanargumentonthecommandline,theshellexpandsthatargumentin
sortedorderintoalistoffilenamesandpassesthelisttotheprogramthatthecommandlinecalls.
Filenamesthatcontainthesespecialcharactersarecalledambiguousfilereferencesbecausetheydonot
refertoanyonespecificfile.Theprocessthattheshellperformsonthesefilenamesiscalledpathname
expansionorglobbing.
Ambiguousfilereferencesrefertoagroupoffileswithsimilarnamesquickly,savingyoutheeffortof
typingthenamesindividually.Theycanalsohelpyoufindafilewhosenameyoudonotrememberinits
entirety.Ifnofilenamematchestheambiguousfilereference,theshellgenerallypassestheunexpanded
referencespecialcharactersandalltothecommand.
The?SpecialCharacter
Thequestionmark(?)isaspecialcharacterthatcausestheshelltogeneratefilenames.Itmatchesany
singlecharacterinthenameofanexistingfile.Thefollowingcommandusesthisspecialcharacterinan
argumenttothelprutility:
$lprmemo?
Theshellexpandsthememo?argumentandgeneratesalistoffilesintheworkingdirectorythathave
namescomposedofmemofollowedbyanysinglecharacter.Theshellthenpassesthislisttolpr.The
lprutilitynever"knows"thattheshellgeneratedthefilenamesitwascalledwith.Ifnofilenamematches
theambiguousfilereference,theshellpassesthestringitself(memo?)tolpror,ifitissetuptodoso,
passesanullstring(seenullglob,page322).
Thefollowingexampleuseslsfirsttodisplaythenamesofallfilesintheworkingdirectoryandthento
displaythefilenamesthatmemo?matches:
$ls
memmemo12memo9memoalexnewmemo5
memomemo5memoamemos
$lsmemo?
memo5memo9memoamemos
Thememo?ambiguousfilereferencedoesnotmatchmem,memo,memo12,memoalex,ornewmemo5.
Youcanalsouseaquestionmarkinthemiddleofanambiguousfilereference:
$ls
7may4reportmay4reportmayqreportmay_report
may14reportmay4report.79mayreportmay.report
$lsmay?report
may.reportmay4reportmay_reportmayqreport
Topracticegeneratingfilenames,youcanuseechoandls.Theechoutilitydisplaystheargumentsthat
theshellpassestoit:
$echomay?report
may.reportmay4reportmay_reportmayqreport
Theshellfirstexpandstheambiguousfilereferenceintoalistofallfilesintheworkingdirectorythat
matchthestringmay?reportandthenpassesthislisttoecho,asthoughyouhadenteredthelistof
filenamesasargumentstoecho.Nextechodisplaysthelistoffilenames.
Aquestionmarkdoesnotmatchaleadingperiod(onethatindicatesaninvisiblefilename;seepage80).
Whenyouwanttomatchfilenamesthatbeginwithaperiod,youmustexplicitlyincludetheperiodinthe
ambiguousfilereference.
The*SpecialCharacter
Theasterisk(*)performsafunctionsimilartothatofthequestionmarkbutmatchesanynumberof
characters,includingzerocharacters,inafilename.Thefollowingexampleshowsallofthefilesinthe
workingdirectoryandthenshowsthreecommandsthatdisplayallthefilenamesthatbeginwiththestring
memo,endwiththestringmo,andcontainthestringalx:
$ls
amemomemomemoalx.0620memosallyuser.memo
memmemo.0612memoalx.keepsallymemo
memalxmemoamemorandumtypescript
$echomemo*
memomemo.0612memoamemoalx.0620memoalx.keepmemorandummemosally
$echo*mo
amemomemosallymemouser.memo
$echo*alx*
memalxmemoalx.0620memoalx.keep
Theambiguousfilereferencememo*doesnotmatchamemo,mem,sallymemo,oruser.memo.Likethe
questionmark,anasteriskdoesnotmatchaleadingperiodinafilename.
Theaoptioncauseslstodisplayinvisiblefilenames.Thecommandecho*doesnotdisplay.(the
workingdirectory),..(theparentoftheworkingdirectory),.aaa,or.profile.Incontrast,thecommand
echo.*displaysonlythosefournames:
$ls
aaamemo.sallysally.0612thurs
memo.0612reportsaturday
$ls-a
..aaaaaamemo.sallysally.0612thurs
...profilememo.0612reportsaturday
$echo*
aaamemo.0612memo.sallyreportsally.0612saturdaythurs
$echo.*
....aaa.profile
Inthefollowingexample.p*doesnotmatchmemo.0612,private,reminder,orreport.Nextthels.*
commandcauseslstolist.privateand.profileinadditiontothecontentsofthe.directory(theworking
directory)andthe..directory(theparentoftheworkingdirectory).Whencalledwiththesameargument,
echodisplaysthenamesoffiles(includingdirectories)intheworkingdirectorythatbeginwithadot(.),
butnotthecontentsofdirectories.
$ls-a
..privatememo.0612reminder
...profileprivatereport
$echo.p*
.private.profile
$ls.*
.private.profile
.:
memo.0612privatereminderreport
..:
.
.
$echo.*
....private.profile
Youcantakeadvantageofambiguousfilereferenceswhenyouestablishconventionsfornamingfiles.For
example,whenyouendalltextfilenameswith.txt,youcanreferencethatgroupoffileswith*.txt.The
nextcommandusesthisconventiontosendallthetextfilesintheworkingdirectorytotheprinter.The
ampersandcauseslprtoruninthebackground.
$lpr*.txt&
The[]SpecialCharacters
Apairofbracketssurroundingalistofcharacterscausestheshelltomatchfilenamescontainingthe
individualcharacters.Whereasmemo?matchesmemofollowedbyanycharacter,memo[17a]ismore
restrictive,andmatchesonlymemo1,memo7,andmemoa.Thebracketsdefineacharacterclassthat
includesallthecharacterswithinthebrackets.(GNUcallsthisacharacterlist;aGNUcharacterclass
issomethingdifferent.)Theshellexpandsanargumentthatincludesacharacter-classdefinition,by
substitutingeachmemberofthecharacterclass,oneatatime,inplaceofthebracketsandtheircontents.
Theshellthenpassesthelistofmatchingfilenamestotheprogramitiscalling.
Eachcharacter-classdefinitioncanreplaceonlyasinglecharacterwithinafilename.Thebracketsand
theircontentsarelikeaquestionmarkthatsubstitutesonlythemembersofthecharacterclass.
Thefirstofthefollowingcommandsliststhenamesofallthefilesintheworkingdirectorythatbegin
witha,e,i,o,oru.Thesecondcommanddisplaysthecontentsofthefilesnamedpage2.txt,page4.txt,
page6.txt,andpage8.txt.
$echo[aeiou]*
...
$lesspage[2468].txt
...
Ahyphenwithinbracketsdefinesarangeofcharacterswithinacharacter-classdefinition.Forexample,
[69]represents[6789],[az]representsalllowercaselettersinEnglish,and[azAZ]representsallletters,
bothuppercaseandlowercase,inEnglish.
Thefollowingcommandlinesshowthreewaystoprintthefilesnamedpart0,part1,part2,part3,and
part5.Eachofthesecommandlinescausestheshelltocalllprwithfivefilenames:
$lprpart0part1part2part3part5
$lprpart[01235]
$lprpart[0-35]
Thefirstcommandlineexplicitlyspecifiesthefivefilenames.Thesecondandthirdcommandlinesuse
ambiguousfilereferences,incorporatingcharacter-classdefinitions.Theshellexpandstheargumenton
thesecondcommandlinetoincludeallfilesthathavenamesbeginningwithpartandendingwithanyof
thecharactersinthecharacterclass.Thecharacterclassisexplicitlydefinedas0,1,2,3,and5.The
thirdcommandlinealsousesacharacter-classdefinitionbutdefinesthecharacterclasstobeall
charactersintherange03plus5.
Thefollowingcommandlineprints39files,part0throughpart38:
$lprpart[0-9]part[12][0-9]part3[0-8]
Thenexttwoexampleslistthenamesofsomeofthefilesintheworkingdirectory.Thefirstliststhefiles
whosenamesstartwithathroughm.Thesecondlistsfileswhosenamesendwithx,y,orz.
$echo[a-m]*
...
$echo*[x-z]
...

optional
Whenanexclamationpoint(!)oracaret(^)immediatelyfollowstheopeningbracket([)thatdefinesacharacterclass,thestring
enclosedbythebracketsmatchesanycharacternotbetweenthebrackets.Thus[^ab]*matchesanyfilenamethatdoesnotbegin
withaorb.
Thefollowingexamplesshowthat*[^ab]matchesfilenamesthatdonotendwiththelettersaorbandthat[b-d]*matches
filenamesthatbeginwithb,c,ord.
$ls
aaabacadbabbbcbdccdd
$ls*[^ab]
acadbcbdccddccdd
$ls[b-d]*
babbbcbdccdd
Youcanmatchahyphen()oraclosingbracket(])byplacingitimmediatelybeforethefinalclosingbracket.
Thenextexampledemonstratesthatthelsutilitycannotinterpretambiguousfilereferences.Firstlsis
calledwithanargumentof?old.Theshellexpands?oldintoamatchingfilename,hold,andpassesthat
nametols.Thesecondcommandisthesameasthefirst,exceptthe?isquoted(referto"Special
Characters"onpage42).Theshelldoesnotrecognizethisquestionmarkasaspecialcharacterand
passesitontols.Thelsutilitygeneratesanerrormessagesayingthatitcannotfindafilenamed?old
(becausethereisnofilenamed?old).
$ls?old
hold
$ls\?old
ls:?old:Nosuchfileordirectory
Likemostutilitiesandprograms,lscannotinterpretambiguousfilereferences;thatworkislefttothe
shell.
tip:Theshellexpandsambiguousfilereferences
Theshelldoestheexpansionwhenitprocessesanambiguousfilereference,notthe
programthattheshellruns.Intheexamplesinthissection,theutilities(ls,cat,echo,
lpr)neverseetheambiguousfilereferences.Theshellexpandstheambiguousfile
referencesandpassesalistofordinaryfilenamestotheutility.Inthepreviousexamples,
echoshowsthistobetruebecauseitsimplydisplaysitsarguments;itneverdisplaysthe
ambiguousfilereference.
Builtins
Abuiltinisautility(alsocalledacommand)thatisbuiltintoashell.Eachoftheshellshasitsownsetof
builtins.Whenitrunsabuiltin,theshelldoesnotforkanewprocess.Consequentlybuiltinsrunmore
quicklyandcanaffecttheenvironmentofthecurrentshell.Becausebuiltinsareusedinthesamewayas
utilities,youwillnottypicallybeawareofwhetherautilityisbuiltintotheshellorisastand-alone
utility.
Theechoutilityisashellbuiltin.Theshellalwaysexecutesashellbuiltinbeforetryingtofinda
commandorutilitywiththesamename.Seepage487foranin-depthdiscussionofbuiltincommands,
page500foralistofbashbuiltins,andpage377foralistoftcshbuiltins.
Listingbashbuiltins
Togetacompletelistofbashbuiltins,givethecommandinfobashbuiltin.Todisplayapagewithmore
informationoneachbuiltin,movethecursortooneofthelineslistingabuiltincommandandpress
RETURN.Alternatively,aftertypinginfobash,givethecommand/builtintosearchthebash
documentationforthestringbuiltin.ThecursorwillrestonthewordBuiltininamenu;pressRETURNto
displaythebuiltinsmenu.
BecausebashwaswrittenbyGNU,theinfopagehasbetterinformationthandoesthemanpage.If
youwanttoreadaboutbuiltinsinthemanpage,givethecommandmanbashandthensearchforthe
sectiononbuiltinswiththecommand/^SHELLBUILTINCOMMANDS(searchforalinethatbegins
withSHELL...).
Listingtcshbuiltins
Fortcsh,givethecommandmantcshtodisplaythetcshmanpageandthensearchforthesecond
occurrenceofBuiltincommandswiththefollowingtwocommands:/Builtincommands(searchforthe
string)andn(searchforthenextoccurrenceofthestring).

ChapterSummary
TheshellistheLinuxcommandinterpreter.Itscansthecommandlineforpropersyntax,pickingoutthe
commandnameandanyarguments.Thefirstargumentisargumentone,thesecondisargumenttwo,andso
on.Thenameofthecommanditselfisargumentzero.Manyprogramsuseoptionstomodifytheeffectsof
acommand.MostLinuxutilitiesidentifyanoptionbyitsleadingoneortwohyphens.
Whenyougiveitacommand,theshelltriestofindanexecutableprogramwiththesamenameasthe
command.Whenitdoes,theshellexecutestheprogram.Whenitdoesnot,theshelltellsyouthatitcannot
findorexecutetheprogram.Ifthecommandisasimplefilename,theshellsearchesthedirectoriesgiven
inthevariablePATHinanattempttolocatethecommand.
Whenitexecutesacommand,theshellassignsonefiletothecommand'sstandardinputandanotherfileto
itsstandardoutput.Bydefaulttheshellcausesacommand'sstandardinputtocomefromthekeyboardand
itsstandardoutputtogotothescreen.Youcaninstructtheshelltoredirectacommand'sstandardinput
fromorstandardoutputtoanyfileordevice.Youcanalsoconnectstandardoutputofonecommandto
standardinputofanothercommandusingapipe.Afilterisacommandthatreadsitsstandardinputfrom
standardoutputofonecommandandwritesitsstandardoutputtostandardinputofanothercommand.
Whenacommandrunsintheforeground,theshellwaitsforittofinishbeforeitdisplaysapromptand
allowsyoutocontinue.Whenyouputanampersand(&)attheendofacommandline,theshellexecutes
thecommandinthebackgroundanddisplaysanotherpromptimmediately.Runslowcommandsinthe
backgroundwhenyouwanttoenterothercommandsattheshellprompt.Thejobsbuiltindisplaysalist
ofjobsandincludesthejobnumberofeach.
Theshellinterpretsspecialcharactersonacommandlinetogeneratefilenames.Aquestionmark
representsanysinglecharacter,andanasteriskrepresentszeroormorecharacters.Asinglecharacter
mayalsoberepresentedbyacharacterclass:alistofcharacterswithinbrackets.Areferencethatuses
specialcharacters(wildcards)toabbreviatealistofoneormorefilenamesiscalledanambiguousfile
reference.
Abuiltinisautilitythatisbuiltintoashell.Eachshellhasitsownsetofbuiltins.Whenitrunsabuiltin,
theshelldoesnotforkanewprocess.Consequentlybuiltinsrunmorequicklyandcanaffectthe
environmentofthecurrentshell.
UtilitiesandBuiltinsIntroducedinThisChapter
Table5-1liststheutilitiesintroducedinthischapter.
Table5-1.Newutilities
Utility Function
Exercises
1: Whatdoestheshellordinarilydowhileacommandisexecuting?Whatshouldyoudoifyoudonotwanttowaitforacommandto
finishbeforerunninganothercommand?
2:
Usingsortasafilter,rewritethefollowingsequenceofcommands:
$sortlist>temp
$lprtemp
$rmtemp
3: WhatisaPIDnumber?Whyarethesenumbersusefulwhenyourunprocessesinthebackground?WhichutilitydisplaysthePID
numbersofthecommandsyouarerunning?
4:
Assumethatthefollowingfilesareintheworkingdirectory:
$ls
intronotesbref2section1section3section4b
notesaref1ref3section2section4asentrev
Givecommandsforeachofthefollowing,usingwildcardstoexpressfilenameswithasfewcharactersaspossible.
1. Listallfilesthatbeginwithsection.
2. Listthesection1,section2,andsection3filesonly.
3. Listtheintrofileonly.
4. Listthesection1,section3,ref1,andref3files.
5:
RefertothedocumentationofutilitiesinPartVorthemanpagestodeterminewhichcommandswill
1. OutputthenumberoflinesinthestandardinputthatcontainthewordaorA.
2. Outputonlythenamesofthefilesintheworkingdirectorythatcontainthepattern$(.
3. Listthefilesintheworkingdirectoryintheirreversealphabeticalorder.
4. Sendalistoffilesintheworkingdirectorytotheprinter,sortedbysize.
6:
Giveacommandto
1. Redirectthestandardoutputfromasortcommandintoafilenamedphone_list.Assumethattheinputfileisnamednumbers.
2. Translatealloccurrencesofthecharacters[and{tothecharacter(,andalloccurrencesofthecharacters]and}tothe
character)inthefilepermdemos.c.(Hint:Refertotronpage804.)
3. Createafilenamedbookthatcontainsthecontentsoftwootherfiles:part1andpart2.
7:
Thelprandsortutilitiesacceptinputeitherfromafilenamedonthecommandlineorfromstandardinput.
1. Nametwootherutilitiesthatfunctioninasimilarmanner.
2. Nameautilitythatacceptsitsinputonlyfromstandardinput.
8:
Giveanexampleofacommandthatusesgrep
1. Withbothinputandoutputredirected.
2. Withonlyinputredirected.
3. Withonlyoutputredirected.
4. Withinapipe.
Inwhichoftheprecedingisgrepusedasafilter?
9:
Explainthefollowingerrormessage.Whatfilenameswouldasubsequentlsdisplay?
$ls
abcabdabeabfabgabh
$rmabcab*
rm:cannotremove'abc':Nosuchfileordirectory
AdvancedExercises
10. Whenyouusetheredirectoutputsymbol(>)withacommand,theshellcreatestheoutputfileimmediately,beforethecommandis
executed.Demonstratethatthisistrue.
11.
Inexperimentingwithshellvariables,AlexaccidentallydeleteshisPATHvariable.HedecidesthathedoesnotneedthePATHvariable.
Discusssomeoftheproblemshemaysoonencounterandexplainthereasonsfortheseproblems.HowcouldheeasilyreturnPATHto
itsoriginalvalue?
12.
Assumethatyourpermissionsallowyoutowritetoafilebutnottodeleteit.
1. Giveacommandtoemptythefilewithoutinvokinganeditor.
2. Explainhowyoumighthavepermissiontomodifyafilethatyoucannotdelete.
13. Ifyouaccidentallycreateafilenamethatcontainsanonprintingcharacter,suchasaCONTROLcharacter,howcanyourenamethefile?
14. Whydoesthenoclobbervariablenotprotectyoufromoverwritinganexistingfilewithcpormv?
15.
WhydocommandnamesandfilenamesusuallynothaveembeddedSPACEs?HowwouldyoucreateafilenamecontainingaSPACE?
Howwouldyouremoveit?(Thisisathoughtexercise,notrecommendedpractice.Ifyouwanttoexperiment,createandworkina
directorythatcontainsonlyyourexperimentalfile.)
16.
Createafilenamedanswerandgivethefollowingcommand:
$>answers.0102<answerscat
Explainwhatthecommanddoesandwhy.Whatisamoreconventionalwayofexpressingthiscommand?
Chapter6.ThevimEditor
INTHISCHAPTER
Tutorial:CreatingandEditingaFilewithvim141
IntroductiontovimFeatures148
OnlineHelp149
CommandMode:MovingtheCursor154
InputMode158
CommandMode:DeletingandChangingText160
SearchingandSubstituting164
Yank,Put,andDeleteCommands171
TheGeneral-PurposeBuffer171
ReadingandWritingFiles174
The.vimrcStartupFile176
Thischapterbeginswithahistoryanddescriptionofvi,theoriginal,powerful,sometimescryptic,
interactive,visuallyorientedtexteditor.Thechaptercontinueswithatutorialthatexplainshowtouse
vim(viimprovedaviclonesuppliedwithoravailableformostLinuxdistributions)tocreateandedit
afile.Muchofthetutorialandthebalanceofthechapterapplytoviandotherviclones.Followingthe
tutorial,thechapterdelvesintothedetailsofmanyvimcommandsandexplainshowtouseparametersto
customizevimtomeetyourneeds.Itconcludeswithaquickreference/summaryofvimcommands.The
vimhomepageiswww.vim.org.
History
Beforeviwasdeveloped,thestandardUNIXsystemeditorwased(stillavailableonmostLinux
systems),aline-orientededitorthatmadeitdifficulttoseethecontextofyourediting.Nextcameex,[1]a
supersetofed.Themostnotableadvantagethatexhasoveredisadisplay-editingfacilitythatallows
youtoworkwithafullscreenoftextinsteadofjustaline.Whileusingex,youcanbringupthedisplay-
editingfacilitybygivingavi(Visualmode)command.Peopleusedthisdisplay-editingfacilityso
extensivelythatthedevelopersofexmadeitpossibletostarttheeditorwiththedisplay-editingfacility
alreadyrunning,withouthavingtostartexandthengiveavicommand.Appropriatelytheynamedthe
programvi.YoucancalltheVisualmodefromex,andyoucangobacktoexwhileyouareusingvi.
Startbyrunningex;giveavicommandtoswitchtoVisualmode,andgiveaQcommandwhileinVisual
modetouseex.Giveaquitcommandtoexitfromex.
[1]Theexprogramisusuallyalinktovi,whichisaversionofvimonsomesystems.
viclones
Linuxoffersanumberofversions,orclones,ofvi.ThemostpopularviclonesfoundonLinuxare
elvis(elvis.the-little-red-haired-girl.org),nvi(animplementationoftheoriginalvieditor,
www.bostic.com/vi),vile(dickey.his.com/vile/vile.html),andvim(www.vim.org).Eachcloneoffers
additionalfeaturesbeyondthoseprovidedwiththeoriginalvi.
Theexamplesinthisbookarebasedonvim.SeveralLinuxdistributionssupportmultipleversionsof
vim.Forexample,RedHatprovides/bin/vi,aminimalbuildofvimthatiscompactandfastertoload
butoffersfewerfeatures,and/usr/bin/vim,afull-featuredversionofvim.
Ifyouuseoneoftheclonesotherthanvim,orviitself,youmaynoticeslightdifferencesfromthe
examplespresentedinthischapter.Thevimeditoriscompatiblewithalmostallvicommandsandruns
onmanyplatforms,includingWindows,Macintosh,OS/2,UNIX,andLinux.Refertothevimhomepage
(www.vim.org)formoreinformationandaveryusefulTipssection.
Whatvimisnot
Thevimeditorisnotatextformattingprogram.Itdoesnotjustifymarginsorprovidetheoutput
formattingfeaturesofasophisticatedwordprocessingsystemsuchasOpenOffice.orgWriter.Rather,
vimisasophisticatedtexteditormeanttobeusedtowritecode(C,HTML,Java,andsoon),shortnotes,
andinputtoatextformattingsystem,suchasgrofforTRoff.Youcanusefmt(page664)todo
minimalformattingonatextfilethatyoucreatewithvim.
Readingthischapter
Becausevimissolargeandpowerful,thischapterdescribesonlysomeofitsfeatures.Nonetheless,if
vimiscompletelynewtoyou,youmayfindeventhislimitedsetofcommandsoverwhelming.Thevim
editorprovidesavarietyofwaystoaccomplishanyspecifiededitingtask.Ausefulstrategyforlearning
vimistobeginbylearningasubsetofcommandstoaccomplishbasiceditingtasks.Then,asyoubecome
morecomfortablewiththeeditor,youcanlearnothercommandsthatenableyoutodothingsmorequickly
andefficiently.Thefollowingtutorialsectionintroducesabasicbutusefulsetofvimcommandsand
featuresthatcreateandeditafile.
Tutorial:CreatingandEditingaFilewithvim
Thissectionexplainshowtostartvim,entertext,movethecursor,correcttext,savethefiletothedisk,
andexitfromvim.Thetutorialdiscussestwoofthemodesofoperationofvimandexplainshowto
switchfromonemodetotheother.
vimtutor
Inadditiontoworkingwiththistutorial,youmaywanttotryvim'stutor,namedvimtutor:Giveits
nameasacommandtorunit.
Specifyingaterminal
Becausevimtakesadvantageoffeaturesthatarespecifictovariouskindsofterminals,youmusttellit
whattypeofterminalorterminalemulatoryouareusing.Onmanysystems,andusuallywhenyouworkon
aterminalemulator,yourterminaltypeissetautomatically.Ifyouneedtospecifyyourterminaltype,refer
to"SpecifyingaTerminal"onpage844.
tip:Thevicommandrunsvim
Onsomesystemsthecommandvirunsaminimalbuildofvimthatiscompactandfasterto
loadthanvimbutincludesfewerfeatures.See"ThecompatibleParameter"onpage148
forinformationonrunningviminvicompatiblemode.
Startingvim
Startvimwiththefollowingcommandlinetocreateandeditafilenamedpractice:
$vimpractice
WhenyoupressRETURN,thecommandlinedisappears,andthescreenlookssimilartotheoneshownin
Figure6-1.

Figure6-1.Startingvim
Thetildes(~)attheleftofthescreenindicatethatthefileisempty.Theydisappearasyouaddlinesof
texttothefile.Ifyourscreenlookslikeadistortedversionoftheoneshown,yourterminaltypeis
probablynotsetcorrectly.
Ifyoustartvimwithaterminaltypethatisnotintheterminfodatabase,vimdisplaysanerrormessage
andtheterminaltypedefaultstoansi,whichworksonmanyterminals.Inthefollowingexample,theuser
mistypedvt100andsettheterminaltypetovg100:
Terminalentrynotfoundinterminfo
'vg100'notknown.Availablebuiltinterminalsare:
builtin_riscos
builtin_amiga
builtin_beos-ansi
builtin_ansi
builtin_pcansi
builtin_win32
builtin_vt320
builtin_vt52
builtin_xterm
builtin_iris-ansi
builtin_debug
builtin_dumb
defaultingto'ansi'
Ifyouwanttoresettheterminaltype,pressESCAPEandthengivethefollowingcommandtoexitfrom
vimandgettheshellpromptback:
:q!
Whenyouenterthecolon(:),vimmovesthecursortothebottomlineofthescreen.Thecharactersq!tell
vimtoquitwithoutsavingyourwork.(Youwillnotordinarilyexitfromvimthiswaybecauseyou
typicallywanttosaveyourwork.)YoumustpressRETURNafteryougivethiscommand.Onceyouget
theshellpromptback,referto"SpecifyingaTerminal"onpage844,andthenstartvimagain.
Ifyoustartitwithoutafilename,vimassumesthatyouareanoviceandtellsyouhowtogetstarted
(Figure6-2).
Figure6-2.Startingvimwithoutafilename

Thepracticefileisnewsoitdoesnotcontainanytext.Thevimeditordisplaysamessagesimilartothe
oneshowninFigure6-1onthestatus(bottom)lineoftheterminaltoshowthatyouarecreatingand
editinganewfile.Whenyoueditanexistingfile,vimdisplaysthefirstfewlinesofthefileandgives
statusinformationaboutthefileonthestatusline.
CommandandInputModes
Twoofvim'smodesofoperationareCommandmode(alsocalledNormalmode)andInputmode
(Figure6-3).WhilevimisinCommandmode,youcangivevimcommands.Forexample,youcan
deletetextorexitfromvim.YoucanalsocommandvimtoenterInputmode.InInputmode,vimaccepts
anythingyouenterastextanddisplaysitonthescreen.PressESCAPEtoreturnvimtoCommandmode.
Figure6-3.Modesinvim

Bydefaultthevimeditorkeepsyouinformedaboutwhichmodeitisin.YouwillseeINSERTatthe
lower-leftcornerofthescreenwhilevimisinInsertmode.
Thefollowingcommandcausesvimtodisplaylinenumbersnexttothetextyouareediting:
:setnumberRETURN
LastLinemode
Thecolon(:)intheprecedingcommandputsvimintoanothermode,LastLinemode.Whileinthis
mode,vimkeepsthecursoronthebottomlineofthescreen.Whenyoufinishenteringthecommandby
pressingRETURN,vimrestoresthecursortoitsplaceinthetext.Givethecommand:setnonumber
RETURNtoturnofflinenumbers.
vimiscasesensitive
Whenyougivevimacommand,rememberthattheeditoriscasesensitive.Thusvimeditorinterprets
thesameletterastwodifferentcommands,dependingonwhetheryouenteranuppercaseorlowercase
character.BewareoftheCAPSLOCK(SHIFTLOCK)key.Ifyousetthiskeytoenteruppercasetext
whileyouareinInputmodeandthenexittoCommandmode,viminterpretsyourcommandsas
uppercaseletters.Itcanbeconfusingwhenthishappensbecausevimdoesnotappeartobeexecutingthe
commandsyouareentering.
EnteringText

Inputmode(i/a)
Whenyoustartvim,youmustputitinInputmodebeforeyoucanentertext.ToputviminInputmode,
presstheikey(insertbeforethecursor)ortheakey(appendafterthecursor).
IfyouarenotsurewhethervimiscurrentlyinInputmode,presstheESCAPEkey;vimreturnsto
CommandmodeifitwasinInputmodeorbeeps,flashes,ordoesnothingifitisalreadyinCommand
mode.YoucanputvimbackinInputmodebypressingtheiorakeyagain.
WhilevimisinInputmode,youcanentertextbytypingonthekeyboard.Ifthetextdoesnotappearon
thescreenasyoutype,youarenotinInputmode.
Tocontinuewiththistutorial,enterthesampleparagraphshowninFigure6-4,pressingtheRETURNkey
toendeachline.IfyoudonotpressRETURNbeforethecursorreachestherightsideofthescreenor
window,vimwillwrapthetextsothatitappearstostartanewline.Physicallineswillnotcorrespond
toprogrammatic(logical)linesinthissituation,andeditingwillbemoredifficult.
Figure6-4.Enteringtextwithvim
[Viewfullsizeimage]
Whileyouareusingvim,youcanalwayscorrectanytypingmistakesyoumake.Ifyounoticeamistake
onthelineyouareentering,youcancorrectitbeforeyoucontinue(page146).Youcancorrectother
mistakeslater.Whenyoufinishenteringtheparagraph,pressESCAPEtoreturnvimtoCommandmode.

GettingHelp
Togethelpwhileyouareusingvim,givethecommand:help[feature]followedbyRETURN(youmust
beinCommandmodewhenyougivethiscommand).Thecolonputsthecursoronthelastlineofthe
screen.Ifyoutype:help,vimdisplaysanintroductiontovimHelp(Figure6-5).Eachdarkbandnear
thebottomofthescreennamesthefilethatisdisplayedaboveit.(Eachareaofthescreenthatdisplaysa
file,suchasthetwoareasshowninFigure6-5,isavim"window.")Thehelp.txtfileoccupiesmostof
thescreen(theupperwindow)inFigure6-5.Thefilethatisbeingedited(practice)occupiesafewlines
inthelowerportionofthescreen(thelowerwindow).
Figure6-5.ThemainvimHelpscreen
[Viewfullsizeimage]
ReadthroughtheintroductiontoHelpbyscrollingthetextasyouread.PressingjortheDOWNARROW
keymovesthecursordownonelineatatime;pressingCONTROL-DorCONTROL-Uscrollsthecursor
downoruphalfawindowatatime.Givethecommand:q!toclosetheHelpwindow.
Youcangethelpwiththeinsertcommandsbygivingthecommand:helpinsertwhilevimisinCommand
mode(Figure6-6).
Figure6-6.Helpwithinsert
[Viewfullsizeimage]

CorrectingTextasYouInsertIt
ThekeysthatbackupandcorrectashellcommandlineservethesamefunctionswhenvimisinInput
mode.Thesekeysincludetheerase,linekill,andwordkillkeys(usuallyCONTROL-H,CONTROL-U,
andCONTROL-W,respectively).Althoughvimmaynotremovedeletedtextfromthescreenasyou
backupoverit,theeditordoesremoveitwhenyoutypeoveritorpressRETURN.
MovingtheCursor
Youneedtobeabletomovethecursoronthescreensothatyoucandelete,insert,andcorrecttext.While
vimisinCommandmode,youcanusetheRETURNkey,theSPACEbar,andtheARROWkeystomove
thecursor.Ifyouprefertokeepyourhandclosertothecenterofthekeyboard,ifyourterminaldoesnot
haveARROWkeys,oriftheemulatoryouareusingdoesnotsupportthem,youcanusetheh,j,k,andl
(lowercase"l")keystomovethecursorleft,down,up,andright,respectively.
DeletingText
Deletecharacter(x)Deleteword(dw)Deleteline(dd)
Youcandeleteasinglecharacterbymovingthecursoruntilitisoverthecharacteryouwanttodeleteand
thengivingthecommandx.Youcandeleteawordbypositioningthecursoronthefirstletteroftheword
andthengivingthecommanddw(Deleteword).Youcandeletealineoftextbymovingthecursoruntilit
isanywhereonthelineandthengivingthecommanddd.
UndoingMistakes
Undo(u)
Ifyoudeleteacharacter,line,orwordbymistakeorgiveanycommandyouwanttoundo,givethe
commandu(Undo)immediatelyafterthecommandyouwanttoundo.Thevimeditorwillrestorethetext
tothewayitwasbeforeyougavethelastcommand.Ifyougivetheucommandagain,vimwillundothe
commandyougavebeforetheoneitjustundid.Youcanusethistechniquetobackupovermanyofyour
actions.Withthecompatibleparameter(page148)set,vimcanundoonlythemostrecentchange.
Redo(:redo)
Ifyouundoacommandyoudidnotmeantoundo,giveaRedocommand:CONTROL-Ror:redo
(followedbyaRETURN).Thevimeditorwillredotheundonecommand.AswiththeUndocommand,
youcangivetheRedocommandmanytimesinarow.
EnteringAdditionalText
Insert(i)Append(a)
Whenyouwanttoinsertnewtextwithinexistingtext,movethecursorsoitisonthecharacterthat
followsthenewtextyouplantoenter.Thengivethei(Insert)commandtoputviminInputmode,enter
thenewtext,andpressESCAPEtoreturnvimtoCommandmode.Alternatively,youcanpositionthe
cursoronthecharacterthatprecedesthenewtext,andusethea(Append)command.
Open(oandO)
Toenteroneormorelines,positionthecursoronthelineabovewhereyouwantthenewtexttogo.Give
thecommando(Open).Thevimeditoropensablankline,putsthecursoronit,andgoesintoInputmode.
Enterthenewtext,endingeachlinewithaRETURN.Whenyouarefinishedenteringtext,pressESCAPE
toreturnvimtoCommandmode.TheOcommandworksinthesamewayoworks,exceptthatitopensa
lineabovethelinethecursorison.
CorrectingText
Tocorrecttext,usedd,dw,orxtoremovetheincorrecttext.Thenusei,a,o,orOtoinsertthecorrect
text.
Forexample,tochangethewordpressingtohittinginFigure6-4onpage145youmightusethe
ARROWkeystomovethecursoruntilitisontopofthepinpressing.Thengivethecommanddwto
deletethewordpressing.PutviminInputmodebygivinganicommand,enterthewordhittingfollowed
byaSPACE,andpressESCAPE.ThewordischangedandvimisinCommandmode,waitingfor
anothercommand.Ashorthandforthetwocommandsdwfollowedbytheicommandiscw(Change
word).ThecommandcwputsvimintoInputmode.
tip:Pagebreaksfortheprinter
CONTROL-Lisasignaltoaprintertoskiptothetopofthsenextpage.Youcanenterthis
characteranywhereinadocumentbypressingCONTROL-LwhileyouareinInputmode.
If^Ldoesnotappear,pressCONTROL-VbeforeCONTROL-L.
EndingtheEditingSession
Whileyouareediting,vimkeepstheeditedtextinanareanamedtheWorkbuffer.Whenyoufinish
editing,youmustwriteoutthecontentsoftheWorkbuffertoadiskfilesothattheeditedtextissavedand
availablewhenyounextwantit.
MakesurethatvimisinCommandmode,andthenusetheZZcommand(youmustuseuppercaseZ's)to
writeyournewlyenteredtexttothediskandendtheeditingsession.AfteryougivetheZZcommand,
vimreturnscontroltotheshell.Youcanexitwith:q!ifyoudonotwanttosaveyourwork.Refertopage
188forasummaryofvimcommands.
caution:DonotconfuseZZwithCONTROL-Z
WhenyouexitfromvimwithZZ,makesurethatyoutypeZZandnotCONTROL-Z
(typicallythesuspendkey).WhenyoupressCONTROL-Z,vimdisappearsfromyour
screen,almostasthoughyouhadexitedfromit.Infact,vimwillcontinuerunninginthe
backgroundwithyourworkunsaved.Referto"JobControl"onpage271.Ifyoutrytostart
editingthesamefilewithanewvimcommand,vimdisplaysamessageaboutaswapfile;
referto"FileLocks"onpage152.
ThecompatibleParameter
Thecompatibleparametermakesvimmorecompatiblewithvi.Bydefaultthisparameterissetsothat
vimworkslikevi.Ifyousetupa~/.vimrcstartupfile(page176),thecompatibleparameterisunset
andvimworkslikevim.Togetstartedwithvimyoucanignorethisparameter.
Settingthecompatibleparameterchangesmanyaspectsofhowvimworks.Forexample,whenthe
compatibleparameterisset,theUndocommand(page146)canundoonlyyourmostrecentchange;with
thecompatibleparameterunset,youcancallundorepeatedlytoundomanychanges.Thischapternotes
whenthecompatibleparameteraffectsacommand.Toobtainmoredetailsonthecompatibleparameter,
givethecommand:helpcompatibleRETURN.Foracompletelistofhowvimdiffersfromtheoriginal
vi,use:helpvi-diffRETURN.Seepage144foradiscussionofthehelpcommand.
FromthecommandlineusetheCoptiontosetthecompatibleparameterandtheNoptiontounsetit.
Referto"SettingParametersfromWithinvim"onpage175forinformationonhowtochangethe
compatibleparameterwhileyouarerunningvim.

IntroductiontovimFeatures
Thissectioncoversmodesofoperation,onlinehelp,theWorkbuffer,emergencyprocedures,andother
vimfeatures.Toseewhichfeaturesareincorporatedinaparticularbuild,giveavimcommandfollowed
bytheversionoption.
OnlineHelp
Ascoveredbrieflyearlier,vimprovideshelpwhileyouareusingit.Givethecommand:helpfeatureto
displayinformationaboutfeature.Asyouscrollthroughthevarioushelptextsyouwillseewordswitha
baroneitherside,suchas|tutor|.Thesewordsareactivelinks:Movethecursorontopofanactivelink
andpressCONTROL-]tojumptothelinkedtext.UseCONTROL-O(lowercase"o")tojumpbackto
whereyouwereinthehelptext.Youcanalsousetheactivelinkwordsinplaceoffeature.Forexample,
youmightseethereference|credits|;youcouldenter:helpcreditsRETURNtoreadmoreaboutcredits.
Enter:q!tocloseahelpwindow.
Somecommonfeaturesthatyoumaywanttolookupusingthehelpsystemareinsert,delete,and
opening-window.Althoughopening-windowisnotintuitive,youwillgettoknowthenamesoffeatures
asyouspendmoretimewithvim.Youcanalsogivethecommand:helpdoc-file-listtoviewacomplete
listofthehelpfiles.Althoughvimisafreeprogram,theauthorrequeststhatyoudonatethemoneyyou
wouldhavespentonsimilarsoftwaretohelpthekidsinUganda(:helpugandaformoreinformation).
ModesofOperation
Thevimeditorispartoftheexeditor,whichhasfivemodesofoperation:
exCommandmode
exInputmode
vimCommandmode
vimInputmode
vimLastLinemode
WhileinCommandmode,vimacceptskeystrokesascommands,respondingtoeachcommandasyou
enterit.Itdoesnotdisplaythecharactersyoutypeinthismode.WhileinInputmode,vimacceptsand
displayskeystrokesastextthatiteventuallyputsintothefileyouareediting.Allcommandsthatstartwith
acolon(:)putviminLastLinemode.Thecolonmovesthecursortothebottomlineofthescreen,where
youentertherestofthecommand.
Inadditiontothepositionofthecursor,thereisanotherimportantdifferencebetweenLastLinemodeand
Commandmode.WhenyougiveacommandinCommandmode,youdonotterminatethecommandwitha
RETURN.However,youmustterminateallLastLinemodecommandswithaRETURN.
Youdonotnormallyusetheexmodes.WhenthischapterreferstoInputandCommandmodes,itmeans
thevimmodes,nottheexmodes.
Atthestartofaneditingsession,vimisinCommandmode.Severalcommands,includingInsertand
Append,putviminInputmode.WhenyoupresstheESCAPEkey,vimalwaysrevertstoCommand
mode.
TheChangeandReplacecommandscombinetheCommandandInputmodes.TheChangecommand
deletesthetextyouwanttochangeandputsviminInputmodesoyoucaninsertnewtext.TheReplace
commanddeletesthecharacter(s)youoverwriteandinsertsthenewone(s)youenter.Figure6-3onpage
143showsthemodesandthemethodsforchangingbetweenthem.
tip:WatchthemodeandtheCAPSLOCKkey
AlmostanythingyoutypeinCommandmodemeanssomethingtovim.Ifyouthinkthatvim
isinInputmodewhenitisactuallyinCommandmode,typingintextcanproduceconfusing
results.Whenlearningvim,makesurethattheshowmodeparameter(page180)isset(itis
bydefault)toremindyouwhichmodeyouareusing.Youmayalsofinditusefultoturnon
thestatuslinebygivinga:setlaststatus=2command(page178).
AlsokeepyoureyeontheCAPSLOCKkey.InCommandmodetypinguppercaseletters
producesdifferentresultsthantypinglowercaseones.Itcanbedisorientingtogive
commandsandhavevimgivethe"wrong"responses.
TheDisplay
Thevimeditorusesthestatuslineandseveralspecialsymbolstogiveinformationaboutwhatis
happeningduringaneditingsession.
StatusLine
Thevimeditordisplaysstatusinformationonthebottomlineofthedisplayarea.Thisinformation
includeserrormessages,informationaboutthedeletionoradditionofblocksoftext,andfilestatus
information.Inaddition,vimdisplaysLastLinemodecommandsonthestatusline.
RedrawingtheScreen
Sometimesthescreenbecomesgarbledoroverwritten.Whenvimputscharactersonthescreen,it
sometimesleaves@onalineinsteadofdeletingtheline.Whenoutputfromaprogrambecomes
intermixedwiththedisplayoftheWorkbufferthingscangetconfusing.Theoutputdoesnotbecomepart
oftheWorkbufferbutaffectsonlythedisplay.Ifthescreengetsoverwritten,pressESCAPEtomakesure
vimisinCommandmode,andpressCONTROL-Ltoredraw(refresh)thescreen.
Tilde(~)Symbol
Iftheendofthefileisdisplayedonthescreen,vimmarkslinesthatwouldappearpasttheendofthefile
withatilde(~)attheleftofthescreen.Whenyoustarteditinganewfile,thevimeditormarkseachline
onthescreen(exceptforthefirstline)withthissymbol.
CorrectingTextasYouInsertIt
WhilevimisinInputmode,youcanusetheeraseandlinekillkeystobackupovertextsoyoucan
correctit.YoucanalsouseCONTROL-Wtobackupoverwords.
WorkBuffer
ThevimeditordoesallofitsworkintheWorkbuffer.Atthestartofaneditingsession,vimreadsthe
fileyouareeditingfromthediskintotheWorkbuffer.Duringtheeditingsession,itmakesallchangesto
thiscopyofthefilebutdoesnotchangethefileonthediskuntilyouwritethecontentsoftheWorkbuffer
backtothedisk.Normallywhenyouendaneditingsession,youcommandvimtowriteoutthecontents
oftheWorkbuffer,whichmakesthechangestothetextfinal.Whenyoueditanewfile,vimcreatesthe
filewhenitwritesthecontentsoftheWorkbuffertothedisk,usuallyattheendoftheeditingsession.
StoringthetextyouareeditingintheWorkbufferhasbothadvantagesanddisadvantages.Ifyou
accidentallyendaneditingsessionwithoutwritingoutthecontentsoftheWorkbuffer,yourworkislost.
However,ifyouunintentionallymakesomemajorchanges(suchasdeletingtheentirecontentsofthe
Workbuffer),youcanendtheeditingsessionwithoutimplementingthechanges.
Ifyouwanttousevimtolookatafilebutnottochangeit,youcanusetheviewutility:
$viewfilename
CallingtheviewutilityisthesameascallingthevimeditorwiththeR(readonly)option.Onceyou
haveinvokedtheeditorinthisway,youcannotwritethecontentsoftheWorkbufferbacktothefile
whosenameappearedonthecommandline.YoucanalwayswritetheWorkbufferouttoafilewitha
differentname.
LineLengthandFileSize
Thevimeditoroperatesonanyformatfile,providedthelengthofasingle"line"(thatis,thecharacters
betweentwoNEWLINEcharacters)canfitintoavailablememory.Thetotallengthofthefileislimited
onlybyavailablediskspaceandmemory.
Windows
Thevimeditorallowsyoutoopen,close,andhidemultiplewindows,eachofwhichallowsyoutoedita
differentfile.MostofthewindowcommandsconsistofCONTROL-Wfollowedbyanotherletter.For
example,CONTROL-Wsopensanotherwindow(splitsthescreen)thatiseditingthesamefile.
CONTROL-Wnopensasecondwindowthatiseditinganemptyfile.CONTROL-Wwmovesthecursor
betweenwindows,andCONTROL-Wq(or:q)quits(closes)awindow.Givethecommand:help
windowstodisplayacompletelistofwindowscommands.
FileLocks
Whenyoueditanexistingfile,vimdisplaysthefirstfewlinesofthefile,givesstatusinformationabout
thefileonthestatusline,andlocksthefile.Whenyoutrytoopenalockedfilewithvim,youwillseea
messagesimilartotheoneshowninFigure6-7.Youwillseethistypeofmessageintwocases:whenyou
trytoeditafilethatsomeoneisalreadyediting(perhapsyouareeditingitinanotherwindoworon
anotherterminal)orwhenyoutrytoeditafilethatyouwereeditingwhenvimorthesystemcrashed.
Figure6-7.Attemptingtoopenalockedfile

Althoughitisadvisabletofollowtheinstructionsthatvimdisplays,asecondusercaneditafileand
writeitoutwithadifferentfilename.Refertothenextsectionsformoreinformation.
AbnormalTerminationofanEditingSession
Youcanendaneditingsessioninoneoftwoways:Whenyouexitfromvim,youcansavethechanges
youmadeduringtheeditingsessionoryoucanabandonthosechanges.YoucanusetheZZor:wq
commandfromCommandmodetosaveyourchangesandexitfromvim(see"EndingtheEditing
Session"onpage147).
ToendaneditingsessionwithoutwritingoutthecontentsoftheWorkbuffer,givethefollowing
command:
:q!
Whenyouusethiscommandtoendaneditingsession,vimdoesnotpreservethecontentsoftheWork
buffer,soyouwilllosealltheworkyoudidsincethelasttimeyouwrotetheWorkbuffertodisk.The
nexttimeyoueditorusethefile,itwillappearasitdidthelasttimeyouwrotetheWorkbuffertodisk.
Usethe:q!commandcautiously.
Sometimesyoumayfindthatyoucreatedoreditedafilebutvimwillnotletyouexit.Forexample,ifyou
forgottospecifyafilenamewhenyoufirstcalledvim,youwillgetamessagesayingNofilenamewhen
yougiveaZZcommand.Ifvimdoesnotletyouexitnormally,youcanusetheWritecommand(:w)to
namethefileandwriteittodiskbeforeyouquitvim.Givethefollowingcommand,substitutingthename
ofthefileforfilename(remembertofollowthecommandwithaRETURN):
:wfilename
AfteryougivetheWritecommand,youcanuse:qtoquitusingvim.Youdonotneedtousethe
exclamationpoint(asinq!);itisnecessaryonlywhenyouhavemadechangessincethelasttimeyou
wrotetheWorkbuffertodisk.Refertopage174formoreinformationabouttheWritecommand.
tip:Whenyoucannotwritetoafile
Itmaybenecessarytowriteafileusing:wfilenameifyoudonothavewritepermission
forthefileyouareediting.IfyougiveaZZcommandandseethemessage"filename"is
readonly,youdonothavewritepermissionforthefile.UsetheWritecommandwitha
temporaryfilenametowritethefiletodiskunderadifferentfilename.Ifyoudonothave
writepermissionfortheworkingdirectory,vimmaystillnotbeabletowritethefiletothe
disk.Givethecommandagain,usinganabsolutepathnameofadummy(nonexistent)filein
yourhomedirectoryinplaceofthefilename.(Forexample,Alexmightgivethecommand
:w/home/alex/tempor:w~/temp.)
IfvimreportsFileexists,youwillneedtouse:w!filenametooverwritetheexistingfile
(makesurethatyouwanttodothis).Refertopage175.
RecoveringTextAfteraCrash
Thevimeditortemporarilystoresthefileyouareworkingoninaswapfile.Ifthesystemcrasheswhile
youareeditingafilewithvim,youcanoftenrecoveritstextfromtheswapfile.Whenyouattempttoedit
afilethathasaswapfile,youwillseeamessagesimilartotheoneshowninFigure6-7onpage152.If
someoneelseiseditingthefile,quitoropenthefileasareadonlyfile.
Alexcheckswhethertheswapfileexistsforafilenamedmemo,whichhewaseditingwhenthesystem
wentdown:
$vim-r
Swapfilesfound:
Incurrentdirectory:
1..memo.swp
dated:MonOct1813:16:062004
ownedby:alex
filename:~alex/memo
hostname:bravo.example.com
username:alex
processID:19786
Indirectory~/tmp:
--none--
Indirectory/var/tmp:
--none--
Indirectory/tmp:
--none--
Withtheroptionvimdisplaysalistofanyswapfilesthatithassaved(somemaybeold).Ifyourwork
wassaved,givethesamecommandfollowedbyaSPACEandthenameofthefile.Youwillthenbe
editingarecentcopyofyourWorkbuffer.Use:wfilenameimmediatelytosavethesalvagedcopyofthe
Workbuffertodiskunderanamedifferentfromtheoriginalfile.Thenchecktherecoveredfiletomake
sureitisOK.FollowingisAlex'sexchangewithvimasherecoversmemo.Subsequentlyhedeletesthe
swapfile:
$vim-rmemo
Usingswapfile".memo.swp"
Originalfile"~/memo"
Recoverycompleted.YoushouldcheckifeverythingisOK.
(Youmightwanttowriteoutthisfileunderanothername
andrundiffwiththeoriginalfiletocheckforchanges)
Deletethe.swpfileafterwards.
HitENTERortypecommandtocontinue
:wmemo2
:q
$rm.memo.swp
tip:Youmustrecoverfilesonthesystemyouwereusing
Therecoveryfeatureofvimisspecifictothesystemyouwereusingwhenthecrash
occurred.Ifyouarerunningonacluster,youmustloginonthesystemyouwereusing
beforethecrashtousetheroption.

CommandMode:MovingtheCursor
WhilevimisinCommandmode,youcanpositionthecursoroveranycharacteronthescreen.Youcan
alsodisplayadifferentportionoftheWorkbufferonthescreen.Bymanipulatingthescreenandcursor
position,youcanplacethecursoronanycharacterintheWorkbuffer.
Youcanmovethecursorforwardorbackwardthroughthetext.AsillustratedinFigure6-8,forward
meanstowardtherightandbottomofthescreenandtheendofthefile.Backwardmeanstowardtheleft
andtopofthescreenandthebeginningofthefile.Whenyouuseacommandthatmovesthecursor
forwardpasttheend(right)ofaline,thecursorgenerallymovestothebeginning(left)ofthenextline.
Whenyoumoveitbackwardpastthebeginningofaline,thecursormovestotheendofthepreviousline.
Figure6-8.Forwardandbackward
Longlines
SometimesalineintheWorkbuffermaybetoolongtoappearasasinglelineonthescreen.Insucha
casevimwrapsthecurrentlineontothenextline(unlessyousetthenowrapoption[page178]).
YoucanmovethecursorthroughthetextbyanyUnitofMeasure(thatis,character,word,line,sentence,
paragraph,orscreen).Ifyouprecedeacursor-movementcommandwithanumber,calledaRepeat
Factor,thecursormovesthatnumberofunitsthroughthetext.Refertopages184and187formore
precisedefinitionsoftheseterms.
MovingtheCursorbyCharacters
l/h

TheSPACEbarmovesthecursorforward,onecharacteratatime,towardtherightsideofthescreen.
Thel(lowercase"l")keyandtheRIGHTARROWkey(Figure6-9)dothesamething.Thecommand7
SPACEor7lmovesthecursorsevencharacterstotheright.Thesekeyscannotmovethecursorpastthe
endofthecurrentlinetothebeginningofthenextline.ThehandLEFTARROWkeysaresimilartothel
keybutworkintheoppositedirection.
Figure6-9.Movingthecursorbycharacters
MovingtheCursortoaSpecificCharacter
f/F
Youcanmovethecursortothenextoccurrenceofaspecifiedcharacteronthecurrentlinebyusingthe
Findcommand.Forexample,thefollowingcommandmovesthecursorfromitscurrentpositiontothe
nextoccurrenceofthecharactera,ifoneappearsonthesameline:
fa
YoucanalsofindthepreviousoccurrencebyusingacapitalF.Thefollowingcommandmovesthecursor
tothepositionoftheclosestpreviousainthecurrentline:
Fa
Asemicolon(;)repeatsthelastFindcommand.
MovingtheCursorbyWords
w/W
Thew(word)keymovesthecursorforwardtothefirstletterofthenextword(Figure6-10).Groupsof
punctuationcountaswords.Thiscommandgoestothenextlineifthenextwordislocatedthere.The

command15wmovesthecursortothefirstcharacterofthefifteenthsubsequentword.
Figure6-10.Movingthecursorbywords
TheWkeyissimilartothewkeybutmovesthecursorbyblank-delimitedwords,includingpunctuation,
asitskipsforward.(Referto"Blank-DelimitedWord"onpage185.)
b/B
Theb(back)keymovesthecursorbackwardtothefirstletterofthepreviousword.TheBkeymovesthe
cursorbackwardbyblank-delimitedwords.Similarlytheekeymovesthecursortotheendofthenext
word;Emovesittotheendofthenextblank-delimitedword.
MovingtheCursorbyLines
j/k
TheRETURNkeymovesthecursortothebeginningofthenextline;thejandDOWNARROWkeys
moveitdownonelinetothecharacterjustbelowthecurrentcharacter(Figure6-11).Ifnocharacteris
immediatelybelowthecurrentcharacter,thecursormovestotheendofthenextline.Thecursorwillnot
movepastthelastlineoftextintheworkbuffer.
Figure6-11.Movingthecursorbylines

ThekandUPARROWkeysaresimilartothejkeybutworkintheoppositedirection.Theminus()key
issimilartotheRETURNkeybutworksintheoppositedirection.
MovingtheCursorbySentencesandParagraphs
)/(}/{
The)and}keysmovethecursorforwardtothebeginningofthenextsentenceorthenextparagraph,
respectively(Figure6-12).The(and{keysmovethecursorbackwardtothebeginningofthecurrent
sentenceorparagraph.Youcanfindmoreinformationonsentencesandparagraphsstartingonpage186.
Figure6-12.Movingthecursorbysentences,paragraphs,H,M,andL
[Viewfullsizeimage]
MovingtheCursorWithintheScreen
H/M/L
TheH(home)keypositionsthecursorattheleftendofthetoplineofthescreen.TheM(middle)key
movesthecursortothemiddleline,andtheL(lower)keymovesittothebottomline(Figure6-12).
ViewingDifferentPartsoftheWorkBuffer
ThescreendisplaysaportionofthetextthatisintheWorkbuffer.Youcandisplaythetextprecedingor
followingthetextonthescreenbyscrollingthedisplay.YoucanalsodisplayaportionoftheWorkbuffer
basedonalinenumber.
CONTROL-DCONTROL-U
PressCONTROL-Dtoscrollthescreendown(forward)throughthefilesothatvimdisplayshalfa
screenofnewtext.UseCONTROL-Utoscrollthescreenup(backward)bythesameamount.Ifyou
precedeeitherofthesecommandswithanumber,vimwillscrollthatnumberoflineseachtimeyouuse
CONTROL-DorCONTROL-Ufortherestofthesession(unlessyouagainchangethenumberoflinesto
scroll).Seepage179foradiscussionofthescrollparameter.
CONTROL-FCONTROL-B
TheCONTROL-F(forward)andCONTROL-B(backward)keysdisplayalmostawholescreenofnew
text,leavingacoupleoflinesfromthepreviousscreenforcontinuity.Onmanykeyboardsyoucanusethe
PAGEDOWNandPAGEUPkeysinplaceofCONTROL-FandCONTROL-B.
Linenumbers(G)
WhenyouenteralinenumberfollowedbyG(goto),vimpositionsthecursoronthatlineintheWork
buffer.IfyoupressGwithoutanumber,vimpositionsthecursoronthelastlineintheWorkbuffer.Line
numbersareimplicit;yourfiledoesnotneedtohaveactuallinenumbersforthiscommandtowork.Refer
to"Linenumbers"onpage178ifyouwantvimtodisplaylinenumbers.

InputMode
TheInsert,Append,Open,Change,andReplacecommandsputviminInputmode.Whilevimisinthis
mode,youcanputnewtextintotheWorkbuffer.YouneedtopresstheESCAPEkeytoreturnvimto
Commandmodewhenyoufinishenteringtext.Referto"Showmode"onpage180ifyouwantvimto
remindyouwhenitisinInputmode(itdoesbydefault).
InsertingText
Insert(i/I)
Thei(Insert)commandputsviminInputmodeandplacesthetextyouenterbeforethecharacterthe
cursorison(thecurrentcharacter).TheIcommandplacestextatthebeginningofthecurrentline
(Figure6-13).AlthoughtheiandIcommandssometimesoverwritetextonthescreen,thecharactersin
theWorkbufferarenotchanged;onlythedisplayisaffected.Theoverwrittentextisredisplayedwhen
youpressESCAPEandvimreturnstoCommandmode.UseiorItoinsertafewcharactersorwords
intoexistingtextortoinserttextinanewfile.
Figure6-13.TheI,i,a,andAcommands
AppendingText
Append(a/A)
Thea(Append)commandissimilartotheicommand,exceptthatitplacesthetextyouenterafterthe
currentcharacter(Figure6-13).TheAcommandplacesthetextafterthelastcharacteronthecurrentline.
OpeningaLineforText
Open(o/O)
Theo(Open)andOcommandsopenablanklinewithinexistingtext,placethecursoratthebeginningof
thenew(blank)line,andputviminInputmode.TheOcommandopensalineabovethecurrentline;o
opensonebelowthecurrentline.UsetheOpencommandswhenyouareenteringseveralnewlines
withinexistingtext.
ReplacingText
Replace(r/R)
TherandR(Replace)commandscausethenewtextyouentertooverwrite(replace)existingtext.The
singlecharacteryouenterfollowinganrcommandoverwritesthecurrentcharacter.Afteryouenterthat
character,vimautomaticallyreturnstoCommandmodeyoudonotneedtopresstheESCAPEkey.
TheRcommandcausesallsubsequentcharacterstooverwriteexistingtextuntilyoupressESCAPEto
returnvimtoCommandmode.
tip:ReplacingTABs
TheReplacecommandsmayappeartobehavestrangelywhenyoureplaceTABcharacters.
TABcharacterscanappearasseveralSPACEsuntilyoutrytoreplacethem.Theyare
actuallyonlyonecharacterandarereplacedbyasinglecharacter.Referto"Invisible
characters"onpage178forinformationonhowtodisplayTABsasvisiblecharacters.
QuotingSpecialCharactersinInputMode
CONTROL-V
WhileyouareinInputmode,youcanusetheQuotecommand,CONTROL-V,toenteranycharacterinto
thetext,includingcharactersthatnormallyhavespecialmeaningtovim.Amongthesecharactersare
CONTROL-L(orCONTROL-R),whichredrawsthescreen;CONTROL-W,whichbacksthecursorupa
wordtotheleft;andESCAPE,whichendsInputmode.
Toinsertoneofthesecharactersintothetext,typeCONTROL-Vfollowedbythecharacter.CONTROL-
Vquotesthesinglecharacterthatfollowsit.Forexample,toinsertthesequenceESCAPE[2Jintoafile
youarecreatinginvim,youtypethecharactersequenceCONTROL-VESCAPE[2J.Thischaracter
sequenceclearsthescreenofaDECVT-100andothersimilarterminals.Althoughyouwouldnot
ordinarilywanttotypethissequenceintoadocument,youmightwanttouseitoranotherESCAPE
sequenceinashellscriptyouarecreatinginvim.RefertoChapter11forinformationaboutwritingshell
scripts.
CommandMode:DeletingandChangingText
Thissectiondescribesthecommandstodeleteandreplace,orchange,textinthedocumentyouare
editing.TheUndocommandiscoveredherebecauseitallowsyoutorestoredeletedorchangedtext.
UndoingChanges
Undo(u/U)
Theucommand(Undo)restorestextthatyoujustdeletedorchangedbymistake.AsingleUndocommand
restoresonlythemostrecentlydeletedtext.Ifyoudeletealineandthenchangeaword,thefirstUndo
restoresonlythechangedword;youhavetogiveasecondUndocommandtorestorethedeletedline.The
Ucommandrestoresthelastlineyouchangedtothewayitwasbeforeyoustartedchangingit,evenafter
severalchanges.
DeletingCharacters
Deletecharacter(x/X)
Thexcommanddeletesthecurrentcharacter.YoucanprecedethexcommandbyaRepeatFactor(page
187)todeleteseveralcharactersonthecurrentline,startingwiththecurrentcharacter.TheXcommand
deletescharacterstotheleftofthecursor.
DeletingText
Delete(d/D)
Thed(Delete)commandremovestextfromtheWorkbuffer.Theamountoftextthatdremovesdepends
ontheRepeatFactorandtheUnitofMeasure(page184)youenterafterthed.Afterthetextisdeleted,
vimisstillinCommandmode.
tip:Useddtodeleteasingleline
ThecommanddRETURNdeletestwolines:thecurrentlineandthefollowingone.Usedd
todeletejustthecurrentline,orprecededdbyaRepeatFactor(page187)todelete
severallines.

Youcandeletefromthecurrentcursorpositionuptoaspecificcharacteronthesameline.Todeleteupto
thenextsemicolon(;),givethecommanddt;(seepage164formoreinformationonthetcommand).To
deletetheremainderofthecurrentline,useDord$.Table6-1listssomeDeletecommands.Each
command,exceptthelastgroupthatstartswithdd,deletesfrom/tothecurrentcharacter.
Table6-1.Deletecommandexamples
Command Result
dl Deletescurrentcharacter(sameasthexcommand)
d0 Deletesfrombeginningofline
d^ Deletesfromfirstcharacteroftheline(notincludingleadingSPACEsor
TABs)
dw Deletestoendofword
d3w Deletestoendofthirdword
db Deletesfrombeginningofword
dW Deletestoendofblank-delimitedword
dB Deletesfrombeginningofblank-delimitedword
d7B Deletesfromseventhpreviousbeginningofblank-delimitedword
d) Deletestoendofsentence
d4) Deletestoendoffourthsentence
d( Deletesfrombeginningofsentence
d} Deletestoendofparagraph
d{ Deletesfrombeginningofparagraph
d7{ Deletesfromseventhparagraphprecedingbeginningofparagraph
d/text Deletesuptothenextoccurrenceofwordtext
dfcDeletesoncurrentlineuptoandincludingnextoccurrenceofcharacterc
dtcDeletesoncurrentlineuptonextoccurrenceofc

DDeletestoendofline
d$ Deletestoendofline
dd Deletesthecurrentline
5dd Deletesfivelinesstartingwiththecurrentline
dL Deletesthroughlastlineonscreen
dH Deletesfromfirstlineonscreen
dG DeletesthroughendofWorkbuffer
d1G DeletesfrombeginningofWorkbuffer
tip:Exchangecharactersandlines
Iftwocharactersareoutoforder,positionthecursoronthefirstcharacterandgivethe
commandsxp.
Iftwolinesareoutoforder,positionthecursoronthefirstlineandgivethecommands
ddp.
Seepage172formoreinformationonthePutcommands.
ChangingText
Change(c/C)
Thec(Change)commandreplacesexistingtextwithnewtext.Thenewtextdoesnothavetooccupythe
samespaceastheexistingtext.Youcanchangeawordtoseveralwords,alinetoseverallines,ora
paragraphtoasinglecharacter.TheCcommandreplacesthetextfromthecursorpositiontotheendof
theline.
TheccommanddeletestheamountoftextspecifiedbytheRepeatFactorandtheUnitofMeasure(page
184)andputsviminInputmode.WhenyoufinishenteringthenewtextandpressESCAPE,theold

word,line,sentence,orparagraphischangedtothenewone.PressingESCAPEwithoutenteringnewtext
deletesthespecifiedtext(replacesthespecifiedtextwithnothing).
Table6-2listssomeChangecommands.Exceptforthelasttwo,eachcommandchangestextfrom/tothe
currentcharacter.
Table6-2.Changecommandexamples
Command Result
cl Changescurrentcharacter
cw Changestoendofword
c3w Changestoendofthirdword
cb Changesfrombeginningofword
cW Changestoendofblank-delimitedword
cB Changesfrombeginningofblank-delimitedword
c7B Changesfrombeginningofseventhpreviousblank-delimitedword
c$ Changestoendofline
c0 Changesfrombeginningofline
c) Changestoendofsentence
c4) Changestoendoffourthsentence
c( Changesfrombeginningofsentence
c} Changestoendofparagraph
c{ Changesfrombeginningofparagraph
c7{ Changesfrombeginningofseventhprecedingparagraph
ctcChangesoncurrentlineuptonextoccurrenceofc
CChangestoendofline
cc Changesthecurrentline
5cc Changesfivelinesstartingwiththecurrentline

tip:dwworksdifferentlyfromcw
Thedwcommanddeletesallthecharactersthrough(including)theSPACEattheendofa
word.Thecwcommandchangesonlythecharactersintheword,leavingthetrailing
SPACEintact.
ReplacingText
Substitute(s/S)
ThesandS(Substitute)commandsalsoreplaceexistingtextwithnewtext(Table6-3).Thescommand
deletesthecharacterthecursorisonandputsvimintoInputmode.Ithastheeffectofreplacingthesingle
characterthatthecursorisonwithwhateveryoutypeuntilyoupressESCAPE.TheScommanddoesthe
samethingasthecccommand:Itchangesthecurrentline.Thescommandreplacescharactersonlyonthe
currentline.IfyouspecifyaRepeatFactorbeforeanscommandandthisactionwouldreplacemore
charactersthanexistonthecurrentline,schangescharactersonlytotheendoftheline(sameasC).
Table6-3.Substitutecommandexamples
Command Result
sSubstitutesoneormorecharactersforcurrentcharacter
SSubstitutesoneormorecharactersforcurrentline
5s Substitutesoneormorecharactersforfivecharacters,startingwithcurrent
character
ChangingCase
Thetilde(~)characterchangesthecaseofthecharacterunderthecursorfromuppercasetolowercase,or
viceversa.Youcanprecedethetildewithanumbertospecifythenumberofcharactersyouwantthe
commandtoaffect.Forexample,5~willtransposethenextfivecharactersstartingwiththecharacter
underthecursor,butitwillnottransposecharacterspasttheendofthelinethecursorison.
SearchingandSubstituting
Searchingforandreplacingacharacter,astringoftext,orastringthatismatchedbyaregularexpression
isakeyfeatureofanyeditor.Thevimeditorprovidessimplecommandsforsearchingforacharacteron
thecurrentline.Italsoprovidesmorecomplexcommandsforsearchingforandoptionallysubstitutingfor
singleandmultipleoccurrencesofstringsorregularexpressionsanywhereintheWorkbuffer.
SearchingforaCharacter
Find(f/F)
Youcansearchforandmovethecursortothenextoccurrenceofaspecifiedcharacteronthecurrentline
usingthef(Find)command.Referto"MovingtheCursortoaSpecificCharacter"onpage155.
t/T
ThenexttwocommandsareusedinthesamemannerastheFindcommand.Thetcommandplacesthe
cursoronthecharacterbeforethenextoccurrenceofthespecifiedcharacter.TheTcommandplacesthe
cursoronthecharacterafterthepreviousoccurrenceofthespecifiedcharacter.
Asemicolon(;)repeatsthelastf,F,t,orTcommand.
Youcancombinethesesearchcommandswithothercommands.Forexample,thecommandd2fqdeletes
thetextfromthelocationofthecursortothesecondoccurrenceoftheletterqonthecurrentline.
SearchingforaString
ThevimeditorcansearchbackwardorforwardthroughtheWorkbuffertofindastringoftextorastring
thatmatchesaregularexpression(seeAppendixA).Tofindthenextoccurrenceofastring(forward),
presstheforwardslash(/)key,enterthetextyouwanttofind(calledthesearchstring),andpress
RETURN.Whenyoupresstheslashkey,vimdisplaysaslashonthestatusline.Asyouenterthestringof
text,itisalsodisplayedonthestatusline.WhenyoupressRETURN,vimsearchesforthestring.Ifthis
searchissuccessful,vimpositionsthecursoronthefirstcharacterofthestring.Ifyouuseaquestion
mark(?)inplaceoftheforwardslash,vimsearchesforthepreviousoccurrenceofthestring.Ifyouneed
toincludeaforwardslashinaforwardsearchoraquestionmarkinabackwardsearch,youmustquoteit
byprecedingitwithabackslash(\).
tip:Twodistinctwaysofquotingcharacters
YouuseCONTROL-Vtoquotespecialcharactersintextthatyouareenteringintoafile
(page159).Thissectiondiscussestheuseofabackslash(\)toquotespecialcharactersin
asearchstring.Thetwotechniquesofquotingcharactersarenotinterchangeable.
TheNandnkeysrepeatthelastsearchwithoutanyneedforyoutoreenterthesearchstring.Thenkey
repeatstheoriginalsearchexactly,andtheNkeyrepeatsthesearchintheoppositedirectionofthe
originalsearch.
IfyouaresearchingforwardandvimdoesnotfindthesearchstringbeforeitgetstotheendoftheWork
buffer,theeditortypicallywrapsaroundandcontinuesthesearchatthebeginningoftheWorkbuffer.
Duringabackwardsearch,vimwrapsaroundfromthebeginningoftheWorkbuffertotheend.Also,
vimnormallyperformscase-sensitivesearches.Referto"Wrapscan"(page180)and"Ignorecasein
searches"(page178)forinformationabouthowtochangethesesearchparameters.
NormalVersusIncrementalSearches
Whenvimperformsanormalsearch(itsdefaultbehavior),youenteraslashorquestionmarkfollowed
bythesearchstringandpressRETURN.Thevimeditormovesthecursortothenextorprevious
occurrenceofthestringyouaresearchingfor.
Whenvimperformsanincrementalsearch,youenteraslashorquestionmark.Asyouentereach
characterofthesearchstring,vimmovesthehighlighttothenextorpreviousoccurrenceofthestringyou
haveenteredsofar.Whenthehighlightisonthestringyouaresearchingfor,youmustpressRETURNto
movethecursortothehighlightedstring.Ifthestringyouenterdoesnotmatchanytext,vimdoesnot
highlightanything.
Thetypeofsearchthatvimperformsdependsontheincsearchparameter(page178).Givethecommand
:setincsearchtoturnonincrementalsearching.Usenoincsearchtoturnitoff.Whenyousetthe
compatibleparameter(page148),vimturnsoffincrementalsearching.
SpecialCharactersinSearchStrings
Becausethesearchstringisaregularexpression,somecharacterstakeonaspecialmeaningwithinthe
searchstring.Thefollowingparagraphslistsomeofthesecharacters.Seealso"ExtendedRegular
Expressions"onpage834.
Thefirsttwoitemsinthefollowinglist(^and$)alwayshavetheirspecialmeaningswithinasearch
stringunlessyouquotethembyprecedingthemwithabackslash(\).Youcanturnoffthespecial
meaningswithinasearchstringfortherestoftheitemsinthelistbysettingthenomagicparameter.See
"Allowspecialcharactersinsearches"(page177)formoreinformation.
^Beginning-of-LineIndicator
Whenthefirstcharacterinasearchstringisacaret(alsocalledacircumflex)itmatchesthebeginningof
aline.Forexample,thecommand/^thefindsthenextlinethatbeginswiththestringthe.
$End-of-LineIndicator
Adollarsignmatchestheendofaline.Forexample,thecommand/!$findsthenextlinethatendswithan
exclamationpointand/$matchesthenextlinethatendswithaSPACE.
.Any-CharacterIndicator
Aperiodmatchesanycharacter,anywhereinthesearchstring.Forexample,thecommand/l..efindsline,
followed,like,included,allmemory,oranyotherwordorcharacterstringthatcontainsanlfollowedby
anytwocharactersandane.Tosearchforaperiod,useabackslashtoquotetheperiod(\.).
\>End-of-WordIndicator
Thispairofcharactersmatchestheendofaword.Forexample,thecommand/s\>findsthenextword
thatendswithans.Whereasabackslash(\)istypicallyusedtoturnoffthespecialmeaningofa
character,thecharactersequence\>hasaspecialmeaning,while>alonedoesnot.
\<Beginning-of-WordIndicator
Thispairofcharactersmatchesthebeginningofaword.Forexample,thecommand/\<Thefindsthenext
wordthatbeginswiththestringThe.Thebeginning-of-wordindicatorusesthebackslashinthesame,
atypicalwayastheend-of-wordindicator.
*ZeroorMoreOccurrences
Thischaracterisamodifierthatwillmatchzeroormoreoccurrencesofthecharacterimmediately
precedingit.Forexample,thecommand/dis*mwillmatchthestringdifollowedbyzeroormores
charactersfollowedbyanm.Examplesofsuccessfulmatchesaredimordismordissm.
[]Character-ClassDefinition
Bracketssurroundingtwoormorecharactersmatchanysinglecharacterlocatedbetweenthebrackets.
Forexample,thecommand/dis[ck]findsthenextoccurrenceofeitherdiskordisc.

Therearetwospecialcharactersyoucanusewithinacharacter-classdefinition.Acaret(^)asthefirst
characterfollowingtheleftbracketdefinesthecharacterclasstobeanyexceptthefollowingcharacters.
Ahyphenbetweentwocharactersindicatesarangeofcharacters.RefertotheexamplesinTable6-4.
Table6-4.Searchexamples
Searchstring Whatitfinds
/and
Findsthenextoccurrenceofthestringand
Examples:sandandstandardslanderandiron
/\<and\>
Findsthenextoccurrenceofthewordand
Example:and
/^The
FindsthenextlinethatstartswithThe
Examples:
The...
There...
/^[0-9][0-9])
Findsthenextlinethatstartswithatwo-digitnumberfollowedbyaright
parenthesis
Examples:
77)...
01)...
15)...
/\<[adr]
Findsthenextwordthatstartswithana,d,orr
Examples:appledriveroadargumentright
/^[A-Za-z]
Findsthenextlinethatstartswithanuppercaseorlowercaseletter
Examples:
willnotfindalinestartingwiththenumber7...
DearMr.Jones...
inthemiddleofasentencelikethis...
SubstitutingOneStringforAnother
ASubstitutecommandcombinestheeffectsofaSearchcommandandaChangecommand.Thatis,it

searchesforastring(regularexpression)justasthe/commanddoes,allowingthesamespecial
charactersdiscussedintheprevioussection.Whenitfindsthestringormatchestheregularexpression,
theSubstitutecommandchangesthestringorregularexpressionitmatches.ThesyntaxoftheSubstitute
commandis
:[g][address]s/search-string/replacement-string[/option]
Aswithallcommandsthatbeginwithacolon,vimexecutesaSubstitutecommandfromthestatusline.
TheSubstituteAddress
Ifyoudonotspecifyanaddress,Substitutesearchesonlythecurrentline.Ifyouuseasinglelinenumber
astheaddress,Substitutesearchesthatline.Iftheaddressistwolinenumbersseparatedbyacomma,
Substitutesearchesthoselinesandthelinesbetweenthem.Referto"Linenumbers"onpage178ifyou
wantvimtodisplaylinenumbers.Whereveralinenumberisallowedintheaddress,youmayalsouse
anaddress-stringenclosedbetweenslashes.Thevimeditoroperatesonthenextlinethattheaddress-
stringmatches.Whenyouprecedethefirstslashoftheaddress-stringwiththeletterg(forglobal),vim
operatesonalllinesinthefilethattheaddress-stringmatches.(Thisgisnotthesameastheonethatgoes
attheendoftheSubstitutecommandtocausemultiplereplacementsonasingleline;see"Searchingfor
andReplacingStrings"below).
Withintheaddress,aperiodrepresentsthecurrentline,adollarsignrepresentsthelastlineintheWork
buffer,andapercentsignrepresentstheentireWorkbuffer.Youcanperformaddressarithmeticusing
plusandminussigns.Table6-5showssomeexamplesofaddresses.
Table6-5.Addresses
Address PortionofWorkbufferaddressed
5Line5
77,100 Lines77through100inclusive
1,. BeginningofWorkbufferthroughcurrentline
.,$ CurrentlinethroughendofWorkbuffer
1,$ EntireWorkbuffer
%EntireWorkbuffer
/pine/ Thenextlinecontainingthewordpine

g/pine/ Alllinescontainingthewordpine
.,.+10 Currentlinethroughtenthfollowingline(11linesinall)
SearchingforandReplacingStrings
Anscomesaftertheaddressinthecommandsyntax,indicatingthatthisisaSubstitutecommand.A
delimiterfollowsthes,markingthebeginningofthesearch-string.Althoughtheexamplesinthisbook
useaforwardslash,youcanuseasadelimiteranycharacterthatisnotaletter,number,blank,or
backslash.Youmustusethesamedelimiterattheendofthesearch-string.
Nextcomesthesearch-string.Ithasthesameformatasthesearchstringinthe/commandandcan
includethesamespecialcharacters(page165).(Thesearch-stringisaregularexpression;referto
AppendixAformoreinformation.)Anotherdelimitermarkstheendofthesearch-stringandthe
beginningofthereplace-string.
Thereplace-stringreplacesthetextmatchedbythesearch-string.Itshouldbefollowedbythedelimiter
character.Youcanomitthefinaldelimiterwhennooptionfollowsthereplace-string;afinaldelimiteris
requiredifanoptionispresent.
Severalcharactershavespecialmeaningsinthesearch-string,andothercharactershavespecial
meaningsinthereplace-string.Forexample,anampersand(&)inthereplace-stringrepresentsthetext
thatwasmatchedbythesearch-string.Abackslashinthereplace-stringquotesthecharacterthat
followsit.RefertoTable6-6andAppendixA.
Table6-6.Searchandreplaceexamples
Command Result
:s/bigger/biggest/
Replacesthefirst
occurrenceofthestring
biggeronthecurrentline
withbiggest
Example:
bigger biggest
:1,.s/Ch1/Ch2/g
Replaceseveryoccurrence
ofthestringCh1,beforeor
onthecurrentline,withthe
stringCh2
Examples:
Ch1 Ch2
Ch12 Ch22

:1,$s/ten/10/g
Replaceseveryoccurrence
ofthestringtenwiththe
string10
Examples:
ten 10
often of10
tenant 10ant
:g/chapter/s/ten/10/
Replacesthefirst
occurrenceofthestringten
withthestring10onalllines
containingthewordchapter
Examples:
chapterten chapter
10
chapterswilloften
chapterswillof10
:%s/\<ten\>/10/g
Replaceseveryoccurrence
ofthewordtenwiththe
string10
Example:
ten 10
:.,.+10s/every/each/g
Replaceseveryoccurrence
ofthestringeverywiththe
stringeachonthecurrent
linethroughthetenth
followingline
Examples:
every each
everything eachthing
:s/\<short\>/"&"/
Replacesthewordshorton
thecurrentlinewith"short"
(enclosedwithinquotation
marks)
Example:
theshortestoftheshort
theshortestofthe
"short"
Normally,theSubstitutecommandreplacesonlythefirstoccurrenceofanytextthatmatchesthesearch-
stringonaline.Ifyouwantaglobalsubstitutionthatis,ifyouwanttoreplaceallmatchingoccurrencesof
textonalineappendtheg(global)optionafterthedelimiterthatendsthereplace-string.Anotheruseful
option,c(check),causesvimtoaskwhetheryouwouldliketomakethechangeeachtimeitfindstext
thatmatchesthesearch-string.Pressingyreplacesthesearch-string,qterminatesthecommand,l(last)
makesthereplacementandquits,a(all)makesallremainingreplacements,andncontinuesthesearch
withoutmakingthatreplacement.
Theaddress-stringneednotbethesameasthesearch-string.Forexample,
:/candle/s/wick/flame/
substitutesflameforthefirstoccurrenceofwickonthenextlinethatcontainsthestringcandle.Similarly,
:g/candle/s/wick/flame/
performsthesamesubstitutionforthefirstoccurrenceofwickoneachlineofthefilecontainingthestring
candleand
:g/candle/s/wick/flame/g
performsthesamesubstitutionforalloccurrencesofwickoneachlinethatcontainsthestringcandle.
Ifthesearch-stringisthesameastheaddress,youcanleavethesearch-stringblank.Forexample,the
command:/candle/s//lamp/isequivalenttothecommand:/candle/s/candle/lamp/.
MiscellaneousCommands
Thissectiondescribesthreecommandsthatdonotfitnaturallyintoanyothergroups.
Join
Join(J)
TheJ(Join)commandjoinsthelinebelowthecurrentlinetotheendofthecurrentline,insertinga
SPACEbetweenwhatwaspreviouslytwolinesandleavingthecursoronthisSPACE.Ifthecurrentline
endswithaperiod,viminsertstwoSPACEs.
Youcanalways"unjoin"(break)alineintotwolinesbyreplacingtheSPACEorSPACEswhereyou
wanttobreakthelinewithaRETURN.
Status
Status(CONTROL-G)
TheStatuscommand,CONTROL-G,displaysthenameofthefileyouareediting,informationabout
whetherthefilehasbeenmodified,thetotalnumberoflinesintheWorkbuffer,thepercentageofthe
Workbufferprecedingthecurrentline,andthenumberofthelineandcharacterthecursorison.Youcan
alsouse:ftodisplaystatusinformation.Followingisasamplestatusline:
"termcap"17103lines--3%--569,1
3%
.(Period)
.
The.(period)commandrepeatsthemostrecentcommandthatmadeachange.Ifyouhadjustgivenad2w
command(deletethenexttwowords),forexample,the.commandwoulddeletethenexttwowords.If
youhadjustinsertedtext,the.commandwouldrepeattheinsertionofthesametext.Thiscommandis
usefulifyouwanttochangesomeoccurrencesofawordorphraseintheWorkbuffer.Searchforthefirst
occurrenceoftheword(use/)andthenmakethechangeyouwant(usecw).Youcanthenusentosearch
forthenextoccurrenceofthewordand.tomakethesamechangetoit.Ifyoudonotwanttomakethe
change,usenagaintofindthenextoccurrence.
Yank,Put,andDeleteCommands
ThevimeditorhasaGeneral-Purposebufferand26Namedbuffersthatcanholdtextduringanediting
session.Thesebuffersareusefulifyouwanttomoveorcopyaportionoftexttoanotherlocationinthe
Workbuffer.AcombinationoftheDeleteandPutcommandsremovestextfromonelocationintheWork
bufferandplacesitinanotherlocationintheWorkbuffer.TheYankandPutcommandscopytextto
anotherlocationintheWorkbuffer,withoutchangingtheoriginaltext.
TheGeneral-PurposeBuffer
Thevimeditorstoresthetextthatyoumostrecentlychanged,deleted,oryankedintheGeneral-Purpose
buffer.TheUndocommandretrievestextfromtheGeneral-Purposebufferwhenitrestorestext.
CopyingTexttotheBuffer
Yank(y/Y)
TheYankcommand(y)isidenticaltotheDelete(d)commandexceptthatitdoesnotdeletetextfromthe
Workbuffer.ThevimeditorplacesacopyoftheyankedtextintheGeneral-Purposebuffer.Youcanthen
useaPutcommandtoplaceanothercopyofitelsewhereintheWorkbuffer.UsetheYankcommandjust
asyouusetheDeletecommand.TheuppercaseYcommandyanksanentirelineintotheGeneral-Purpose
buffer.
tip:Useyytoyankoneline
JustasdRETURNdeletestwolines,soyRETURNyankstwolines.Usetheyycommand
toyankandddtodeletethecurrentline.
tip:DworksdifferentlyfromY
TheDcommand(page160)doesnotworkinthesamemannerastheYcommand.Whereas
Ddeletestotheendoftheline,Yyankstheentirelineregardlessofthecursorposition.
CopyingTextFromtheBuffer
Put(p/P)
ThePutcommands,pandP,copytextfromtheGeneral-PurposebuffertotheWorkbuffer.Ifyoudeleteor
yankcharactersorwordsintotheGeneral-Purposebuffer,pinsertsthemafterthecurrentcharacter,and
Pinsertsthembeforethischaracter.Ifyoudeleteoryanklines,sentences,orparagraphs,Pinsertsthe
contentsoftheGeneral-Purposebufferbeforethelinethecursorison,andpinsertsthemafterthisline.
PutcommandsdonotdestroythecontentsoftheGeneral-Purposebuffer.Thusyoucanplacethesametext
atseveralpointswithinthefilebyusingoneDeleteorYankcommandandseveralPutcommands.
DeletingTextCopiesItintotheBuffer
AnyoftheDeletecommandsdescribedearlierinthischapter(page160)placethedeletedtextinthe
General-Purposebuffer.JustasyoucanusetheUndocommandtoputthedeletedtextbackwhereitcame
from,soyoucanuseaPutcommandtoputthedeletedtextatanotherlocationintheWorkbuffer.
Forexample,ifyoudeleteawordfromthemiddleofasentencebyusingthedwcommandandthenmove
thecursortoaSPACEbetweentwowordsandgiveapcommand,vimplacesthewordyoujustdeleted
atthenewlocation.Ifyoudeletealineusingtheddcommandandthenmovethecursortothelinebelow
thelinewhereyouwantthedeletedlinetoappearandgiveaPcommand,vimplacesthelineatthenew
location.

optional:NamedBuffers
YoucanuseaNamedbufferwithanyoftheDelete,Yank,orPutcommands.Eachofthe26Namedbuffersisnamedbyaletter
ofthealphabet.EachNamedbuffercanstoreadifferentblockoftextsothatyoucanrecalleachblockasneeded.Unlikethe
General-Purposebuffer,vimdoesnotchangethecontentsofaNamedbufferunlessyouuseacommandthatspecifically
overwritesthatbuffer.ThevimeditormaintainsthecontentsoftheNamedbuffersthroughoutaneditingsession.
ThevimeditorstorestextinaNamedbufferifyouprecedeaDeleteorYankcommandwithadoublequotationmark(")anda
buffername(forexample,"kyyyanksacopyofthecurrentlineintobufferk).YoucanuseaNamedbufferintwoways.First,
ifyougivethenameofthebufferasalowercaseletter,vimoverwritesthecontentsofthebufferwhenitdeletesoryankstext
intothebuffer.Second,ifyouuseanuppercaseletterforthebuffername,vimappendsthenewlydeletedoryankedtexttothe
endofthebuffer.Thisfeatureenablesyoutocollectblocksoftextfromvarioussectionsofafileanddepositthematoneplacein
thefilewithasinglecommand.Namedbuffersarealsousefulwhenyouaremovingasectionofafileanddonotwanttousea
PutcommandimmediatelyafterthecorrespondingDeletecommand,andwhenyouwanttoinsertaparagraph,sentence,or
phraserepeatedlyinadocument.
Ifyouhaveonesentencethatyouusethroughoutadocument,youcanyankthatsentenceintoaNamedbufferandputit
whereveryouneeditbyusingthefollowingprocedure:AfterenteringthefirstoccurrenceofthesentenceandpressingESCAPE
toreturntoCommandmode,leavethecursoronthelinecontainingthesentence.(Thesentencemustappearonalineorlinesby
itselfforthisproceduretowork.)ThenyankthesentenceintoNamedbufferabygivingthe"ayycommand(or"a2yyifthe
sentencetakesuptwolines).Nowanytimeyouneedthesentence,youcanreturntoCommandmodeandgivethecommand"ap
toputacopyofthesentencebelowthelinethecursorison.
Thistechniqueprovidesaquickandeasywaytoinserttextthatyouusefrequentlyinadocument.Forexample,ifyouwere
editingalegaldocument,youmightstorethephraseThePlaintiffallegesthattheDefendantinaNamedbuffertosave
yourselfthetroubleoftypingiteverytimeyouwanttouseit.Similarly,ifyouwerecreatingaletterthatfrequentlyusedalong
companyname,suchasNationalStandardsInstitute,youmightputitintoaNamedbuffer.
NUMBEREDBUFFERS
Inadditiontothe26Namedbuffersand1General-Purposebuffer,9Numberedbuffersareavailable.Theyare,inonesense,
readonlybuffers.Thevimeditorfillsthemwiththeninemostrecentlydeletedchunksoftextthatareatleastonelinelong.The
mostrecentlydeletedpatternisheldin"1,thenextmostrecentin"2,andsoon.Ifyoudeleteablockoftextandthengiveother
vimcommandssothatyoucannotreclaimthedeletedtextwithUndo,use"1ptopastethemostrecentlydeletedchunkoftext
belowthelocationofthecursor.Ifyouhavedeletedseveralblocksoftextandwanttoreclaimaspecificone,proceedasfollows:
Pastethecontentsofthefirstbufferwith"1p.Ifthefirstbufferdoesnothavethetextyouarelookingfor,undothepastewithu
andthengivetheperiod(.)commandtorepeatthepreviouscommand.TheNumberedbuffersworkinauniquewaywiththe
periodcommand:Insteadofpastingthecontentsofbuffer"1,theperiodcommandpastesthecontentsofthenextbuffer("2).
Anotheruandperiodreplacethecontentsofbuffer"2withthatofbuffer"3,andsoonthroughtheninebuffers.
ReadingandWritingFiles
Exit(ZZ)
ThevimeditorreadsadiskfileintotheWorkbufferwhenyouspecifyafilenameonthecommandline
youusetocallvim.TheZZcommandthatterminatestheeditingsessionwritesthecontentsoftheWork
bufferbacktothediskfile.ThissectiondiscussesotherwaysofreadingtextintotheWorkbufferand
writingittoafile.
ReadingFiles
Read(:r)
TheReadcommandreadsafileintotheWorkbuffer.ThenewfiledoesnotoverwriteanytextintheWork
bufferbutratherispositionedfollowingthesingleaddressyouspecify(orthecurrentlineifyoudonot
specifyanaddress).Youcanuseanaddressof0toreadthefileintothebeginningoftheWorkbuffer.The
Readcommandhasthefollowingsyntax:
:[address]r[filename]
Aswithothercommandsthatbeginwithacolon,whenyouenterthecolonitappearsonthestatusline.
ThefilenameisthepathnameofthefilethatyouwanttoreadandmustbeterminatedbyRETURN.Ifyou
omitthefilename,vimreadsthefileyouareeditingfromthedisk.
WritingFiles
Write(:w)
TheWritecommandwritespartoralloftheWorkbuffertoafile.Youcanuseanaddresstowriteout
partoftheWorkbufferandafilenametospecifyafiletoreceivethetext.Ifyoudonotuseanaddressor
filename,vimwritestheentirecontentsoftheWorkbuffertothefileyouareediting,updatingthefileon
thedisk.
Duringalongeditingsession,itisagoodideatousetheWritecommandoccasionally.Ifaproblemlater
develops,arecentcopyoftheWorkbufferisthensafeonthedisk.Ifyouusea:q!commandtoexitfrom
vim,thediskfilereflectstheversionoftheWorkbufferatthetimeyoulastusedtheWritecommand.The
Writecommandhastwopossibleformats:
:[address]w[!][filename]
:[address]w>>filename
Thesecondformatappendstexttoanexistingfile.TheaddressspecifiestheportionoftheWorkbuffer
vimwillwritetothefile.TheaddressfollowstheformoftheaddressthattheSubstitutecommanduses
(page167).Ifyoudonotspecifyanaddress,vimwritestheentirecontentsoftheWorkbuffer.The
optionalfilenameisthepathnameofthefileyouarewritingto.Ifyoudonotspecifyafilename,vim
writestothefileyouareediting.
w!
BecausetheWritecommandcanquicklydestroyalargeamountofwork,vimdemandsthatyouenteran
exclamationpoint(!)followingthewasasafeguardagainstaccidentallyoverwritingafile.Theonly
timesyoudonotneedanexclamationpointarewhenyouarewritingouttheentirecontentsoftheWork
buffertothefilebeingedited(usingnoaddressandnofilename)andwhenyouarewritingpartorallof
theWorkbuffertoanewfile.Whenyouarewritingpartofthefiletothefilebeingeditedorwhenyou
areoverwritinganotherfile,youmustuseanexclamationpoint.
IdentifyingtheCurrentFile
TheFilecommand(:f)providesthesameinformationastheStatuscommand(CONTROL-G,page171).
ThefilenametheFilecommanddisplaysistheonetheWritecommandusesifyougivea:wcommand
withoutafilename.
SettingParameters
Youcantailorthevimeditortoyouruniqueneedsandhabitsbysettingvimparameters.Parameters
performsuchfunctionsasdisplayinglinenumbers,automaticallyinsertingRETURNsforyou,and
establishingincrementalandnonstandardsearches.
Youcansetparametersinseveralways.Forexample,youcansetthemtoestablishtheenvironmentfor
thecurrenteditingsessionwhileyouareusingvim.Alternatively,youcansettheparametersinyour
~/.bash_profile(bash)or~/.login(tcsh)shellstartupfileorinthevimstartupfile,~/.vimrc.When
yousettheparametersinanyofthesefiles,eachtimeyouusevim,theenvironmenthasbeenestablished
andyoucanbegineditingimmediately.
SettingParametersfromWithinvim
Tosetaparameterwhileyouareusingvim,enteracolon(:),thewordset,aSPACE,andtheparameter
(referto"Parameters"onpage177).Thecommandappearsonthestatuslineasyoutypeitandtakes
effectwhenyoupressRETURN.Thefollowingcommandestablishesincrementalsearchesforthecurrent
editingsession:
:setincsearch
SettingParametersinaStartupFile
VIMINIT
Ifyouareusingbash,youcanputalinewiththefollowingformatinyour~/.bash_profilestartupfile
(page257):
exportVIMINIT='setparam1param2...'
Replaceparam1andparam2withparametersselectedfromTable6-7.VIMINITisashellvariablethat
vimreads.Thefollowingstatementignoresthecaseofcharactersinsearches,displayslinenumbers,
usestheTCShelltoexecuteLinuxcommands,andwrapstext15charactersfromtherightedgeofthe
screen:

exportVIMINIT='setautoindentnumbershell=/bin/tcshwrapmargin=15'
Table6-7.Parameters
Parameter Effect
Allowspecialcharactersin
searches
magic
Referto"SpecialCharactersinSearchStrings"onpage165.By
defaultthefollowingcharactershavespecialmeaningswhenused
inasearchstring:
.[]*
Whenyousetthenomagicparameter,thesecharactersnolonger
havespecialmeanings.Themagicparameterrestorestheirspecial
meanings.
The^and$charactersalwayshavespecialmeaningswithin
searchstrings,regardlessofhowyousetthisparameter.
Automaticindention
autoindent,ai
Theautomaticindentionfeatureworkswiththeshiftwidth
parametertoprovidearegularsetofindentionsforprogramsor
tabularmaterial.Thisfeatureisoffbydefault.Youcanturniton
bysettingautoindentandturnitoffbysettingnoautoindent.
WhenautomaticindentionisonandvimisinInputmode,
CONTROL-Tmovesthecursorfromtheleftmargin(oran
indention)tothenextindentionposition,RETURNmovesthe
cursortotheleftsideofthenextlineunderthefirstcharacterof
thepreviousline,andCONTROL-Dbacksupoverindention
positions.TheCONTROL-TandCONTROL-Dkeysworkonly
beforetextisplacedonaline.
Automaticwrite
autowrite,aw
BydefaultvimasksyoubeforewritingouttheWorkbufferwhen
youhavenotexplicitlytoldittodoso(aswhenyougivea:n
commandtoeditthenextfile).Theautowriteoptioncausesvim
towritetheWorkbufferautomaticallywhenyouusecommands,
suchas:n,toedittoanotherfile.Youcandisablethisparameterby
settingthenoautowriteornoawoption.
Flash
flash,fl
Thevimeditornormallycausestheterminaltobeepwhenyougive
aninvalidcommandorpressESCAPEwhenitisinCommand
mode.Settingtheparameterflashcausestheterminaltoflash
insteadofbeep.Setnoflashtocauseittobeep.Notallterminals
andemulatorssupportthisparameter.
Ignorecaseinsearches
ignorecase,ic
Thevimeditornormallyperformscase-sensitivesearches,
differentiatingbetweenuppercaseandlowercaseletters.It
performscase-insensitivesearcheswhenyousettheignorecase
parameter.Setnoignorecasetorestorecase-sensitivesearches.
Incrementalsearch
Referto"NormalVersusIncrementalSearches"onpage165.By
defaultvimdoesnotperformincrementalsearches.Tocausevim
toperformincrementalsearches,settheparameterincsearch.To

incsearch,is causevimnottoperformincrementalsearches,settheparameter
noincsearch.
Invisiblecharacters
list
TocausevimtodisplayeachTABas^Iandtomarktheendof
eachlinewitha$,setthelistparameter.TodisplayTABsas
whitespaceandnotmarkendsoflines,setnolist.
Statusline
laststatus=n,ls=n
Displaysastatuslinethatshowsthenameofthefileyouare
editing,a[+]ifthefilehasbeenchangedsinceitwaslastwritten
out,andthepositionofthecursor.Settheparameterlaststatus=n,
wherenis0(zero)toturnoffthestatusline,1todisplaythe
statuslinewhenatleasttwowindowsaredisplayed,or2toalways
displaythestatusline.
Linenumbers
number,nu
Thevimeditordoesnotnormallydisplaythelinenumber
associatedwitheachline.Todisplaylinenumbers,setthe
parameternumber.Tocauselinenumbersnottobedisplayed,set
theparameternonumber.
Linenumbersarenotpartofthefile,arenotstoredwiththefile,
andarenotdisplayedwhenthefileisprinted.Theyappearonthe
screenonlywhileyouareusingvim.
Linewrap
wrap
Thelinewrapcontrolshowvimdisplayslinesthataretoolongto
fitonthescreen.Tocausevimtowraplonglinesandcontinue
themonthenextline,setwrap(setbydefault).Ifyousetnowrap,
vimTRuncateslonglinesattherightedgeofthescreen.
Linewrapmargin
wrapmargin=nn,wm=nn
Thelinewrapmargincausesvimtobreakthetextthatyouare
insertingatapproximatelythespecifiednumberofcharactersfrom
therightmargin.Thevimeditorbreaksthetextbyinsertinga
NEWLINEcharacterattheclosestblank-delimitedwordboundary.
Settingthelinewrapmarginishandyifyouwantallyourtextlines
tobeaboutthesamelength.Itrelievesyouofhavingtoremember
topressRETURNtoendeachlineofinput.
Settheparameterwrapmargin=nn,wherennisthenumberof
charactersfromtherightsideofthescreenwhereyouwantvim
tobreakthetext.Thisnumberisnotthecolumnwidthofthetext
butthedistancefromtheendofthetexttotherightedgeofthe
screen.Settingthewrapmarginto0(zero)turnsthisfeatureoff.
Bydefaultthelinewrapmarginisoff(setto0).
Report
report=nn
Causesvimtodisplayareportonthestatuslinewheneveryou
makeachangethataffectsatleastnnlines.Forexample,ifreport
issetto7andyoudeletesevenlines,vimdisplaysthemessage7
linesdeleted.Whenyoudeletesixorfewerlines,vimdoesnot
displayamessage.Thedefaultforreportis5.
Scroll
scroll=nn,scr=nn
ControlsthenumberoflinesthatCONTROL-DandCONTROL-U
(page158)scrolltextonthescreen.Bydefaultscrollissettohalf
thewindowheight.
Therearetwowaystochangethevalueofscroll.Firstyoucan
enteranumberbeforegivingaCONTROL-DorCONTROL-U
command;vimsetsscrolltothatnumber.Alternatively,youcan
setscrollexplicitlywithscroll=nn,wherennisthenumberof
linesyouwanttoscrollwitheachCONTROL-DorCONTROL-U
command.

Shell
shell=path,sh=path
Whileyouareusingvim,youcancauseittospawnanewshell.
Youcaneithercreateaninteractiveshell(ifyouwanttorunseveral
commands)orrunasinglecommand.Theshellparameter
determineswhichshellviminvokes.Bydefaultvimsetstheshell
parametertoyourloginshell.Tochangeit,settheparameter
shell=path,wherepathistheabsolutepathnameoftheshellyou
wanttouse.
Shiftwidth
shiftwidth=nn,sw=nn
ControlsthefunctioningofCONTROL-TandCONTROL-Din
Inputmodewhenautomaticindentionison(see"Automatic
indention"inthistable).Settheparametershiftwidth=nn,where
nnisthespacingoftheindentionpositions(8bydefault).Setting
theshiftwidthissimilartosettingtheTABstopsonatypewriter;
withshiftwidth,however,thedistancebetweenTABstopsremains
constant.
Showmatch
showmatch,sm
Usefulforprogrammersworkinginlanguagesthatusebraces({})
orparenthesesasexpressiondelimiters(Lisp,C,Tcl,andsoon).
Whenshowmatchissetandyouareenteringcode(inInputmode)
andtypeaclosingbraceorparenthesis,thecursorjumpsbrieflyto
thematchingopeningbraceorparenthesis(thatis,thepreceding
correspondingelementatthesamenestinglevel).Afterithighlights
thematchingelement,thecursorresumesitspreviousposition.
Whenyoutypearightbraceorparenthesisthatdoesnothavea
match,vimbeeps.Usenoshowmatchtoturnoffautomatic
matching.
Showmode
showmode,smd
Settheparametershowmodetodisplaythemodeinthelower-right
cornerofthescreenwhenvimisinInputmode(default).Set
noshowmodetocausevimnottodisplaythemode.
vicompatibility
compatible,cp
Referto"ThecompatibleParameter"onpage148.Bydefault,
exceptwhenyouhavea.vimrcstartupfile(page176),vim
attemptstobecompatiblewithvi.Tocausevimtobecompatible
withvi,settheparametercompatible.Tocausevimnottobe
compatiblewithvi,settheparameternocompatible.
Wrapscan
wrapscan,ws
Bydefault,whenasearchforthenextoccurrenceofasearch
stringreachestheendoftheWorkbuffer,vimcontinuesthe
searchatthebeginningoftheWorkbuffer.Thereverseistrueofa
searchforthepreviousoccurrenceofasearchstring.The
nowrapscanparameterstopsthesearchateitherendoftheWork
buffer.Setthewrapscanparameterifyouwantsearchestowrap
aroundtheendsoftheWorkbuffer.
Ifyouusetheparameterabbreviations,itlookslikethis:
exportVIMINIT='setainush=/bin/tcshwm=15'
Ifyouareusingtcsh,putthefollowinglineinyour~/.tcshrcstartupfile(page342).
setenvVIMINIT'setparam1param2...'
Again,replaceparam1andparam2withparametersfromTable6-7.Thevaluesbetweenthesingle
quotationmarksarethesameasshownintheprecedingexamples.
The.vimrcStartupFile
Insteadofsettingvimparametersinyourshellstartupfile,youcancreatea~/.vimrcfileinyourhome
directoryandsetthemthere.Creatinga.vimrcfilecausesvimtostartwiththecompatibleparameter
unset(page148).Linesina.vimrcfileusethefollowingformat:
setparam1param2...
Followingareexamplesof.vimrcfilesthatperformthesamefunctionasVIMINITdescribedpreviously:
$cat~/.vimrc
setignorecase
setnumber
setshell=/bin/tcsh
setwrapmargin=15
$cat~/.vimrc
seticnush=/bin/tcshwm=15
ParameterssetbytheVIMINITvariabletakeprecedenceoverthosesetinthe.vimrcfile.
Parameters
Table6-7listssomeofthemostusefulvimparameters.Thevimeditordisplaysacompletelistof
parametersandindicateshowtheyarecurrentlysetwhenyougivethecommand:setallfollowedbya
RETURN.Thecommand:setRETURNdisplaysalistofoptionsthataresettovaluesotherthantheir
defaultvalues.Twoclassesofparametersexist:thosethatcontainanequalsign(andcantakeonavalue)
andthosethatareoptionallyprefixedwithno(switchesthatareonoroff).Youcanchangethesenseofa
switchparameterbygivingthecommand:set[no]param.Forexample,givethecommand:setnumber
(or:setnonumber)toturnon(oroff)linenumbering.Tochangethevalueofaparameterthattakesona
value(andusesanequalsign),giveacommandsuchas:setshiftwidth=15.
Mostparametershaveabbreviationssuchasnufornumber,nonufornonumber,andswforshiftwidth.
TheabbreviationsarelistedintheleftcolumnofTable6-7,followingthenameoftheparameter.
AdvancedEditingTechniques
Thissectionpresentsseveralcommandsthatyoumayfindusefulonceyouhavebecomecomfortable
usingvim.

optional:UsingMarkers
Whileyouareusingvim,youcansetandusemarkerstomakeaddressingmoreconvenient.Setamarkerbygivingthecommand
mc,wherecisanycharacter.(Lettersarepreferredbecausesomecharacters,suchasasinglequotationmark,havespecial
meaningswhenusedasmarkers.)Thevimeditordoesnotpreservemarkerswhenyouexitfromvim.
Onceyouhavesetamarker,youcanuseitinamannersimilartoalinenumber.Youcanmovethecursortothebeginningofa
linethatcontainsamarkerbyprecedingthemarkernamewithasinglequotationmark.Forexample,tosetmarkert,positionthe
cursoronthelineyouwanttomarkandgivethecommandmt.Duringthiseditingsession,unlessyouresetmarkertordeletethe
lineitmarks,youcanreturntothebeginningofthelineyoumarkedwiththecommand't.
Youcandeletealltextfromthecurrentlinethroughthelinecontainingmarkerrwiththefollowingcommand:
d'r
Youcanuseabacktick(',alsocalledagraveaccentorreversesinglequotationmark)togototheexactpositionofthemarkon
theline.Aftersettingmarkert,youcanmovethecursortothelocationofthismarker(notthebeginningofthelinethatholdsthe
marker)withthecommand't.Thefollowingcommanddeletesallthetextfromthecurrentlineuptothecharacterwherethe
markrwasplaced;therestofthelinecontainingthemarkerremainsintact:
d'r
Youcanusemarkersinaddressesofcommandsinsteadoflinenumbers.ThefollowingcommandreplacesalloccurrencesofThe
withTHEonalllinesfrommarkermtothecurrentline(markermmustprecedethecurrentline):
:'m,.s/The/THE/g
EDITINGOTHERFILES
Thefollowingcommandcausesvimtoeditthefileyouspecifywithfilename:
:e[!][filename]
IfyouwanttosavethecontentsoftheWorkbuffer,youmustwriteitout(using:w)beforeyougivethiscommand.Ifyoudonot
wanttosavethecontentsoftheWorkbuffer,viminsiststhatyouuseanexclamationpointtoacknowledgethatyouwilllosethe
workyoudidsincethelasttimeyouwroteouttheWorkbuffer.Ifyoudonotsupplyafilename,vimeditsthesamefileyouare
currentlyworkingon.
:e!
Thecommand:e!startsaneditingsessionoveragain.ThiscommandreturnstheWorkbuffertothestateitwasinthelasttime
youwroteitoutor,ifyouhavenotwrittenitout,thestateitwasinwhenyoustartededitingthefile.Itisusefulwhenyoumake
mistakeswhileeditingafileanddecidethatitwouldbeeasiertostartoverthantofixthemistakes.
BecausethiscommanddoesnotdestroythecontentsoftheGeneral-PurposeorNamedbuffers,youcanstoretextfromonefilein
abuffer,usea:ecommandtoeditasecondfile,andputtextfromthebufferinthesecondfile.
:e#
Thecommand:e#closesthecurrentfileandopensthelastfileyouwereediting,placingthecursoronthelinethatitwason
whenyoulastclosedthefile.Ifyoudonotsavethefileyouareworkingonbeforeyougivethiscommand,vimpromptsyouto
doso.Settingtheautowriteparameter(page178)willnotstopvimfrompromptingyou.
:n
:rew

The:e#commandcanhelpyoucopyblocksoftextfromonefiletoanother.Callvimwiththenamesofseveralfilesas
arguments.Youcanuse:ntoeditthenextfile,:e#toeditthefileyoujustedited,and:rewtorewindthesequenceoffilessothat
youareeditingthefirstfileagain.Asyoumovebetweenfiles,youcancopytextfromonefileintoabufferandpastethattextinto
anotherfile.Youcanuse:n!toforcevimtocloseafilewithoutwritingoutchangesbeforeitopensthenextfile.
MACRO S ANDSHO RTCUTS
:map
Thevimeditorallowsyoutocreatemacrosandshortcuts.The:mapcommanddefinesakeyorsequenceofkeysthatperform
someactioninCommandmode.ThefollowingcommandmapsCONTROL-Xtothecommandsthatwillfindthenextleftbracket
onthelinethecursorison(f[),deleteallcharactersfromthatbrackettothenextrightbracket(df])onthesameline,deletethe
nextcharacter(x),movethecursordowntwolines(2j),andfinallymovethecursortothebeginningoftheline(0):
:map^Xf[df]x2j0
YoucanuseESCAPEandCONTROLsequencesbuttrytoavoidremappingcharactersorsequencesthatarevimcommands.
Type:mapbyitselftoseealistofthecurrentmappings.YoumayneedtouseCONTROL-V(page159)toquotesomeofthe
charactersyouwanttoenterintothe:mapstring.
:abbrev
The:abbrevcommandissimilarto:mapbutcreatesabbreviationsyoucanusewhileinInputmode.WhenyouareinInputmode
andtypeastringyouhavedefinedwith:abbrev,followedbyaSPACE,vimreplacesthestringandtheSPACEwiththe
charactersyouspecifiedwhenyoudefinedthestring.Foreaseofuse,donotusecommonsequencesofcharacterswhencreating
abbreviations.ThefollowingcommanddefinesZZasanabbreviationforMarkG.Sobell:
:abbrevZZMarkG.Sobell
EventhoughZZisavimcommand,itisusedonlyinCommandmode.IthasnospecialmeaninginInputmode,whereyouuse
abbreviations.
ExecutingShellCommandsfromWithinvim
Youcanexecuteshellcommandsinseveralwayswhileyouareusingvim.Youcanspawnanew
interactiveshellbygivingthefollowingcommandandpressingRETURN:
:sh
Thevimshellparameter(page179)determineswhichshellisspawned(usuallybashortcsh).By
defaultshellisthesameasyourloginshell.
Afteryouhavefinishedyourworkintheshell,youcanreturntovimbyexitingfromtheshell(press
CONTROL-Dorgiveanexitcommand).
tip:If:shdoesnotworkcorrectly
The:shcommandmaybehavestrangelydependingonhowyourshellhasbeenconfigured.
Youmaygetwarningswiththe:shcommandoritmayevenhang.Experimentwiththe:sh
commandtobesureitworkswithyourconfiguration.Ifitdoesnot,thenyoumightwantto
setthevimshellparametertoanothershellbeforeusing:sh.Forexample,thefollowing
commandcausesvimtousetcshwiththe:shcommand:
:setshell=/bin/tcsh
YoumayneedtochangetheSHELLenvironmentvariableafterstarting:shtoshowthe
correctshell.
caution:Editonlyonecopyofafile
Whenyoucreateanewshellbyusing:sh,rememberthatyouarestillusingvim.A
commonmistakeistotrytoeditthesamefilefromthenewshell,forgettingthatvimis
alreadyeditingthefilefromadifferentshell.Becauseyoucanloseinformationbyediting
thesamefilefromtwoinstancesofaneditor,vimwarnsyouwhenyoumakethismistake.
Referto"FileLocks"onpage152toseeanexampleofthemessagethatvimdisplays.
Youcanexecuteashellcommandlinefromvimbygivingthefollowingcommand,replacingcommand
withthecommandlineyouwanttoexecuteandterminatingthecommandwithaRETURN:
:!command
Thevimeditorspawnsanewshellthatexecutesthecommand.Whenthecommandrunstocompletion,
thenewlyspawnedshellreturnscontroltotheeditor.
Youcanexecuteacommandfromvimandhaveitreplacethecurrentlinewiththeoutputfromthe
command.Ifyoudonotwanttoreplaceanytext,putthecursoronablanklinebeforegivingthefollowing
command:
!!command
Nothinghappenswhenyouenterthefirstexclamationpoint.Whenyouenterthesecondone,vimmoves
thecursortothestatuslineandallowsyoutoenterthecommandyouwanttoexecute.Becausethis
commandputsviminLastLinemode,youmustendthecommandwithaRETURN(asyouwouldend
mostshellcommands).
Finallyyoucanexecuteacommandfromvimwithstandardinputtothecommandcomingfromallorpart
ofthefileyouareeditingandstandardoutputfromthecommandreplacingtheinputinthefileyouare
editing.Youcanusethistypeofcommandtosortalistinplacewithinafile.
Tospecifytheblockoftextthatwillbecomestandardinputforthecommand,movethecursortooneend
oftheblockoftext.Thenenteranexclamationpointfollowedbyacommandthatwouldnormallymove
thecursortotheotherendoftheblockoftext.Forexample,ifthecursorisatthebeginningofthefileand
youwanttospecifythewholefile,givethecommand!G.Ifyouwanttospecifythepartofthefile
betweenthecursorandmarkerb,givethecommand!'b.Afteryougivethecursor-movementcommand,
vimdisplaysanexclamationpointonthestatuslineandwaitsforyoutoenterashellcommand.
Tosortalistofnamesinafile,movethecursortothebeginningofthelistandsetmarkerqwithanmq
command.Thenmovethecursortotheendofthelistandgivethefollowingcommand:
!'sort
PressRETURNandwait.Afterafewseconds,thesortedlistshouldreplacetheoriginallistonthe
screen.Ifthecommanddidnotdowhatyouexpected,youcanusuallyundothechangewithaucommand.
Refertopage762formoreinformationonsort.
caution:!candestroyafile
Ifyouenterthewrongcommandormistypeacommand,youcandestroyafile(for
example,ifthecommandhangsorstopsvimfromworking).Forthisreasonitisagood
ideatosaveyourfilebeforeusingthiscommand.TheUndocommand(page160)canbea
lifesaver.A:e!command(page181)willgetridofyourchanges,returningthebuffertothe
stateitwasinlasttimeyousavedit.
Aswiththe:shcommand,thedefaultshellmaynotworkproperlywiththe!command.You
maywanttotesttheshellwithasimplefilebeforeexecutingthiscommandwithyourreal
work.Iftheusualshelldoesnotworkproperly,changetheshellparameter.

UnitsofMeasure
Manyvimcommandsoperateonablockoftextrangingfromonecharactertomanyparagraphs.You
specifythesizeofablockoftextwithaUnitofMeasure.YoucanspecifymultipleUnitsofMeasureby
precedingaUnitofMeasurewithaRepeatFactor(page187).ThissectiondefinesthevariousUnitsof
Measure.
Character
Acharacterisonecharactervisibleornot,printableornotincludingSPACEsandTABs.Someexamples
ofcharactersare
aqA.5R->TABSPACE
Word
Aword,similartoanordinarywordintheEnglishlanguage,isastringofoneormorecharacters
boundedonbothsidesbyanycombinationofoneormoreofthefollowingelements:apunctuationmark,
SPACE,TAB,numeral,orNEWLINE.Inaddition,vimconsiderseachgroupofpunctuationmarkstobe
aword(Table6-8).
Table6-8.Words
Wordcount Text
1pear
2pear!
2pear!)
3pear!)The
4pear!)"The
11 Thisisashort,conciseline(nofrills).

Blank-DelimitedWord
Ablank-delimitedwordisthesameasawordbutincludesadjacentpunctuation.Blank-delimitedwords
areseparatedbyoneormoreofthefollowingelements:aSPACE,TAB,orNEWLINE(Table6-9).
Table6-9.Blank-delimitedwords
Wordcount Text
1pear
1pear!
1pear!)
2pear!)The
2pear!)"The
8Thisisashort,conciseline(nofrills).
Line
AlineisastringofcharactersboundedbyNEWLINEsthatisnotnecessarilydisplayedasasingle
physicallineonthescreen.Youcanenteraverylongsingle(logical)linethatwrapsaround(continueson
thenextphysicalline)severaltimesordisappearsofftherightedgeofthedisplay.Itisagoodideato
avoidlonglogicallinesbyterminatinglineswithaRETURNbeforetheyreachtherightsideofthe
screen.Terminatinglinesinthismannerensuresthateachphysicallinecontainsonelogicallineand
avoidsconfusionwhenyoueditandformattext.Somecommandsdonotappeartoworkproperlyon
physicallinesthatarelongerthanthewidthofthescreen.Forexample,withthecursoronalonglogical
linethatwrapsaroundseveralphysicallines,pressingRETURNonceappearstomovethecursordown
morethanoneline.Youcanusefmt(page664)tobreaklonglogicallinesintoshorterones.
Sentence
AsentenceisanEnglishsentenceortheequivalent.Asentencestartsattheendoftheprevioussentence
andendswithaperiod,exclamationpoint,orquestionmark,followedbytwoSPACEsoraNEWLINE
(Table6-10).
Table6-10.Sentences

Table6-10.Sentences
Sentencecount Text
One:onlyoneSPACEafterthefirstperiodandaNEWLINEafter
thesecondperiod
That'sit.Thisis
onesentence.
Two:twoSPACEsafterthefirstperiodandaNEWLINEafterthe
secondperiod
That'sit.Thisis
twosentences.
Three:twoSPACEsafterthefirsttwoquestionmarksanda
NEWLINEaftertheexclamationpoint
What?Three
sentences?Oneline!
One:NEWLINEaftertheperiod
Thissentencetakes
upatotalof
threelines.
Paragraph
Aparagraphisprecededandfollowedbyoneormoreblanklines.Ablanklineiscomposedoftwo
NEWLINEcharactersinarow(Table6-11).
Table6-11.Paragraphs
Paragraphcount Text
One:blanklinebeforeandaftertext One
paragraph
One:blanklinebeforeandaftertext
This
mayappear
tobe
morethan
one
paragraph.
Just
because
thereare
two
indentions
doesnot
mean

it
qualifies
astwo
paragraphs.
Three:threeblocksoftextseparatedbyblanklines
Eventhough
in
English
thisis
only
one
sentence,
vim
considers
ittobe
three
paragraphs.
Window
Undervim,ascreenorterminalemulatorwindowcandisplayoneormorelogicalwindowsof
information.AwindowdisplaysallorpartofaWorkbuffer.Figure6-5onpage145showsascreenwith
twowindows.
RepeatFactor
AnumberthatprecedesaUnitofMeasure(page184)isaRepeatFactor.Justasthe5in5inchescauses
youtoconsider5inchesasasingleUnitofMeasure,soaRepeatFactorcausesvimtogroupmorethan
oneUnitofMeasureandconsideritasasingleUnitofMeasure.Forexample,thecommandwmovesthe
cursorforward1word,thecommand5wmovesitforward5words,andthecommand250wmovesit
forward250words.IfyoudonotspecifyaRepeatFactor,vimassumesaRepeatFactorof1.Ifthe
RepeatFactorwouldmovethecursorpasttheendofthefile,thecursorisleftattheendofthefile.

ChapterSummary
Thissummaryofvimincludesallthecommandscoveredinthischapter,plusafewmore.Table6-12
listssomeofthewaysyoucancallvimfromthecommandline.
Table6-12.Callingvim
Command Result
vimfilename Editsfilenamestartingatline1
vim+nfilename Editsfilenamestartingatlinen
vim+filename Editsfilenamestartingatthelastline
vim+/patternfilename Editsfilenamestartingatthefirstline
containingpattern
vimrfilename Recoversfilenameafterasystemcrash
vimRfilename Editsfilenamereadonly(sameasopening
thefilewithview)
YoumustbeinCommandmodetousecommandsthatmovethecursorbyUnitsofMeasure(Table6-13).
YoucanusetheseUnitsofMeasurewithChange,Delete,andYankcommands.Eachofthesecommands
canbeprecededbyaRepeatFactor.
Table6-13.MovingthecursorbyUnitsofMeasure
Command Movesthecursor
SPACE,l(ell),or
RIGHTARROW
Spacetotheright
horLEFTARROW Spacetotheleft
wWordtotheright
WBlank-delimitedwordtotheright
bWordtotheleft
BBlank-delimitedwordtotheleft

$Endofline
eEndofwordtotheright
EEndofblank-delimitedwordtotheright
0(zero) Beginningofline(cannotbeusedwithaRepeatFactor)
RETURN Beginningofnextline
jorDOWNARROW Downoneline
Beginningofpreviousline
korUPARROW Uponeline
)Endofsentence
(Beginningofsentence
}Endofparagraph
{Beginningofparagraph
%Movetomatchingbraceofsametypeatsamenestinglevel
Table6-14showsthecommandsthatenableyoutoviewdifferentpartsoftheWorkbuffer.
Table6-14.ViewingtheWorkbuffer
Command Movesthecursor
CONTROL-D Forwardone-halfwindow
CONTROL-U Backwardone-halfwindow
CONTROL-For
PAGEDOWN Forwardonewindow
CONTROL-Bor
PAGEUP Backwardonewindow
nG Tolinen(withoutn,tothelastline)

HTotopofwindow
MTomiddleofwindow
LTobottomofwindow
ThecommandsinTable6-15enableyoutoaddtexttothebuffer.Allthesecommands,exceptr,leave
viminInputmode.YoumustpressESCAPEtoreturntoCommandmode.
Table6-15.Addingtext
Command Addstext
iBeforecursor
IBeforefirstnonblankcharacteronline
aAftercursor
AAtendofline
oOpenalinebelowcurrentline
OOpenalineabovecurrentline
rReplacecurrentcharacter(noESCAPEneeded)
RReplacecharacters,startingwithcurrentcharacter(overwriteuntil
ESCAPE)
Table6-16listscommandsthatdeleteandchangetext.InthistableMisaUnitofMeasurethatyoucan
precedewithaRepeatFactor,nisanoptionalRepeatFactor,andcisanycharacter.
Table6-16.Deletingandchangingtext
Command Result
nx
Deletesthenumberof
charactersspecifiedbyn,
startingwiththecurrent
character

nX
Deletesncharactersbefore
thecurrentcharacter,
startingwiththecharacter
precedingthecurrent
character
dMDeletestextspecifiedbyM
ndd Deletesnlines
dtcDeletestothenextcharacter
conthecurrentline
DDeletestoendoftheline
n~ Changecaseofthenextn
characters
ThefollowingcommandsleaveviminInputmode.YoumustpressESCAPEtoreturnto
Commandmode.
nsSubstitutesncharacters
SSubstitutesfortheentireline
cMChangestextspecifiedbyM
ncc Changesnlines
ctc
Changestothenext
characterconthecurrent
line
CChangestoendofline
Table6-17listssearchcommands.Hererexpisaregularexpressionthatcanbeasimplestringof
characters.
Table6-17.Searching
Command Result
/rexpRETURN Searchesforwardforrexp
?rexpRETURN Searchesbackwardforrexp
nRepeatsoriginalsearchexactly

NRepeatsoriginalsearch,intheoppositedirection
/RETURN Repeatsoriginalsearchforward
?RETURN Repeatsoriginalsearchbackward
fcPositionsthecursoronthenextcharacterconthecurrentline
FcPositionsthecursoronthepreviouscharacterconthecurrentline
tcPositionsthecursoronthecharacterbefore(totheleftof)thenext
characterconthecurrentline
TcPositionsthecursoronthecharacterafter(totherightof)theprevious
characterconthecurrentline
; Repeatsthelastf,F,t,orTcommand
TheformatofaSubstitutecommandis
:[address]s/search-string/replacement-string[/g]
whereaddressisonelinenumberortwolinenumbersseparatedbyacomma.A.(period)representsthe
currentline,$representsthelastline,and%representstheentirefile.Youcanuseamarkerorasearch
stringinplaceofalinenumber.Thesearch-stringisaregularexpressionthatcanbeasimplestringof
characters.Thereplacement-stringisthereplacementstring.Agindicatesaglobalreplacement(more
thanonereplacementperline).
Table6-18listsmiscellaneousvimcommands.
Table6-18.Miscellaneouscommands
Command Result
JJoinsthecurrentlineandthefollowingline
. Repeatsthemostrecentcommandthatmadeachange
:wfilename WritescontentsofWorkbuffertofilename(ortocurrentfileifthereis
nofilename)
:q Quitsvim

ZZ WritescontentsofWorkbuffertothecurrentfileandquitsvim
:forCONTROL-G
Displaysthefilename,status,currentlinenumber,numberoflinesinthe
Workbuffer,andpercentageoftheWorkbufferprecedingthecurrent
line
CONTROL-V Insertsthenextcharacterliterallyevenifitisavimcommand(usein
Inputmode)
Table6-19listscommandsthatyankandputtext.InthistableMisaUnitofMeasurethatyoucan
precedewithaRepeatFactorandnisaRepeatFactor.Youcanprecedeanyofthesecommandswiththe
nameofabufferusingtheform"x,wherexisthenameofthebuffer(az).
Table6-19.Yankingandputtingtext
Command Result
yMYankstextspecifiedbyM
nyy Yanksnlines
YYankstoendofline
PPutstextbeforeorabove
pPutstextafterorbelow
Table6-20listsadvancedvimcommands.
Table6-20.Advancedcommands
Command Result
mxSetsmarkerx,wherexisaletterfromatoz.
''(twosingle
quotationmarks) Movescursorbacktoitspreviouslocation.
'xMovescursortolinewithmarkerx.
'xMovescursortocharacterwithmarkerx.

:efilename
Editsfilename,requiringyoutowriteoutchangestothecurrentfile(with
:worautowrite)beforeeditingthenewfile.Use:e!filenametodiscard
changestothecurrentfile.Use:e!withoutafilenametodiscardchangesto
thecurrentfileandstarteditingthesavedversionofthecurrentfile.
:n
Editsthenextfilewhenvimisstartedwithmultiplefilenamearguments.
Requiresyoutowriteoutchangestothecurrentfile(with:worautowrite)
beforeeditingthenextfile.Use:n!todiscardchangestothecurrentfile
andeditthenextfile.
:rew
Rewindsthefilenamelistwhenvimisstartedwithmultiplefilename
argumentsandstartseditingwiththefirstfile.Requiresyoutowriteout
changestothecurrentfile(with:worautowrite)beforeeditingthefirst
file.Use:rew!todiscardchangestothecurrentfileandeditthefirstfile.
:sh Startsashell.Exitfromtheshelltoreturntovim.
:!command Startsashellandexecutescommand.
!!command Startsashell,executescommand,andplacesoutputintheWorkbuffer,
replacingthecurrentline.
Exercises
1. HowcanyoucausevimtoenterInputmode?HowcanyoumakevimreverttoCommandmode?
2. WhatistheWorkbuffer?NametwowaysofwritingthecontentsoftheWorkbuffertothedisk.
3.
Supposethatyouareeditingafilethatcontainsthefollowingparagraphandthecursorisonthesecondtilde(~):
Thevimeditorhasacommand,tilde(~),
thatchangeslowercaselettersto
uppercase,andviceversa.
The~commandworkswithaUnitofMeasureor
aRepeatFactor,soyoucanchange
thecaseofmorethanonecharacteratatime.
Howcanyou
1. Movethecursortotheendoftheparagraph?
2. MovethecursortothebeginningofthewordUnit?
3. Changethewordcharactertoletter?
4. Whileworkinginvim,withthecursorpositionedonthefirstletterofaword,yougivethecommandxfollowedbyp.Explainwhat
happens.
5.
Whatarethedifferencesbetweenthefollowingcommands?
1. iandI
2. aandA
3. oandO
4. randR
5. uandU
6. WhichcommandwouldyouusetosearchbackwardthroughtheWorkbufferforlinesthatstartwiththewordit?
7. Whichcommandsubstitutesalloccurrencesofthephrasethisweekwiththephrasenextweek?
8.
Considerthefollowingscenario:Youstartvimtoeditanexistingfile.Youmakemanychangestothefileandthenrealizethatyou
deletedacriticalsectionofthefileearlyinyoureditingsession.Youwanttogetthatsectionbackbutdonotwanttolosealltheother
changesyoumade.Whatwouldyoudo?
9. Howcanyoumovethelinethatthecursorisontothebeginningofthefile?
AdvancedExercises
11. Whichcommandscanyouusetotakeaparagraphfromonefileandinsertitinasecondfile?
12.
Createafilethatcontainsthefollowinglist,andthenexecutecommandsfromwithinvimtosortthelistanddisplayitintwocolumns.
(Hint:Refertopage744formoreinformationonpr.)
Commandmode
Inputmode
LastLinemode
Workbuffer
General-Purposebuffer
Namedbuffer
RegularExpression
SearchString
ReplacementString
StartupFile
RepeatFactor
13. HowdotheNamedbuffersdifferfromtheGeneral-Purposebuffer?
14. AssumethatyourversionofvimdoesnotsupportmultipleUndocommands.Ifyoudeletealineoftext,thendeleteasecondline,and
thenathirdline,whichcommandswouldyouusetorecoverthefirsttwolinesthatyoudeleted?
15. Whichcommandwouldyouusetoswapthewordshitherandyononanylinewithanynumberofwordsbetweenthem?(Youneed
notworryaboutspecialpunctuation,justuppercaseandlowercaselettersandspaces.)
Chapter7.TheemacsEditor
INTHISCHAPTER
History196
emacsVersusvim197
Tutorial:GettingStartedwithemacs198
BasicEditingCommands204
OnlineHelp209
AdvancedEditing212
Language-SensitiveEditing225
Customizingemacs235
In1956theLisp(Listprocessing)languagewasdevelopedatMITbyJohnMcCarthy.Initsoriginal
conception,Lisphadonlyafewscalar(atomic)datatypesandonlyonedatastructure(page870):alist.
Listscouldcontainatomicdataorperhapsotherlists.Lispsupportedrecursionandnonnumericdata
(excitingconceptsinthoseFORTRANandCOBOLdays)and,intheCambridgecultureatleast,wasonce
thefavoredimplementationlanguage.RichardStallmanandGuySteelewerepartofthisMITLisp
culture.In1975theycollaboratedonemacs,whichStallmanmaintainedbyhimselfforalongtime.This
chapterdiscussestheemacseditorasimplementedbytheFreeSoftwareFoundation(GNU).The
emacshomepageiswww.gnu.org/software/emacs.
History
Theemacseditorwasprototypedasaseriesofextensioncommandsormacrosforthelate1960stext
editorTECO(TextEditorandCOrrector).Itsacronymicname,EditorMACroS,reflectsthisorigin,
althoughtherehavebeenmanyhumorousreinterpretations,includingESCAPEMETAALTCONTROL
SHIFT,EmacsMakesAllComputingSimple,andtheunkindtranslationEightMegabytesAndConstantly
Swapping.
Evolution
Overtimeemacshasgrownandevolvedthroughmorethan20majorrevisionstothemainstreamGNU
version.Theemacseditor,whichiscodedinC,containsacompleteLispinterpreterandfullysupports
theXWindowSystemandmouseinteraction.TheoriginalTECOmacrosarelonggone,butemacsis
stillverymuchaworkinprogress.Thereareplanstosupportvariable-widthfonts,widecharactersets,
andtheworld'smajorlanguagesaswellastomoveemacsinthedirectionofaWYSIWYG(whatyou
seeiswhatyouget)wordprocessorandmakeiteasierforbeginnerstouse.
Theemacseditorhasalwaysbeenconsiderablymorethanatexteditor.Nothavingbeendeveloped
originallyinaUNIXenvironment,itdoesnotadheretotheUNIX/Linuxphilosophy.Whereasa
UNIX/Linuxutilityistypicallydesignedtodoonethingandtobeusedinconjunctionwithotherutilities,
emacsisdesignedto"doitall."Takingadvantageoftheunderlyingprogramminglanguage(Lisp),
emacsuserstendtocustomizeandextendtheeditorratherthantouseexistingutilitiesorcreatenew
general-purposetools.Insteadtheysharetheir~/.emacs(customization)files.
WellbeforetheemergenceoftheXWindowSystem,Stallmanputagreatdealofthoughtandeffortinto
designingawindow-orientedworkenvironment,andheusedemacsashisresearchvehicle.Overtime
hebuiltfacilitieswithinemacsforreadingandcomposingemailmessages,readingandpostingnetnews,
givingshellcommands,compilingprogramsandanalyzingerrormessages,runninganddebuggingthese
programs,andplayinggames.Eventuallyitbecamepossibletoentertheemacsenvironmentandnot
comeoutallday,switchingfromwindowtowindowandfromfiletofile.Ifyouhadonlyanordinary
serial,character-basedterminal,emacsgaveyoutremendousleverage.
InanXWindowSystemenvironment,emacsdoesnotneedtocontrolthewholedisplay.Instead,it
usuallyoperatesonlyoneortwowindows.Theoriginalworkenvironmentisstillavailableandis
coveredinthischapter.
Asalanguage-sensitiveeditor,emacshasspecialfeaturesthatyoucanturnontohelpedittext,nroff,
TeX,Lisp,C,Fortran,andsoon.Thesefeaturesetsarecalledmodes,buttheyarenotrelatedinanyway
totheCommandmodeandInputmodefoundinvi,vim,andothereditors.Becauseyouneverneedto
switchemacsbetweenInputandCommandmodes,emacsisamodelesseditor.
emacsVersusvim
Likevim,emacsisadisplayeditor:Itdisplaysonthescreenthetextyouareeditingandchangesthe
displayasyoutypeeachcommandorinsertnewtext.Unlikevim,emacsdoesnotrequireyoutokeep
trackofwhetheryouareinCommandmodeorInsertmode:CommandsalwaysuseCONTROLorother
specialkeys.Theemacseditorinsertsordinarycharactersintothetextyouareediting(asopposedto
usingordinarycharactersascommands),anothertraitofmodelessediting.Formanypeoplethisapproach
isconvenientandnatural.
Likevim,emacshasarich,extensivecommandsetformovingaboutinthebufferandalteringtext.This
commandsetisnot"castinconcrete"youcanchangeorcustomizecommandsatanytime.Literallyany
keycanbecoupled(bound)toanycommandsoastomatchaparticularkeyboardbetterorjusttofulfilla
personalwhim.Usuallykeybindingsaresetinthe.emacsstartupfile,buttheycanalsobechanged
interactivelyduringasession.AllthekeybindingsdescribedinthischapterarestandardoncurrentGNU
emacsversions,whichalsosupportmanyvisual,mouse-orientedcapabilitiesthatarenotcoveredhere.
caution:Toomanykeybindings
Ifyouchangetoomanykeybindings,youmayproduceacommandsetthatyouwillnot
rememberorthatwillmakeitimpossibleforyoutogetbacktothestandardbindingsagain
inthesamesession.
Finally,andveryunlikevim,emacsallowsyoutouseLisptowritenewcommandsoroverrideold
ones.Stallmancallsthisfeatureonlineextensibility,butitwouldtakeagutsyLispgurutowriteand
debuganewcommandwhileeditinglivetext.Itismuchmorecommontoaddafewextradebugged
commandstothe.emacsfile,wheretheyareloadedwhenemacsstartsup.Experiencedemacsusers
oftenwritemodes,orenvironments,thatareconditionallyloadedbyemacsforspecifictasks.
tip:Thescreenandemacswindows
Inthischapter,thetermscreendenotesacharacter-basedterminalscreenoraterminal
emulatorwindowinagraphicalenvironment.Thetermwindowreferstoanemacs
windowwithinascreen.
tip:emacsandtheXWindowSystem
Withversion19,GNUemacsfullyembracedtheXWindowSystemenvironment.Ifyou
startemacsfromaterminalemulatorwindowrunninginagraphicalenvironment,you
willbringuptheX(GUI)interfacetoemacs.Thisbookdoesnotcoverthegraphical
interface;usethenwoptionwhenyoustartemacstobringupthetextualinterfaceinany
environment.See"Startingemacs"onpage198.

Tutorial:GettingStartedwithemacs
Theemacseditorhasmany,manyfeatures,andtherearemanywaystouseit.Itscompletemanual
includesmorethan35chapters.Nevertheless,youcandoaconsiderableamountofmeaningfulworkwith
arelativelysmallsubsetofthecommands.Thissectiondescribesasimpleeditingsession,explaining
howtostartandexitfromemacsandhowtomovethecursoranddeletetext.Someissuesarepostponed
orsimplifiedintheinterestofclarity.
Startingemacs
Toeditafilenamedsampleusingemacsasatext-basededitor,enterthefollowingcommand.Thenw
option,whichmustbethefirstoptionontheemacscommandline,tellsemacsnottouseitsX(GUI)
interface.
$emacs-nw-qsample
Thiscommandstartsemacs,readsthefilenamedsampleintoabuffer,anddisplaysitscontentsonthe
screenorwindow.Ifnofilehasthisname,emacsdisplaysablankscreenwithNewFileatthebottom
(Figure7-1).Ifthefileexists,emacsdisplaysanothermessage(Figure7-2,page200).Theqoption
tellsemacsnottoreadthe~/.emacsstartupfilefromyourhomedirectory.Notreadingthestartupfile
guaranteesthatyougetstandard,uncustomizedbehaviorandissometimesusefulforbeginnersorforother
userswhowanttobypassa.emacsfile.
Figure7-1.Theemacswelcomescreen
[Viewfullsizeimage]

Figure7-2.Samplebuffer
[Viewfullsizeimage]
Thescreenstartswithasinglewindow.Atthebottomofthiswindowisareverse-videotitlebarcalled
theModeLine.Ataminimum,theModeLineshowswhichbufferthewindowisviewing,whetherthe
bufferhasbeenchanged,whatmajorandminormodesareineffect,andhowfardownthebufferthe
windowispositioned.Whenyouhavemorethanonewindow,oneModeLineappearsineachwindow.
Atthebottomofthescreen,emacsleavesasinglelineopen.ThisEchoArea,orMinibuffer,lineisused
forshortmessagesandspecialone-linecommands.
AcursorisinthewindoworMinibuffer.Allinputandnearlyalleditingtakesplaceatthecursor.Asyou
typeordinarycharacters,emacsinsertsthematthecursorposition.Ifcharactersareunderthecursoror
toitsright,theygetpushedtotherightasyoutype,sonocharactersarelost.
Stoppingemacs
Thecommandtoexitfromemacsisthetwo-keysequenceCONTROL-XCONTROL-C.Youcangive
thiscommandatalmostanytime(insomemodesyoumayhavetopressCONTROL-Gfirst).Itstops
emacsgracefully,askingyoutoconfirmchangesifyoumadeanyduringtheeditingsession.
Ifyouwanttocancelahalf-typedcommandorstoparunningcommandbeforeitisdone,youcanquitby
pressingCONTROL-G.TheemacseditordisplaysQuitintheEchoAreaandwaitsforyournext
command.
InsertingText
Typinganordinary(printing)characterpushesthecursorandanycharacterstotherightofthecursorone
positiontotherightandinsertsthenewcharacterinthepositionjustopened.Backspacingpullsthecursor
andanycharacterstotherightofthecursoronepositiontotheleft,erasingthecharacterthatwasthere
before.
DeletingCharacters
Dependingonthekeyboardyouareusingandtheemacsstartupfile,differentkeysmaydeletecharacters
indifferentways.CONTROL-Dtypicallydeletesthecharacterunderthecursor,asdoDELETEand
DEL.BACKSPACEtypicallydeletesthecharactertotheleftofthecursor.Tryeachofthesekeysandsee
whatitdoes.
tip:Moreaboutdeletingcharacters
Iftheinstructionsdescribedinthissectiondonotwork,readtheemacsinfosectionon
deletion.Givethiscommandfromashellprompt:
$infoemacs
Frominfogivethecommandmdeletiontodisplayadocumentthatdescribesindetail
howtodeletesmallamountsoftext.UsetheSPACEbartoscrollthroughthedocument.
Typeqtoexitfrominfo.
Startemacsandtypeafewlinesoftext.Ifyoumakeamistake,usethedeletioncharactersdiscussed
previously.TheRETURNkeyinsertsaninvisibleend-of-linecharacterinthebufferandreturnsthe
cursortotheleftmargin,onelinedown.Itispossibletobackuppastthestartofalineanduptotheend
ofthepreviousline.Figure7-2showsasamplebuffer.
MovingtheCursor
Youcanpositionthecursoroveranycharacterintheemacswindowandmovethewindowsoit
displaysanyportionofthebuffer.Youcanmovethecursorforwardorbackwardthroughthetext(Figure
6-8,page155)byvarioustextualunitsforexample,characters,words,sentences,lines,andparagraphs.
Anyofthecursor-movementcommandscanbeprecededbyarepetitioncount(CONTROL-Ufollowedby
anumericargument),whichcausesthecursortomovethatnumberoftextualunitsthroughthetext.Refer
topage205foradiscussionofnumericarguments.
tip:UsetheARROWkeys
SometimestheeasiestwaytomovethecursorisbyusingtheLEFT,RIGHT,UP,and
DOWNARROWkeys.
MovingtheCursorbyCharacters
CONTROL-F
PressingtheRIGHTARROWkeyorCONTROL-Fmovesthecursorforwardonecharacter.Ifthecursor
isattheendofaline,thesecommandswrapittothebeginningofthenextline.Thecommand
CONTROL-U7CONTROL-Fmovesthecursorsevencharactersforward(totheright).
CONTROL-B
PressingtheLEFTARROWkeyorCONTROL-Bmovesthecursorbackwardonecharacter.The
commandCONTROL-U7CONTROL-Bmovesthecursorsevencharactersbackward(totheleft).
CONTROL-BworksinamannersimilartoCONTROL-F(Figure7-3).

Figure7-3.Movingthecursorbycharacters
MovingtheCursorbyWords
META-f
PressingMETA-fmovesthecursorforwardoneword.TopressMETA-fholddowntheMETAorALT
keywhileyoupressf.Ifyoudonothaveeitherofthesekeys,pressESCAPE,releaseit,andthenpressf.
Thiscommandleavesthecursoronthefirstcharacterthatisnotpartofthewordthecursorstartedon.
ThecommandCONTROL-U4META-fmovesthecursorforwardonespacepasttheendofthefourth
word.Seepage204formoreaboutkeys.
META-b
PressingMETA-bmovesthecursorbackwardonewordsothecursorisonthefirstletterofthewordit
startedon.Ifthecursorwasonthefirstletterofaword,META-bmovesthecursortothefirstletterofthe
precedingword.ItworksinamannersimilartoMETA-f(Figure7-4).
Figure7-4.Movingthecursorbywords
MovingtheCursorbyLines
CONTROL-ACONTROL-E
CONTROL-PCONTROL-N
PressingCONTROL-Amovesthecursortothebeginningofthelineitison;CONTROL-Emovesittothe
end.PressingtheUPARROWkeyorCONTROL-Pmovesthecursoruponelinetothepositiondirectly
abovewherethecursorstarted;theDOWNARROWkeyorCONTROL-Nmovesitdown.Aswiththe

othercursor-movementkeys,youcanprecedeCONTROL-PandCONTROL-NwithCONTROL-Uanda
numericargumenttomoveupordownmultiplelines.Youcanusepairsofthesecommandstomovethe
cursoruptothebeginningofthepreviousline,downtotheendofthefollowingline,andsoon(Figure7-
5).
Figure7-5.Movingthecursorbylines
MovingtheCursorbySentences,Paragraphs,andWindowPosition
META-a,META-eMETA-{,META-}
PressingMETA-amovesthecursortothebeginningofthesentencethecursorison;META-emovesthe
cursortotheend.META-{movesthecursortothebeginningoftheparagraphthecursorison;META-}
movesittotheend.(Sentencesandparagraphsaredefinedstartingonpage227.)Youcanprecedeanyof
thesecommandswitharepetitioncount(CONTROL-Uandanumericargument)tomovethecursorthat
manysentencesorparagraphs.
META-r
PressingMETA-rmovesthecursortothebeginningofthemiddlelineofthewindow.Youcanprecede
thiscommandwithCONTROL-Uandalinenumber(hereCONTROL-Udoesnotindicatearepetition
countbutascreenlinenumber).ThecommandCONTROL-U0META-rmovesthecursortothe
beginningofthetopline(linezero)inthewindow.Youcanreplacezerowiththelinenumberoftheline
youwanttomovethecursortoorwithaminussign(),inwhichcasethecursormovestothebeginningof
thelastlineofthewindow(Figure7-6).
Figure7-6.Movingthecursorbysentences,paragraphs,andwindowposition
[Viewfullsizeimage]

EditingattheCursorPosition
Withthecursorinthewindowyoucantypenewtext,pushingtheexistingtexttotheright.Enteringnew
textrequiresnospecialcommandsoncethecursorispositioned.Ifyoutypesomanycharactersthatthe
textinalinegoespasttherightedgeofthewindow,emacsputsabackslash(\)neartherightedgeofthe
windowandwrapsthetexttothenextline.Thebackslashappearsonthescreenbutisnotsavedaspart
ofthefileandisneverprinted.Althoughyoucancreateanarbitrarilylongline,someUNIXtoolshave
problemswithtextfilescontainingsuchlines.Youcansplitalineatanypointbypositioningthecursor
andpressingRETURN.
Deletingtext
PressingDELETEremovescharacterstotheleftofthecursor.Thecursorandtheremainderofthetexton
thislinebothmovetothelefteachtimeyoupressDELETE.Tojoinalinewiththelineaboveit,position
thecursoronthefirstcharacterofthesecondlineandpressDELETE.
PressCONTROL-Dtodeletethecharacterunderthecursor.Thecursorremainsstationary,butthe
remainderofthetextonthelinemoveslefttoreplacethedeletedcharacter.Seethetip"Moreabout
deletingcharacters"onpage199ifeitherofthesekeysdoesnotworkasdescribedhere.
SavingandRetrievingtheBuffer
Nomatterwhathappenstoabufferduringanemacssession,theassociatedfiledoesnotchangeuntil
yousavethebuffer.Ifyouleaveemacswithoutsavingthebuffer(thisispossibleifyouareinsistent
enough),thefileisnotchangedandthesession'sworkisdiscarded.
Backups
Asmentionedpreviously,emacspromptsyouaboutunsavedchangestothebuffercontents.Asitwrites
abuffer'seditedcontentsbacktothefile,emacsmayoptionallyfirstmakeabackupoftheoriginalfile
contents.Youcanchoosetomakenobackups,onelevel(default),oranarbitrarynumberoflevels.The
one-levelbackupfilenamesareformedbyappendinga~charactertotheoriginalfilename.The
multilevelbackupsappend.~n~tothefilename,wherenisthesequentialbackupnumber,startingwith1.
Theversion-controlvariabledictateshowemacssavesbackups.
Savingthebuffer
ThecommandCONTROL-XCONTROL-Ssavesthecurrentbufferinitsassociatedfile.Theemacs
editorconfirmsasuccessfulsavewithamessageintheEchoArea.
Visitinganotherfile
Ifyouarealreadyeditingafilewithemacsandwanttoeditanotherfile(alsocalledvisitingafile),you
cancopythenewfileintoanewemacsbufferbygivingthecommandCONTROL-XCONTROL-F.The
emacseditorpromptsyouforafilename,readsthatfileintoanewbuffer,anddisplaysthatbufferinthe
currentwindow.Havingtwofilesopeninoneeditingsessionismoreconvenientthanexitingfrom
emacs,returningtotheshell,andthenstartinganewcopyofemacstoeditasecondfile.
tip:VisitingafilewithCONTROL-XCONTROL-F
WhenyouuseCONTROL-XCONTROL-F,emacspartiallycompletesthepathtothe
filenameyouaretoenter.Normallyitisthepathtotheworkingdirectory,butinsome
situationsemacsmaydisplayadifferentpath,suchasthepathtoyourhomedirectory.You
caneditthispathifitisnotpointingtothedirectoryyouwant.

BasicEditingCommands
Thissectiontakesamoredetailedlookatthefundamentalemacseditingcommands.Itcovers
straightforwardeditingofasinglefileinasinglewindow.
Keys:NotationandUse
Mainstreamemacsusesthe128-characterASCIIcharacterset.ASCIIkeyboardshaveatypewriter-style
SHIFTkeyandaCONTROLkey.SomekeyboardsalsohaveaMETA(diamondorALT)keythatcontrols
theeighthbit.IttakessevenbitstodescribeanASCIIcharacter;theeighthbitofaneight-bitbytecanbe
usedtocommunicateotherinformation.Becausesomuchoftheemacscommandsetisinthenonprinting
CONTROLorMETAcase,Stallmanwasoneofthefirsttoconfronttheproblemofdevelopinganotation
forwritingaboutkeystrokes.
Hissolution,althoughnotpopularoutsidetheemacscommunity,isclearandunambiguous(Table7-1).
ItusesthecapitallettersCandMtodenoteholdingdowntheCONTROLandMETA(orALT)keys,
respectively,andafewsimpleacronymsforthemostcommonspecialcharacters,suchasRET(thisbook
usesRETURN),LFD(LINEFEED),DEL(DELETE),ESC(ESCAPE),SPC(SPACE),andTAB.Most
emacsdocumentation,includingtheonlinehelp,usesthisnotation.
Table7-1.emacskeynotation
Character Classicemacsnotation
(lowercase)a a
(uppercase)SHIFT-a A
CONTROL-a C-a
CONTROL-A C-a(donotuseSHIFT),equivalenttoCONTROL-a
META-a M-a
META-A M-A(douseSHIFT),differentfromM-a
CONTROL-META-a C-M-a
META-CONTROL-a M-C-a(notusedfrequently)
Thisuseofkeyshadsomeproblems.ManykeyboardshadnoMETAkey,andsomeoperatingsystems
discardedtheMETAbit.Inaddition,theemacscharactersetclasheswithXON-XOFFflowcontrol,
whichalsousesCONTROL-SandCONTROL-Q.
Althoughtheflow-controlproblemstillexists,theMETAkeyissuewasresolvedbymakingitanoptional
two-keysequencestartingwithESCAPE.Forinstance,youcantypeESCAPE-ainsteadofMETA-aor
typeESCAPECONTROL-AtogetCONTROL-META-a.Ifthekeyboardyouareusingdoesnothavea
METAorALTkey,youcanusethetwo-keyESCAPEsequencebypressingtheESCAPEkey,releasingit,
andthenpressingthekeyfollowingtheMETAkeyinthisbook.Forexample,whenthisbooksaystopress
META-r,youcaneitherpresstheMETAorALTkeywhileyoupressrorpressandreleaseESCAPEand
thenpressr.
tip:Thenotationusedinthisbook
ThisbookusesanuppercaseletterfollowingtheCONTROLkeyandalowercaseletter
followingtheMETAkey.IneithercaseyoudonothavetoholddowntheSHIFTkeywhile
enteringaCONTROLorMETAcharacter.AlthoughtheMETAuppercasecharacter(that
is,META-A)isadifferentcharacter,itisusuallysetuptocausenoactionorthesame
effectasitslowercasecounterpart.
KeySequencesandCommands
Inemacstherelationshipbetweenkeysequences(oneormorekeysthatarepressedtogetherorin
sequencetoissueanemacscommand)andcommandsisveryflexible,andthereisconsiderable
opportunityforexercisingyourpersonalpreference.Youcantranslateandremapkeysequencestoother
commandsandreplaceorreprogramcommands.
Althoughmostemacsdocumentationglossesoverthedetailsandtalksaboutkeystrokesasthoughthey
werethecommands,itisimportanttorecognizethattheunderlyingmachineryremainsseparatefromthe
keysequencesandtounderstandthatyoucanchangethebehaviorofthekeysequencesandthecommands.
Formoreinformationreferto"Customizingemacs"onpage235.
META-x:RunningaCommandWithoutaKeyBinding
Theemacskeymaps(thetables,orvectors,thatemacsusestotranslatekeysequencestocommands
[page237])areverycrowded,andoftenitisnotpossibletobindeverycommandtoakeysequence.You
canexecuteanycommandbynamebyprecedingitwithMETA-x.WhenyoupressMETA-x,theemacs
editorpromptsyouforacommandintheEchoArea.Afteryouenterthecommandnameandpress

RETURN,itexecutesthecommand.
Smartcompletion
Whenacommandhasnocommonkeysequence,itissometimesdescribedasMETA-xcommand-name.
Theemacseditorhasasmartcompletionformostpromptedanswers,usingSPACEorTABto
complete,ifpossible,totheendofthecurrentwordorthewholecommand,respectively.Forcinga
completionpastthelastunambiguouspointortyping?displaysalistofalternatives.Youcanfindmore
detailsonsmartcompletionintheonlineemacsmanual.
NumericArguments
Someoftheemacseditingcommandsacceptanumericargumentasarepetitioncount.Youplacethis
argumentimmediatelybeforethekeysequenceforthecommand.Absenceofanargumentalmostalways
meansacountof1.Evenanordinaryalphabeticcharactercanhaveanumericargument,whichmeans
"insertthismanytimes."Togiveacommandanumericargument,youcandoeitherofthefollowing:
PressMETAwitheachdigit(09)ortheminussign().Forexample,toinsert10zcharacters,type
META-1META-0z.
UseCONTROL-Utobeginastringofdigits,includingtheminussign.Forexample,tomovethe
cursorforward20words,typeCONTROL-U20META-f.
CONTROL-U
Forconvenience,CONTROL-Udefaultstomultiplyby4whenyoudonotfollowitwithastringofone
ormoredigits.Forexample,enteringCONTROL-Urmeansinsertrrrr(4*1),whereasCONTROL-U
CONTROL-Urmeansinsertrrrrrrrrrrrrrrrr(4*4*1).Forquickpartialscrollingofatallwindow,
youmayfinditconvenienttouserepeatedsequencesofCONTROL-UCONTROL-Vtoscrolldownfour
lines,CONTROL-UMETA-vtoscrollupfourlines,CONTROL-UCONTROL-UCONTROL-Vtoscroll
down16lines,orCONTROL-UCONTROL-UMETA-vtoscrollup16lines.
PointandtheCursor
Pointistheplaceinabufferwhereeditingtakesplaceandiswherethecursorispositioned.Strictly
speaking,Pointistheleftedgeofthecursoritisthoughtofaslyingbetweentwocharacters.
EachwindowhasitsownPoint,butthereisonlyonecursor.Whenthecursorisinawindow,movingthe
cursoralsomovesPoint.Switchingthecursoroutofawindowdoesnotchangethatwindow'sPoint;itis
inthesameplacewhenyouswitchthecursorbacktothatwindow.
Allofthecursor-movementcommandsdescribedpreviouslyalsomovePoint.
ScrollingThroughaBuffer
CONTROL-VMETA-v
CONTROL-L
Abufferislikelytobemuchlargerthanthewindowthroughwhichitisviewed,soyouneedawayof
movingthedisplayofthebuffercontentsupordowntopositiontheinterestingpartinthewindow.
Scrollingforwardreferstomovingthetextupward,withnewlinesenteringatthebottomofthewindow.
UseCONTROL-VorthePAGEDOWNkeytoscrollforwardonewindow(minustwolinesforcontext).
Scrollingbackwardreferstomovingthetextdownward,withnewlinesenteringatthetopofthewindow.
UseMETA-vorthePAGEUPkeytoscrollbackwardonewindow(againleavingtwolinesforcontext).
PressingCONTROL-Lclearsthescreenandrepaintsit,movingthecurrentlinetothecenterofthe
window.Thiscommandisusefulifthescreenbecomesgarbled.
AnumericargumenttoCONTROL-VorMETA-vmeans"scrollthatmanylines";thusCONTROL-U10
CONTROL-Vmeansscrollforwardtenlines.AnumericargumenttoCONTROL-Lmeans"scrollthetext
sothecursorisonthatlineofthewindow,"where0meansthetoplineand1meansthebottom,just
abovetheModeLine.ScrollingoccursautomaticallyifyouexceedthewindowlimitswithCONTROL-P
orCONTROL-N.
META-<META->
YoucanmovethecursortothebeginningofthebufferwithMETA-<ortotheendofthebufferwith
META->.
ErasingText
Deleteversuskill
Whenyouerasetextyoucandiscarditormoveitintoaholdingareaandoptionallybringitbacklater.
Thetermdeletemeanspermanentlydiscard,andthetermkillmeansmovetoaholdingarea.Theholding
area,calledtheKillRing,canholdseveralpiecesofkilledtext.YoucanusethetextintheKillRingin
manyways(referto"CutandPaste:YankingKilledText"onpage215).
TheMETA-dcommandkillsfromthecursorforwardtotheendofthecurrentword.CONTROL-Kkills
forwardtotheendofthecurrentline.Itdoesnotdeletetheline-endingLINEFEEDcharacterunlessPoint
andthecursorarejusttotheleftoftheLINEFEED.Thissetupallowsyoutoreachtheleftendofaline

withCONTROL-A,killthewholelinewithCONTROL-K,andthenimmediatelytypeareplacementline
withouthavingtoreopenaholeforthenewline.Anotherconsequenceisthat,fromthebeginningofthe
line,ittakesCONTROL-KCONTROL-K(orCONTROL-U2CONTROL-K)tokillthetextandclosethe
hole.
Searching
Theemacseditorhasseveraltypesofsearchcommands.Youcansearchinthefollowingways:
Incrementallyforacharacterstring
Incrementallyforaregularexpression(possiblebutuncommon)
Foracompletecharacterstring
Foracompleteregularexpression(AppendixA)
Youcanruneachofthefourtypesofsearcheseitherforwardorbackwardinthebuffer.
Thecompletesearchesbehaveinthesamemannerasasearchonothereditors.Searchingbeginsonly
whenthesearchstringiscomplete.Incontrast,anincrementalsearchbeginswhenyoutypethefirst
characterofthesearchstringandkeepsgoingasyouenteradditionalcharacters.Initiallythisapproach
maysoundconfusing,butitissurprisinglyuseful.
IncrementalSearches
CONTROL-SCONTROL-R
Asinglecommandselectsthedirectionofandstartsanincrementalsearch.CONTROL-Sstartsaforward
incrementalsearch,andCONTROL-Rstartsareverseincrementalsearch.
Whenyoustartanincrementalsearch,emacspromptsyouwithI-search:intheEchoArea.Whenyou
enteracharacter,itimmediatelysearchesforthatcharacterinthebuffer.Ifitfindsthatcharacter,emacs
movesPointandcursortothatpositionsoyoucanseethesearchprogress.Ifthesearchfails,emacs
tellsyouso.
Afteryouentereachcharacterofthesearchstring,youcantakeoneofseveralactionsdependingonthe
resultofthesearchtothatpoint.
Thesearchfindsthestringyouarelookingforinthebuffer,leavingthecursorpositionedjusttoits

right.StopthesearchandleavethecursorinitsnewpositionbypressingRETURN.(Anyemacs
commandnotrelatedtosearchingwillalsostopthesearchbutrememberingexactlywhichones
applycanbedifficult.Foranewuser,RETURNissafer.)
Thesearchfindsastringbutitisnottheoneyouarelookingfor.Youcanrefinethesearchstringby
addinganotherletter,pressCONTROL-RorCONTROL-Sagaintolookforthenextoccurrenceof
thissearchstring,orpressRETURNtostopthesearchandleavethecursorwhereitis.
ThesearchhitsthebeginningorendofthebufferandreportsFailingI-Search.Youcanproceedin
severalwaysatthispoint.
Ifyoumistypedthesearchstring,pressBACKSPACEasneededtoremovecharactersfromthe
searchstring.Thetextandcursorinthewindowjumpbackwardinstepwithyourremovalof
characters.
Ifyouwanttowrappastthebeginningorendofthebufferandcontinuesearching,youcanforce
awrapbypressingCONTROL-RorCONTROL-Sagain.
Ifthesearchhasnotfoundthestringyouarelookingforbutyouwanttoleavethecursoratits
currentposition,pressRETURNtostopthesearch.
Ifthesearchhasgonewrongandyoujustwanttogetbacktowhereyoustarted,press
CONTROL-G(thequitcharacter).FromanunsuccessfulsearchasingleCONTROL-Gbacks
outallthecharactersinthesearchstringthatcouldnotbefound.Ifthisactionreturnsyoutoa
placeyouwishtocontinuesearchingfrom,youcanaddcharacterstothesearchstringagain.If
youdonotwanttocontinuethesearchfromthatposition,asecondCONTROL-Gstopsthe
searchandleavesthecursorwhereitwasinitially.
NonincrementalSearches
CONTROL-SRETURNCONTROL-RRETURN
Ifyoupreferthatyoursearchessucceedorfailwithoutshowingalltheintermediateresults,youcangive
thenonincrementalcommandCONTROL-SRETURNtosearchforwardorCONTROL-RRETURNto
searchbackward.Searchingdoesnotbeginuntilyouenterasearchstringinresponsetotheemacs
promptandpressRETURNagain.Neitherofthesecommandswrapspasttheendofthebuffer.
RegularExpressionSearches
Youcanperformbothincrementalandnonincrementalregularexpressionsearchinginemacs.Usethe
commandslistedinTable7-2tobeginaregularexpressionsearch.

Table7-2.Searchingforregularexpressions
Command Result
META-CONTROL-s Incrementallysearchesforwardforaregularexpression;
promptsforaregularexpressiononecharacteratatime
META-xisearch-backward-regexp
Incrementallysearchesbackwardforaregular
expression;promptsforaregularexpressionone
characteratatime
META-xisearch-completeRETURN Promptsforandthensearchesforwardforacomplete
regularexpression
META-xisearch-backward-regexp
RETURN
Promptsforandthensearchesbackwardforacomplete
regularexpression

OnlineHelp
Theemacshelpsystemisalwaysavailable.Withthedefaultkeybindings,youcanstartitwith
CONTROL-H.Thehelpsystemthenpromptsyouforaone-letterhelpcommand.Ifyoudonotknow
whichhelpcommandyouwant,type?orCONTROL-Htoswitchthecurrentwindowtoalistofhelp
commands,eachwithaone-linedescription;emacsagainrequestsaone-letterhelpcommand.Ifyou
decideyoudonotwanthelpafterall,typeCONTROL-Gtocancelyourhelprequestandreturntothe
formerbuffer.
Ifthehelpoutputisonlyasingleline,itappearsintheEchoArea.Ifitconsistsofmoretext,theoutput
appearsinitsownwindow.UseCONTROL-VandMETA-vtoscrollforwardandbackwardthroughthe
buffer(page206).YoucanmovethecursorbetweenwindowswithCONTROL-Xo(lowercase"o").See
page222foradiscussiononworkingwithmultiplewindows.
OnmanyterminalstheBACKSPACEorLEFTARROWkeygeneratesCONTROL-H.Ifyouforgetthat
youareusingemacsandtrytobackoverafewcharacters,youmayunintentionallyenterthehelpsystem.
Thisactiondoesnotposeadangertothebufferyouareediting,butitcanbeunsettlingtolosethe
windowcontentsandnothaveaclearpictureofhowtorestoreit.Whileyouarebeingpromptedforthe
typeofhelpyouwantyoucantypeCONTROL-Gtoremovethepromptandreturntoeditingthebuffer.
Someuserselecttoputhelponadifferentkey(page237).Table7-3listssomeofthehelpcommands.
Table7-3.Helpcommands
Command Typeofhelpoffered
CONTROL-Ha Promptsforastringanddisplaysalistofcommandswhose
namescontainthatstring.
CONTROL-Hb Displaysalongtableofthekeybindingsineffect.
CONTROL-Hckey-sequence
Displaysthenameofthecommandboundtokey-sequence.
Multiplekeysequencesareallowed.Foralongkeysequence
whereonlythefirstpartisrecognized,thecommand
describesthefirstpartandquietlyinsertstheunrecognized
partintothebuffer.Thiscanhappenwiththree-character
functionkeys(F1,F2,andsoon,onthekeyboard)that
generatecharactersequencessuchasESCAPE[SHIFT.
CONTROL-Hf
PromptsforthenameofaLispfunctionanddisplaysthe
documentationforit.BecausecommandsareLispfunctions,
youcanuseacommandnamewiththiscommand.
CONTROL-Hi Displaysthetopinfo(page32)menuwhereyoucanbrowse
emacsorotherdocumentation.
CONTROL-Hkkey-sequence Displaysthenameanddocumentationofthecommandbound
tokey-sequence.(SeethenotesonCONTROL-Hc.)

CONTROL-Hl(lowercase"l")
Displaysthelast100characterstyped.Therecordiskept
afterthefirst-stagekeyboardtranslation.Ifyouhave
customizedthekeyboardtranslationtable,youmustmakea
mentalreversetranslation.
CONTROL-Hm
Displaysthedocumentationandspecialkeybindingsforthe
currentMajormode(Text,C,Fundamental,andsoon,[page
226]).
CONTROL-Hn
Displaystheemacsnewsfilewhichlistsrecentchangesto
emacs,orderedwiththemostrecentchangesfirst.Seethe
tip"Closingthehelpwindow"onpage210.
CONTROL-Ht Runsanemacstutorialsession.Seethetip"Closingthehelp
window"onpage210.
CONTROL-Hv PromptsforaLispvariablenameanddisplaysthe
documentationforthatvariable.
CONTROL-Hw
Promptsforacommandnameandidentifiesanykey
sequenceboundtothatcommand.Multiplekeysequences
areallowed.(SeethenotesonCONTROL-Hc.)
tip:Closingthehelpwindow
Todeletethehelpwindowwhilethecursorisinthewindowthatholdsthetextyouare
editing,typeCONTROL-X1(one).Alternatively,youcanmovethecursortothehelp
window(CONTROL-Xo[lowercase"o"])andtypeCONTROL-X0(zero)todeletethe
currentwindow.
Ifhelpdisplaysawindowthatoccupiestheentirescreen,asisthecasewithCONTROL-H
n(emacsnews)andCONTROL-Ht(emacstutorial),youcankillthehelpbufferwith
CONTROL-XkoruseCONTROL-Xbtoswitchbuffers(bothonpage220).
Asthisabridgedpresentationmakesclear,youcanusethehelpsystemtobrowsethroughtheemacs
internalLispsystem.Forthecurious,followingisStallman'slistofstringsthatmatchmanynamesinthe
Lispsystem.Togetaviewoftheinternalfunctionalityofemacs,youcanuseanyofthesestringswith
CONTROL-Ha(helpsystemlistofcommands)orMETA-xapropos(promptsforastringandlists
variableswhosenamescontainthatstring).
backward dir insert previous view

beginning down kill region what
buffer end line register window
case file list screen word
change fill mark search yank
char find mode sentence
defun forward next set
delete goto page sexp
describe indent paragraph up

AdvancedEditing
Thebasicemacscommandssufficeformanyeditingtasksbuttheserioususerwillquicklydiscoverthe
needformorepower.Thissectionpresentssomeofthemoreadvancedemacscapabilities.
UndoingChanges
Aneditingsessionbeginswhenyoureadafileintoanemacsbuffer.Atthatpointthebuffercontent
matchesthefileexactly.Asyouinserttextandgiveeditingcommands,thebuffercontentbecomes
increasinglymoredifferentfromthefile.Ifyouaresatisfiedwiththechanges,youcanwritethealtered
bufferbackouttothefileandendthesession.
NeartheleftendoftheModeLine(Figure7-1,page198)isanindicatorthatshowsthemodificationstate
ofthebufferthatisdisplayedinthewindow.Thethreepossiblestatesare(notmodified),**(modified),
and%%(readonly).
Theemacseditorkeepsarecordofallthekeysyouhavepressed(textandcommands)sincethe
beginningoftheeditingsession,uptoalimitcurrentlysetat20,000characters.Ifyouarewithinthis
limit,itispossibletoundotheentiresessionforthisbuffer,onechangeatatime.Ifyouhavemultiple
buffers(page220),eachbufferhasitsownundorecord.
Undoingisconsideredsoimportantthatithasabackupkeysequence,justincasesomekeyboardscannot
easilyhandletheprimarysequence.ThetwosequencesareCONTROL-_(underscore,whichonold
ASR-33TTYkeyboardswasLEFTARROW)andCONTROL-Xu.WhenyoutypeCONTROL-_,
emacsundoesthelastcommandandmovesthecursortothatpositioninthebuffersoyoucanseewhat
happened.IfyoutypeCONTROL-_asecondtime,thenext-to-lastcommandisundone,andsoon.Ifyou
keeptypingCONTROL-_,eventuallyyouwillgetthebufferbacktoitsoriginalunmodifiedstateandthe
**ModeLineindicatorwillchangeto.
WhenyoubreakthestringofUndocommandswithanything(textoranycommandexceptUndo),all
reversechangesyoumadeduringthestringofundosbecomeapartofthechangerecordandcan
themselvesbeundone.Thisstrategyoffersawaytoredosomeoralltheundooperations.Ifyoudecide
youbackeduptoofar,typeacommand(somethinginnocuous,suchasCONTROL-F,thatdoesnotchange
thebuffer),andbeginundoinginreverse.Table7-4listssomeexamplesofUndocommands.
Table7-4.Undocommands
Commands Result
CONTROL-_ Undoesthelastchange
CONTROL-_CONTROL-FCONTROL-_ Undoesthelastchangeandchangesitback
again

CONTROL-_CONTROL-_ Undoesthelasttwochanges
CONTROL-_CONTROL-_CONTROL-F
CONTROL-_CONTROL-_
Undoestwochangesandchangesthemboth
backagain
CONTROL-_CONTROL-_CONTROL-F
CONTROL-_
Undoestwochangesandchangesoneofthem
backagain
Ifyoudonotrememberthelastchangeyoumade,youcantypeCONTROL-_andundoit.Ifyouwantedto
makethischange,typeCONTROL-FCONTROL-_andmakeitagain.Ifyoumodifiedabufferby
accident,youcankeeptypingCONTROL-_untiltheModeLineindicatorshowsoncemore.
Ifthebufferiscompletelyruinedandyouwanttostartover,issuethecommandMETA-xrevert-bufferto
discardthecurrentbuffercontentsandrereadtheassociatedfile.Theemacseditorasksyoutoconfirm
thiscommand.
MarkandRegion
Pointisthecurrenteditingpositioninabufferwhichyoucanmoveanywherewithinthebufferbymoving
thecursor.ItisalsopossibletosetamarkercalledMarkinthebuffer.Thecontiguouscharactersbetween
PointandMark(eitheronemaycomefirst)arecalledtheRegion.Manycommandsoperateonabuffer's
Region,notjustonthecharactersnearPoint.
MovingMarkandEstablishingaRegion
CONTROL-@CONTROL-SPACECONTROL-XCONTROL-X
MarkisnotaseasytomoveasPoint.Onceset,Markcanbemovedonlybysettingitsomewhereelse.
EachbufferhasonlyoneMark.TheCONTROL-@(orCONTROL-SPACE)commandexplicitlysets
Markatthecurrentcursor(andPoint)position.SomekeyboardsgenerateCONTROL-@whenyoutype
CONTROL-Q.Althoughthisisnotreallyabackupkeybinding,itisoccasionallyaconvenient
alternative.YoucanuseCONTROL-XCONTROL-XtoexchangePointandMark(andmovethecursorto
thenewPoint).
ToestablishaRegion,youusuallypositionthecursor(andPoint)atoneendofthedesiredRegion,set
MarkwithCONTROL-@,andthenmovethecursor(andPoint)totheotherendoftheRegion.Ifyou
forgetwhereyouleftMark,youcanmovethecursorbacktoitagainwithCONTROL-XCONTROL-Xor
hopbackandforthwithrepeatedCONTROL-XCONTROL-XtoshowtheRegionmoreclearly.
IfaRegionboundaryisnottoyourliking,youcanswapPointandMarkusingCONTROL-XCONTROL-

XtomovethecursorfromoneendoftheRegiontotheotherandthenmovePoint.Continueuntilyouare
satisfiedwiththeRegion.
OperatingonaRegion
Table7-5listsselectedcommandsthatoperateonaRegion.GivethecommandCONTROL-Haregionto
seeacompletelistofthesecommands.
Table7-5.Operatingonaregion
Command Result
META-w CopiestheRegionnondestructively(withoutkillingit)tothe
KillRing
CONTROL-W KillstheRegion
META-xprint-region SendstheRegiontotheprinter
META-xappend-to-buffer PromptsforabufferandappendstheRegiontothatbuffer
META-xappend-to-file PromptsforafilenameandappendstheRegiontothatfile
META-xcapitalize-region ConvertstheRegiontouppercase
TheMarkRing
EachtimeyousetMarkinabuffer,youarealsopushingMark'sformerlocationontothebuffer'sMark
Ring.TheMarkRingisorganizedasaFIFO(first-in-first-out)listandholdsthe16mostrecentlocations
whereMarkwasset.EachbufferhasitsownMarkRing.ThisrecordofrecentMarkhistoryisuseful
becauseitoftenholdslocationsthatyouwanttojumpbacktoquickly.Jumpingtoalocationpointedtoby
theMarkRingcanbefasterandeasierthanscrollingorsearchingyourwaythroughthebuffertofindthe
siteofapreviouschange.
CONTROL-UCONTROL-@
ToworkyourwaybackwardalongthetrailofformerMarklocations,givethecommandCONTROL-U
CONTROL-@oneormoretimes.Eachtimeyougivethecommand,emacs
MovesPoint(andthecursor)tothecurrentMarklocation

SavesthecurrentMarklocationattheoldestendoftheMarkRing
Popsofftheyoungest(mostrecent)MarkRingentryandsetsMark
EachadditionalCONTROL-UCONTROL-@commandcausesemacstomovePointandthecursorto
thepreviousentryontheMarkRing.
Althoughthisprocessmayseemcomplex,itreallyjustmakesasafejumptoapreviousMarklocation.It
issafebecauseeachjump'sstartingpointisrecirculatedthroughtheMarkRing,whereitiseasytofind
again.YoucanjumptoallpreviouslocationsontheMarkRing(itmaybefewerthan16)bygivingthe
commandCONTROL-UCONTROL-@againandagain.Youcangoaroundtheringasmanytimesasyou
likeandstopwheneveryouwant.
SettingMarkAutomatically
SomecommandssetMarkautomatically:TheideaistoleaveabookmarkbeforemovingPointalong
distance.Forexample,META->setsMarkbeforejumpingtotheendofthebuffer.Youcanthenreturnto
yourstartingpositionwithCONTROL-UCONTROL-@.Searchesbehavesimilarly.Toavoidsurprises
themessageMarkSetappearsintheEchoAreawheneverMarkisset,eitherexplicitlyorimplicitly.
CutandPaste:YankingKilledText
RecallthatkilledtextisnotdiscardedbutratheriskeptintheKillRing.TheKillRingholdsthelast30
piecesofkilledtextandisvisiblefromallbuffers.
RetrievingtextfromtheKillRingiscalledyanking.Thisterminologyistheoppositeofthatusedinvim:
Invimyankingpullstextfromthebuffer,andputtingputstextintothebuffer.Killingandyankingwhich
areroughlyanalogoustocuttingandpastingareemacs'sprimarymechanismsformovingandcopying
text.Table7-6liststhemostcommonkillandyankcommands.
Table7-6.Commonkillandyankcommands
Command Result
META-d Killstoendofcurrentword
META-D Killsfrombeginningofpreviousword
CONTROL-K Killstoendofline,notincludingLINEFEED
CONTROL-U1CONTROL-K Killstoendofline,includingLINEFEED
CONTROL-U0CONTROL-K Killsfrombeginningofline

META-w CopiestheRegion(betweenPointandMark)totheKillRing
butdoesnoterasetheRegionfromthebuffer
CONTROL-W KillstheRegion(betweenPointandMark)
META-zchar Killsuptonextoccurrenceofchar
CONTROL-Y
Yanksthemostrecentlykilledtextintothecurrentbufferat
Point,setsMarkatthebeginningofthistext,andpositions
Pointandthecursorattheend
META-y Erasesthejust-yankedtext,rotatestheKillRing,andyanks
thenextitem(onlyafterCONTROL-YorMETA-y)
Tomovetwolinesoftext,movePointtothebeginningofthefirstlineandthenenterCONTROL-U2
CONTROL-Ktokilltwolines.NextmovePointtothedestinationposition,andenterCONTROL-Y.
Tocopytwolinesoftext,movePointtothebeginningofthefirstlineandgivethecommandsCONTROL-
U2CONTROL-KCONTROL-Ytokillandthenyankbackimmediately.ThenmovePointtothe
destinationpositionandtypeCONTROL-Y.
Tocopyalargerpieceofthebuffer,settheRegiontocoverthispieceandthentypeCONTROL-W
CONTROL-Ytokillandyankbackatonce.NextmovePointtothedestination,andtypeCONTROL-Y.
YoucanalsosettheRegionanduseMETA-wtocopytheRegiontotheKillRing.
TheKillRingisorganizedasafixed-lengthFIFOlist,witheachnewentrycausingtheeldesttobe
discarded(onceyoubuildupto30entries).Simplecut-and-pasteoperationsgenerallyuseonlythe
newestentry.Theolderentriesareretainedtogiveyoutimetochangeyourmindaboutadeletion.Ifyou
dochangeyourmindyoucan"mine"theKillRinglikeanarchaeologicaldig,workingbackwardthrough
timeanddownthroughthestrataofkilledmaterialtocopyaspecificitembackintothebuffer.
TovieweveryentryintheKillRing,beginayankingsessionbypressingCONTROL-Y.Thisaction
copiestheyoungestentrytoyourbufferatthecurrentcursorposition.Ifthisentryisnottheitemyouwant,
continuetheyankingsessionbypressingMETA-y.Thisactionerasesthepreviousyankandcopiesthe
nextyoungestentrytothebufferatthecurrentcursorposition.Ifthisstillisnottheitemyouwanted,press
META-yagaintoeraseitandretrieveacopyofthenextentry,andsoon.YoucancontinuegivingMETA-
ycommandsallthewaybacktotheoldestentry.IfyoucontinuetopressMETA-y,youwrapbacktothe
youngestentryagain.Inthismanneryoucanexamineeachentryasmanytimesasyouwish.
ThesequenceusedinayankingsessionconsistsofCONTROL-YfollowedbyanymixtureofCONTROL-
YandMETA-y.IfyoutypeanyothercommandafterMETA-y,thesequenceisbrokenandyoumustgive
theCONTROL-Ycommandagaintostartanotheryankingsession.
AsyouworkbackwardintheKillRing,itisusefultothinkofthisprocessasadvancingaLastYank

pointerbackthroughhistorytoincreasinglyolderentries.Thispointerisnotresettotheyoungestentry
untilyougiveanewkillcommand.Usingthistechnique,youcanworkbackwardpartwaythroughtheKill
RingwithCONTROL-YandafewMETA-ycommands,givesomecommandsthatdonotkill,andthen
pickupwhereyouleftoffwithanotherCONTROL-YandasuccessionofMETA-ycommands.
ItisalsopossibletopositiontheLastYankpointerwithpositiveornegativenumericargumentsto
META-y.Refertotheonlinedocumentationformoreinformation.
InsertingSpecialCharacters
Asstatedearlier,emacsinsertseverythingthatisnotacommandintothebufferatthepositionofthe
cursor.Toinsertcharactersthatwouldordinarilybeemacscommands,youcanusetheemacsescape
character:CONTROL-Q.Therearetwowaysofusingthisescapecharacter:
CONTROL-Qfollowedbyanyothercharacterinsertsthatcharacterinthebuffer,nomatterwhat
commandinterpretationitwassupposedtohave.
CONTROL-Qfollowedbythreeoctaldigitsinsertsabytewiththatvalueinthebuffer.
tip:CONTROL-Q
Dependingonthewayyourterminalissetup,CONTROL-Qmayclashwithsoftwareflow
control.IfCONTROL-Qseemstohavenoeffect,itismostlikelybeingusedforflow
control.Inthatcaseyoumustbindanotherkeytothecommandquoted-insert(page237).
GlobalBufferCommands
Thevimeditoranditspredecessorshaveglobalcommandsforbufferwidesearchandreplace
operations.TheirdefaultoperatingRegionistheentirebuffer.Theemacseditorhasasimilarfamilyof
commands.TheiroperatingRegionbeginsatPointandextendstotheendofthebuffer.Ifyouwishto
operateontheentirebuffer,useMETA-<tosetPointatthebeginningofthebufferbeforeissuingthe
command.
Line-OrientedOperations
ThecommandslistedinTable7-7takearegularexpressionandapplyittothelinesbetweenPointand
theendofthebuffer.

Table7-7.Line-orientedoperations
Command Result
META-xoccur Promptsforaregularexpressionandcopieseachlinewitha
matchfortheexpressioninabuffernamed*Occur*
META-xdelete-matching-lines Promptsforaregularexpressionanddeleteseachlinewitha
matchfortheexpression
META-xdelete-non-matching-
lines
Promptsforaregularexpressionanddeleteseachlinethat
doesnothaveamatchforthatexpression
TheMETA-xoccurcommandputsitsoutputinaspecialbuffernamed*Occur*,whichyoucanperuse
anddiscardoruseasajumpmenutoreacheachlinequickly.Tousethe*Occur*bufferasajumpmenu,
switchtoit(CONTROL-Xo[lowercase"o"]),movethecursortothecopyofthedesireddestination
line,andtypeCONTROL-CCONTROL-C.Thiscommandmovesthecursortothebufferthatwas
searchedandpositionsitonthelinethattheregularexpressionmatched.
Aswithanybufferchange,youcanundothedeletioncommands.
UnconditionalandInteractiveReplacement
ThecommandslistedinTable7-8operateonthecharactersbetweenPointandtheendofthebuffer,
changingeverystringmatchorregularexpressionmatch.Anunconditionalreplacementmakesall
replacementsautomatically.Aninteractivereplacementgivesyoutheopportunitytoseeandapproveeach
replacementbeforeitismade.
Table7-8.Replacementcommands
Command Result
META-xreplace-string
Promptsforstringandnewstringandreplacesevery
instanceofstringwithnewstring.Pointisleftatthesiteof
thelastreplacement,butMarkissetwhenyougivethe
command,soyoucanreturntoitwithCONTROL-U
CONTROL-@.
META-xreplace-regexp
Promptsforregexpandnewstringandreplacesevery
matchforregexpwithnewstring.Pointisleftatthesiteof
thelastreplacement,butMarkissetwhenyougivethe
command,soyoucanreturntoitwithCONTROL-U
CONTROL-@.
META-%stringorMETA-xquery-
replace
Thefirstformusesstring,thesecondformpromptsfor
string.Bothformspromptfornewstring,queryeach
instanceofstring,and,dependingonyourresponse,
replaceitwithnewstring.Pointisleftatthesiteofthelast

replacement,butMarkissetwhenyougivethecommand,
soyoucanreturntoitwithCONTROL-UCONTROL-@.
META-xquery-replace-regexp
Promptsforregexpandnewstring,querieseachmatchfor
regexp,and,dependingonyourresponse,replacesitwith
newstring.Pointisleftatthesiteofthelastreplacement,
butMarkissetwhenyougivethecommand,soyoucan
returntoitwithCONTROL-UCONTROL-@.
Ifyouperformaninteractivereplacement,emacsdisplayseachinstanceofstringormatchforregexp
andpromptsyouforanactiontotake.Table7-9listssomeofthepossibleresponses.
Table7-9.Responsestointeractivereplacementprompts
Response Meaning
RETURN Donotdoanymorereplacements;quitnow.
SPACE Makethisreplacementandgoon.
DELETE Donotmakethisreplacement.Skipitandgoon.
,(comma)
Makethisreplacement,displaytheresult,andaskforanother
command.AnycommandislegalexceptDELETEistreated
likeSPACEanddoesnotundothechange.
.(period) Makethisreplacementandquitsearching.
!(exclamationpoint) Replacethisandallremaininginstanceswithoutaskingany
morequestions.
Files
Whenyouvisit(emacsterminologyfor"callup")afile,emacsreadsitintoabuffer(page220),allows
youtoeditthebuffer,andeventuallysavesthebufferbacktothefile.Thecommandsdiscussedhererelate
tovisitingandsavingfiles.
META-xpwdMETA-xcd
Eachemacsbufferkeepsarecordofitsdefaultdirectory(thedirectorythefilewasreadfromorthe
workingdirectory,ifitisanewfile)thatisprependedtoanyrelativepathnameyouspecify.This

convenienceismeanttosavesometyping.EnterMETA-xpwdtoprintthedefaultdirectoryforthecurrent
bufferorMETA-xcdtopromptforanewdefaultdirectoryandassignittothisbuffer.
VisitingFiles
Theemacseditordealswellwithvisitingafilethathasalreadybeencalledupandwhoseimageisnow
inabuffer.Afteracheckofthemodificationtimetoensurethatthefilehasnotbeenchangedsinceitwas
lastcalledup,emacssimplyswitchestothatbuffer.Table7-10listscommandsusedtovisitfiles.
Table7-10.Visitingfiles
Command Result
CONTROL-XCONTROL-F
Promptsforafilenameandreadsitscontentsintoa
freshlycreatedbuffer.Assignsthefile'ssimplefilename
asthebuffername.Otherbuffersareunaffected.Itis
commonandoftenusefultohaveseveralfilesopen
simultaneouslyforediting.
CONTROL-XCONTROL-V
Promptsforafilenameandreplacesthecurrentbuffer
withabuffercontainingthecontentsoftherequested
file.Thecurrentbufferisdestroyed.
CONTROL-X4CONTROL-F
Promptsforafilenameandreadsitscontentsintoanew
buffer.Assignsthefile'ssimplefilenameasthebuffer
name.Createsanewwindowforthisbufferandselects
thatwindow.Thewindowselectedbeforethecommand
stilldisplaysthebufferitwasshowingbeforethis
operation,althoughthenewwindowmaycoveruppart
oftheoldwindow.
Tocreateanewfile,simplycallitup.Anemptybufferiscreatedandproperlynamedsoyoucan
eventuallysaveit.Themessage(NewFile)appearsintheEchoArea,reflectingemacs'sunderstanding
ofthesituation.Ofcourse,ifthis"newfile"grewoutofatypographicalerror,youwillprobablywantto
issueCONTROL-XCONTROL-Vwiththecorrectname.
SavingFiles
Yousaveabufferbycopyingitscontentsbacktotheoriginalfileyoucalledup.Therelevantcommands
arelistedinTable7-11.
Table7-11.Savingfiles
Command Result
Thisworkhorsefile-savingcommandsavesthecurrentbuffer

CONTROL-XCONTROL-S intoitsoriginalfile.Ifthecurrentbufferisnotmodified,you
getthefollowingmessage:(Nochangesneedtobesaved).
CONTROL-Xs
Foreachmodifiedbuffer,youareaskedwhetheryouwishto
saveit.Answeryorn.Thiscommandisgivenautomatically
asyouexitfromemacsandallowsyoutosaveanybuffers
thathavebeenmodifiedbutnotyetwrittenout.Ifyouwantto
saveintermediatecopiesofyourwork,youcangivethis
commandatanytime.
META-xset-visited-file-name Promptsforafilenameandsetsthisnameasthecurrent
buffer's"original"name.
CONTROL-XCONTROL-W
Promptsforafilename,setsthisnameasthe"original"name
forthecurrentbuffer,andsavesthecurrentbufferintothat
file.ItisequivalenttoMETA-xset-visited-file-name
followedbyCONTROL-XCONTROL-S.
META-~(tilde)
Clearsmodifiedflagfromthecurrentbuffer.Ifyou
mistakenlytypedMETA-~againstabufferwithchangesyou
wanttokeep,youneedtomakesurethatthemodified
conditionandits**indicatorareturnedbackonbeforeleaving
emacs,orallthechangeswillbelost.Oneeasywaytodo
thisistoinsertaSPACEintothebufferandthenremoveit
againwithDELETE.
Buffers
Anemacsbufferisastorageobjectthatyoucanedit.Itoftenholdsthecontentsofafilebutcanalso
existwithoutbeingassociatedwithafile.Youcanselectonlyonebufferatatime,designatedasthe
currentbuffer.Mostcommandsoperateonlyonthecurrentbuffer,evenwhenmultiplewindowsshow
twoormorebuffersonthescreen.Forthemostparteachbufferisitsownworld:Ithasitsownname,its
ownmodes,itsownfileassociations,itsownmodifiedstate,andperhapsitsownspecialkeybindings.
YoucanusethecommandsshowninTable7-12tocreate,select,list,andmanipulatebuffers.
Table7-12.Workwithbuffers
Command Result
CONTROL-Xb Promptsforabuffernameandselectsit.Ifthebufferyouname
doesnotexist,thiscommandcreatesit.
CONTROL-X4b
Promptsforabuffernameandselectsitinanotherwindow.The
existingwindowisnotdisturbed,althoughthenewwindowmay
overlapit.
Createsabuffernamed*Bufferlist*anddisplaysitinanother
window.Theexistingwindowisnotdisturbed,althoughthenew
windowmayoverlapit.Thenewbufferisnotselected.Inthe*

CONTROL-XCONTROL-B Bufferlist*buffer,eachbuffer'sdataisshownalongwiththe
name,size,mode(s),andoriginalfilename.A%appearsfora
readonlybuffer,a*indicatesamodifiedbuffer,and.appearsfor
theselectedbuffer.
META-xrename-buffer Promptsforanewbuffernameandgivesthisnewnametothe
currentbuffer.
CONTROL-XCONTROL-
Q
Togglesthecurrentbuffer'sreadonlystatusandtheassociated%%
ModeLineindicator.Thiscanbeusefultopreventaccidental
buffermodificationortoallowmodificationofabufferwhen
visitingareadonlyfile.
META-xappend-to-buffer PromptsforabuffernameandappendstheRegion(betweenPoint
andMark)totheendofthatbuffer.
META-xprepend-to-buffer PromptsforabuffernameandprependstheRegion(between
PointandMark)tothebeginningofthatbuffer.
META-xcopy-to-buffer Promptsforabuffernameanddeletesthecontentsofthebuffer
beforecopyingtheRegion(betweenPointandMark)tothatbuffer.
META-xinsert-buffer Promptsforabuffernameandinsertstheentirecontentsofthat
bufferintothecurrentbufferatPoint.
CONTROL-Xk Promptsforabuffernameanddeletesthatbuffer.Ifthebufferis
modifiedbutunsaved,youareaskedtoconfirmtheoperation.
META-xkill-some-buffers
Goesthroughtheentirebufferlistandoffersthechancetodelete
eachbuffer.AswithCONTROL-Xk,youareaskedtoconfirm
thekillcommandifamodifiedbufferisnotyetsaved.
caution:Didyoumodifyabufferbymistake?
WhenyougiveaCONTROL-Xscommand,youmaydiscoverfileswhosebufferswere
modifiedbymistakeasemacstriestosavethewrongchangesbacktothefile.When
emacspromptsyoutoconfirmthesave,donotansweryifyouarenotsure.Firstexit
fromtheCONTROL-Xsdialogbytypingntoanysavesyouarenotsureabout.Youthen
haveseveraloptions:
SavethesuspiciousbufferintoatemporaryfilewithCONTROL-XCONTROL-W
andanalyzeitlater.
UndothechangeswithastringofCONTROL-_commandsuntilthe**indicator
disappearsfromthebuffer'sModeLine.

Ifyouaresurethatallthechangesarewrong,useMETA-xrevert-buffertogeta
freshcopyofthefile.
Killthebufferoutright.Becauseitismodified,emacsaskswhetheryouaresure
beforecarryingoutthiscommand.
GivetheMETA-~(tilde)commandtoclearthemodifiedconditionand**indicator.A
subsequentCONTROL-Xsthenbelievesthatthebufferdoesnotneedtobewritten.
caution:Youcanexitwithoutfirstgettingawarning
Clearingthemodifiedflag(META-~)allowsyoutoexitwithoutsavingamodifiedbuffer
withnowarning.MakesureyouknowwhatyouaredoingwhenyouuseMETA-~.
Windows
Anemacswindowisaviewportthatlooksintoabuffer.Theemacsscreenbeginsbydisplayinga
singlewindow,butthisscreenspacecanlaterbedividedamongtwoormorewindows.Onthescreenthe
currentwindowholdsthecursorandviewsthecurrentbuffer.Foratiponterminology,see"Thescreen
andemacswindows"onpage197.
Awindowviewsonebufferatatime.Youcanswitchthebufferthatawindowviewsbygivingthe
commandCONTROL-Xbbuffer-nameinthecurrentwindow.Multiplewindowscanviewonebuffer;
eachwindowmayviewdifferentpartsofthesamebuffer;andeachwindowhasitsownPointvalue.Any
changetoabufferisreflectedinallthewindowsviewingthatbuffer.Also,abuffercanexistwithouta
windowopenonit.
SplittingaWindow
Onewaytodividethescreenistosplitthestartingwindowexplicitlyintotwoormorepieces.The
commandCONTROL-X2splitsthecurrentwindowintwo,withonenewwindowappearingabovethe
other.Anumericargumentistakenasthesizeoftheupperwindowinlines.ThecommandCONTROL-X
3splitsthecurrentwindowintwo,withthenewwindowsbeingarrangedsidebyside(Figure7-7).A
numericargumentistakenasthenumberofcolumnstogivetheleftwindow.Forexample,CONTROL-U
CONTROL-X2splitsthecurrentwindowintwo;becauseofthespecial"times4"interpretationof

CONTROL-Ustandingalone,theupperwindowisgivenfourlines(barelyenoughtobeuseful).
Figure7-7.Splittingawindowvertically
[Viewfullsizeimage]
Althoughthesecommandssplitthecurrentwindow,bothwindowscontinuetoviewthesamebuffer.You
canselectanewbufferineitherorbothnewwindows,oryoucanscrolleachwindowtoshowdifferent
portionsofthesamebuffer.
ManipulatingWindows
CONTROL-XoMETA-CONTROL-V
YoucanuseCONTROL-Xo(lowercase"o")toselecttheotherwindow.Ifmorethantwowindows
appearonthescreen,asequenceofCONTROL-Xocommandscyclesthroughthemintop-to-bottom,left-
to-rightorder.TheMETA-CONTROL-Vcommandscrollstheotherwindow.Ifmorethantwowindows
arevisible,thecommandscrollsthewindowthatCONTROL-Xowouldselectnext.Youcanusea
positiveornegativescrollingargument,justaswithCONTROL-Vscrollinginthecurrentwindow.
Other-WindowDisplay
CONTROL-X4bCONTROL-X4f
Innormalemacsoperation,explicitwindowsplittingisnotnearlyascommonastheimplicitsplitting

donebythefamilyofCONTROL-X4commands.TheCONTROL-X4bcommand,forexample,prompts
forabuffernameandselectsitintheotherwindow.Ifthereisnootherwindow,thiscommandbegins
withahalf-and-halfsplitthatarrangesthewindowsoneabovetheother.TheCONTROL-X4fcommand
promptsforafilename,callsitupintheotherwindow,andselectstheotherwindow.Ifthereisnoother
window,thiscommandbeginswithahalf-and-halfsplitthatarrangesthewindowsoneabovetheother.
AdjustingandDeletingWindows
CONTROL-X0CONTROL-X1
Windowsmaybedestroyedwhentheygetintheway.Nodataislostinthewindow'sassociatedbuffer
withthisoperation,andyoucanmakeanotherwindowwheneveryoulike.TheCONTROL-X0(zero)
commanddeletesthecurrentwindowandgivesitsspacetoitsneighbors;CONTROL-X1deletesall
windowsexceptthecurrentwindow.
META-xshrink-windowCONTROL-X^CONTROL-X}CONTROL-X{
Youcanalsoadjustthedimensionsofthecurrentwindow,onceagainattheexpenseofitsneighbors.To
makeawindowshorter,useMETA-xshrink-window.UseCONTROL-X^toincreasetheheightofa
window,CONTROL-X}tomakethewindowwider,andCONTROL-X{tomakethewindownarrower.
Eachofthesecommandsaddsorsubtractsonelineorcolumntoorfromthewindow,unlessyouprecede
thecommandwithanumericargument.
Theemacseditorhasitsownguidelinesforawindow'sminimumusefulsizeandmaydestroyawindow
beforeyouforceoneofitsdimensionstozero.Althoughthewindowmaydisappear,thebufferremains
intact.
ForegroundShellCommands
Theemacseditorcanrunasubshell(ashellthatisachildoftheshellthatisrunningemacsreferto
"ExecutingaCommand"onpage294)toexecuteasinglecommandline,optionallywithstandardinput
comingfromtheRegionofthecurrentbufferandoptionallywithstandardoutputreplacingtheRegion
(Table7-13).Thisprocessisanalogoustoexecutingashellcommandfromthevimeditorandhavingthe
inputcomefromthefileyouareeditingandtheoutputgobacktothesamefile(page183).Aswithvim,
howwellthisprocessworksdependsinpartonthecapabilitiesoftheshell.
Table7-13.Foregroundshellcommands
Command Result
META-!(exclamationpoint) Promptsforashellcommand,executesit,anddisplaysthe
output

CONTROL-UMETA-!
(exclamationpoint)
Promptsforashellcommand,executesit,andinsertsthe
outputatPoint
META-|(verticalbar) Promptsforashellcommand,givestheRegionasinput,
filtersitthroughthecommand,anddisplaystheoutput
CONTROL-UMETA-|(vertical
bar)
Promptsforashellcommand,givestheRegionasinput,
filtersitthroughthecommand,deletestheoldRegion,and
insertstheoutputinthatposition
Theemacseditorcanalsostartaninteractivesubshellthatrunscontinuouslyinitsownbuffer.See
"ShellMode"onpage234formoreinformation.
BackgroundShellCommands
Theemacseditorcanrunprocessesinthebackground,withtheiroutputbeingfedintoagrowing
emacsbufferthatdoesnothavetoremaininview.Youcancontinueeditingwhilethebackground
processrunsandlookatitsoutputlater.Anyshellcommandcanberuninthisway.
Thegrowingoutputbufferisalwaysnamed*compilation*.Youcanreadit,copyfromit,oredititinany
way,withoutwaitingforthebackgroundprocesstofinish.Mostcommonlythisbufferisusedtoreview
theoutputofprogramcompilationandtocorrectanysyntaxerrorsfoundbythecompiler.
META-xcompile
Torunaprocessinthebackground,givethecommandMETA-xcompiletopromptforashellcommand
andbeginexecutingitasabackgroundprocess.Thescreensplitsinhalftoshowthe*compilation*
buffer.
Youcanswitchtothe*compilation*bufferandwatchtheexecution,ifyouwish.Tomakethedisplay
scrollasyouwatch,positionthecursorattheveryendofthetextwithaMETA->command.Ifyouarenot
interestedinthisdisplayjustremovethewindowwithCONTROL-X0(zero)ifyouareinitor
CONTROL-X1otherwiseandkeepworking.Youcanswitchbacktothe*compilation*bufferlaterwith
CONTROL-Xb.
YoucankillthebackgroundprocesswithMETA-xkill-compilation.Theemacseditorasksfor
confirmationandthenkillsthebackgroundprocess.
Ifstandardformaterrormessagesappearin*compilation*,youcanautomaticallyvisitthelineinthefile
whereeacherroroccurred.GivethecommandCONTROL-X'(backtick)tosplitthescreenintotwo
windowsandvisitthefileandlineofthenexterrormessage.Scrollthe*compilation*bufferuntilthis
errormessageappearsatthetopofitswindow.UseCONTROL-UCONTROL-X'tostartoverwiththe
firsterrormessageandvisitthatfileandline.

Language-SensitiveEditing
Theemacseditorhasalargecollectionoffeaturesets,eachspecifictoacertainvarietyoftext.The
featuresetsarecalledMajormodes.AbuffercanhaveonlyoneMajormodeatanytime.
Abuffer'sMajormodeisprivatetothebufferanddoesnotaffecteditinginanyotherbuffer.Ifyouswitch
toanewbufferhavingadifferentmode,rulesforthenewmodeimmediatelytakeeffect.Toavoid
confusion,thenameofabuffer'sMajormodeappearsintheModeLineofanywindowviewingthat
buffer(Figure7-1onpage198).
ThethreeclassesofMajormodesareusedforthefollowingtasks:
Editinghumanlanguages(forexample,text,nroff,TeX)
Editingprogramminglanguages(forexample,C,Fortran,Lisp)
Specialpurposes(forexample,shell,mail,dired,ftp)
Inaddition,oneMajormodeFundamentaldoesnothingspecial.AMajormodeusuallysetsupthe
following:
Specialcommandsuniquetothemode,possiblywiththeirownkeybindings.Languagesmayhave
justafewspecialcommands,butspecial-purposemodesmayhavedozens.
Mode-specificcharactersyntaxandregularexpressionsdefiningwordconstituentcharacters,
delimiters,comments,whitespace,andsoon.Thissetupconditionsthebehaviorofcommands
orientedtosyntacticunits,suchaswords,sentences,comments,orparenthesizedexpressions.
SelectingaMajorMode
META-xmodename
Theemacseditorchoosesandsetsamodewhenafileiscalledupbymatchingthefilenameagainstaset
ofregularexpressionpatternsdescribingthefilenameandfilenameextension.Theexplicitcommandto
enteraMajormodeisMETA-xmodename.Thiscommandisrarelyusedexcepttocorrectwrong
guesses.
Afilecandefineitsownmodebyincludingthetext*modename*somewhereinthefirstnonblankline,
possiblyinsideacommentsuitableforthatprogramminglanguage.
Human-LanguageModes
Ahumanlanguageismeanteventuallytobeusedbyhumans,possiblyafterbeingformattedbysometext-
formattingprogram.Humanlanguagessharemanyconventionsaboutthestructureofwords,sentences,
andparagraphs.Withregardtothesetextualunits,themajorhumanlanguagemodesallbehaveinthesame
way.
Beyondthisareaofcommonality,eachmodeoffersadditionalfunctionalityorientedtoaspecifictext
formatter,suchasTeX,LaTeX,ornroff.Text-formatterextensionsarebeyondthescopeofthis
presentation;thefocushereisonthecommandsrelatingtohumantextualunits(forexample,words,
sentences,andparagraphs).
Words
Asamnemonicaid,thebindingsforwordsaredefinedparalleltothecharacter-orientedbindings
CONTROL-F,CONTROL-B,CONTROL-D,DELETE,andCONTROL-T.
JustasCONTROL-FandCONTROL-Bmoveforwardandbackwardovercharacters,META-fand
META-bmoveforwardandbackwardoverwords.Theymaystartfromapositioninsideoroutsidethe
wordtobetraversed,butinallcasesPointfinishesjustbeyondtheword,adjacenttothelastcharacter
skippedover.Bothcommandsacceptanumericargumentspecifyingthenumberofwordstobetraversed.
JustasCONTROL-DandDELETEdeletecharactersforwardandbackward,thekeysMETA-dand
META-DELETEkillwordsforwardandbackward.TheyleavePointinexactlythesamefinishing
positionasMETA-fandMETA-bdo,buttheykillthewordstheypassover.Theyalsoacceptanumeric
argument.
META-ttransposesthewordbeforePointwiththewordafterPoint.
Sentences
Asamnemonicaid,threeofthebindingsforsentencesaredefinedparalleltotheline-orientedbindings:
CONTROL-A,CONTROL-E,andCONTROL-K.TheMETA-acommandmovesbackwardtothe
beginningofasentence,andMETA-emovesforwardtotheendofasentence.Inaddition,CONTROL-X
DELETEkillsbackwardtothebeginningofasentence;META-kkillsforwardtotheendofasentence.
Theemacseditorrecognizestheendsofsentencesbyreferringtoaregularexpressionthatiskeptina
variablenamedsentence-end.(Ifyouarecurious,givethecommandCONTROL-Hvsentence-end
RETURNtoviewthisvariable.)Briefly,itlooksforthecharacters.,?,or!followedbytwoSPACEsor
anend-of-linemarker,possiblywithclosequotationmarksorclosebraces.
TheMETA-aandMETA-ecommandsleavePointadjacenttothefirstorlastnonblankcharacterinthe
sentence.Theyacceptanumericargumentspecifyingthenumberofsentencestotraverse;anegative
argumentrunstheminreverse.
TheMETA-kandCONTROL-XDELETEcommandskillsentencesforwardandbackward,inamanner
analogoustoCONTROL-Klinekill.TheyleavePointinexactlythesamefinishingpositionasMETA-a
andMETA-edo,buttheykillthesentencestheypassover.Theyalsoacceptanumericargument.
CONTROL-XDELETEisusefulforquicklybackingoutofahalf-finishedsentence.
Paragraphs
TheMETA-{commandmovesbackwardtothemostrecentparagraphbeginning,andMETA-}moves
forwardtothenextparagraphending.TheMETA-hcommandmarkstheparagraph(thatis,putsPointat
thebeginningandMarkattheend)thatthecursoriscurrentlyon,orthenextparagraphifitisbetween
paragraphs.
TheMETA-}andMETA-{commandsleavePointatthebeginningofaline,adjacenttothefirstcharacter
orlastcharacteroftheparagraph.Theyacceptanumericargumentspecifyingthenumberofparagraphsto
traverseandruninreverseifgivenanegativeargument.
Inhuman-languagemodes,paragraphsareseparatedbyblanklinesandtext-formattercommandlines,and
anindentedlinestartsaparagraph.Recognitionisbasedontheregularexpressionsstoredinthe
variablesparagraph-separateandparagraph-start.Aparagraphiscomposedofcompletelines,
includingthefinallineterminator.Ifaparagraphstartsfollowingoneormoreblanklines,thelastblank
linebeforetheparagraphbelongstotheparagraph.
Fill
Theemacseditorcanfillaparagraphtofitaspecifiedwidth,breakinglinesandrearrangingthemas
necessary.Breakingtakesplaceonlybetweenwordsandnohyphenationoccurs.Fillingcanbedone
automaticallyasyoutypeorinresponsetoanexplicitcommand.
TheMETA-xauto-fill-modecommandtogglesAutoFillmodeonandoff.WhenAutoFillmodeison,
emacsautomaticallybreakslineswhenyoupressSPACEorRETURNandarecurrentlybeyondthe
specifiedlinewidth.Thisfeatureisusefulwhenyouareenteringnewtext.
AutoFillmodedoesnotautomaticallyrefilltheentireparagraphyouarecurrentlyworkingon.Ifyouadd
newtextinthemiddleofaparagraph,AutoFillmodebreaksyournewtextasyoutypebutdoesnotrefill
thecompleteparagraph.TorefillacompleteparagraphorRegionofparagraphs,useeitherMETA-qto
refillthecurrentparagraphorMETA-xfill-regiontorefilleachparagraphintheRegionbetweenPoint
andMark.
Youcanchangethefillingwidthfromitsdefaultvalueof70bysettingthefill-columnvariable.Use
CONTROL-Xftosetfill-columntothecurrentcursorpositionandCONTROL-UnnnCONTROL-Xfto
setfill-columntonnn,where0istheleftmargin.

CaseConversion
TheemacseditorcanforcewordsorRegionstoalluppercase,alllowercase,orinitialcaps(thefirst
letterofeachworduppercase,therestlowercase).RefertoTable7-14.
Table7-14.Caseconversion
Command Result
META-l(lowercase"l") ConvertswordtotherightofPointtolowercase
META-u ConvertswordtotherightofPointtouppercase
META-c ConvertswordtotherightofPointtoinitialcaps
CONTROL-XCONTROL-L ConvertstheRegion(betweenPointandMark)tolowercase
CONTROL-XCONTROL-U ConvertstheRegion(betweenPointandMark)touppercase
Theword-orientedconversionsmovePointoverthewordjustconverted(justasMETA-fdoes),
allowingyoutowalkthroughtextandconverteachwordwithMETA-l,META-u,orMETA-c,orskip
overwordstobeleftalonewithMETA-f.Apositivenumericargumentconvertsthatnumberofwordsto
therightofPoint,movingPointasitgoes.Anegativenumericargumentconvertsthatnumberofwordsto
theleftofPointbutleavesPointstationary.Thisfeatureisusefulforquicklychangingthecaseofwords
youhavejusttyped.Table7-15showssomeexamples.
Table7-15.Examplesofcaseconversion
Charactersandcommands Result
HELLOMETA-META-l(lowercase
"l") hello
helloMETA-META-u HELLO
helloMETA-META-c Hello
Thewordconversionsarenotpickyaboutbeginninginthemiddleofaword.Inallcases,theyconsider
thefirstword-constituentcharactertotherightofPointasthebeginningofthewordtobeconverted.
TextMode

Withveryfewexceptions,thecommandsforhuman-languagetextunits,suchaswordsandsentences,are
alwaysturnedonandavailable,evenintheprogramming-languagemodes.Textmodeaddsverylittleto
thesebasiccommandsbutisstillworthturningonjusttogettheTABkey.UsethecommandMETA-x
text-modetoactivateTextmode.
InTextmodeTABrunsthefunctiontab-to-tab-stop.BydefaultTABstopsareseteveryeightcolumns.
YoucanadjustthemwithMETA-xedit-tab-stops,whichswitchestoaspecial*TabStops*buffer.The
currentstopsarelaidoutinthisbufferonascaleforyoutoedit.Thenewstopsareinstalledwhenorif
youtypeCONTROL-CCONTROL-C.Ofcourse,youarefreetokillthisbuffer(CONTROL-Xk)or
switchawayfromit(CONTROL-Xb)withouteverchangingthestops.
ThetabstopsyousetwiththeMETA-xedit-tab-stopscommandaffectonlytheinterpretationofTAB
charactersarrivingfromthekeyboard.Theemacseditorautomaticallyinsertsenoughspacestoreachthe
TABstop.ThiscommanddoesnotaffecttheinterpretationofTABcharactersalreadyinthebufferorthe
underlyingfile.IfyouedittheTABstopsandthenusethem,youcanstillprintthefileandthehardcopy
willlookthesameasthetextonthescreen.
CMode
Programminglanguagesarereadbyhumansbutareinterpretedbymachines.Besidescontinuingtohandle
someofthehuman-languagetextunits(forexample,wordsandsentences),themajorprogramming-
languagemodesaddressseveraladditionalproblems:
Balancedexpressionsenclosedbyparentheses,brackets,orbracesastextualunits
Commentsastextualunits
Indention
TheemacseditorincludesMajormodestosupportC,Fortran,andseveralvariantsofLisp.Inaddition,
manyusershavecontributedmodesfortheirfavoritelanguages.Inthesemodesthecommandsforhuman
textualunitsarestillavailable,withoccasionalredefinitions.Forexample,aparagraphisboundedonly
byblanklinesandindentiondoesnotsignalaparagraphstart.Inaddition,eachmodehascustomcoding
tohandlethelanguage-specificconventionsforbalancedexpressions,comments,andindention.This
presentationdiscussesonlyCmode.
Expressions
TheemacsMajormodesarelimitedtolexicalanalysis.Theycanrecognizemosttokens(forexample,
symbols,strings,andnumbers)andallmatchedsetsofparentheses,brackets,andbraces.Thisisenough
forLispbutnotforC.TheCmodelacksafull-functionsyntaxanalyzerandisnotpreparedtorecognize

allofC'spossibleexpressions.[1]
[1]IntheemacsdocumentationtherecurringtermsexpreferstotheLisptermS-expression.Unfortunately,itissometimesused
interchangeablywithexpression,eventhoughthelanguagemightnotbeLisp.
Table7-16liststheemacscommandsapplicabletoparenthesizedexpressionsandsometokens.By
designthebindingsrunparalleltotheCONTROLcommandsforcharactersandtheMETAcommandsfor
words.Allthesecommandsacceptanumericargumentandruninreverseifthatargumentisnegative.
Table7-16.Commandsforexpressionsandtokens
Command Result
CONTROL-META-f
Movesforwardoveranexpression.Theexactbehavior
dependsonwhichcharacterliestotherightofPoint(orleft
ofPoint,dependingonwhichdirectionyouaremovingPoint).
Ifthefirstnonwhitespaceisanopeningdelimiter
(parenthesis,bracket,orbrace),Pointismovedjust
pastthematchingclosingdelimiter.
Ifthefirstnonwhitespaceisatoken,Pointismoved
justpasttheendofthistoken.
CONTROL-META-b Movesbackwardoveranexpression.
CONTROL-META-k
Killsanexpressionforward.ThiscommandleavesPointatthe
samefinishingpositionasCONTROL-META-fbutkillsthe
expressionittraverses.
CONTROL-META-@
SetsMarkatthepositionCONTROL-META-fwouldmoveto
butdoesnotchangePoint.ToseethemarkedRegionclearly,
giveapairofCONTROL-XCONTROL-Xcommandsto
interchangePointandMark.
FunctionDefinitions
Inemacsabalancedexpressionattheoutermostlevelisconsideredtobeafunctiondefinitionandis
oftencalledadefun,eventhoughthattermisspecifictoLisp.Moregenerallyitisunderstoodtobea
functiondefinitioninthelanguageathand.
InCmodeafunctiondefinitionincludesthereturndatatype,thefunctionname,andtheargument
declarationsappearingbeforethe{character.Table7-17showsthecommandsforoperatingonfunction
definitions.
Table7-17.Functiondefinitions
Command Result

CONTROL-META-a
Movestothebeginningofthemostrecentfunctiondefinition.
Usethiscommandtoscanbackwardthroughabufferone
functionatatime.
CONTROL-META-e
Movestotheendofthenextfunctiondefinition.Usethis
commandtoscanforwardthroughabufferonefunctionata
time.
CONTROL-META-h
PutsPointatthebeginningandMarkattheendofthecurrent
functiondefinition(ornextfunctiondefinition,ifbetween
two).Thiscommandsetsupanentirefunctiondefinitionfora
Region-orientedoperationsuchaskill.
caution:Functionindentionstyle
Theemacseditorassumesthatanopeningbraceattheleftmarginispartofafunction
definition.Thisheuristicspeedsupthereversescanforadefinition'sleadingedge.Ifyour
codehasanindentionstylethatputsthatopeningbraceelsewhere,youmaygetunexpected
results.
Indention
TheemacsCmodehasextensivelogictocontroltheindentionofCprograms.Furthermore,youcan
adjustthislogicformanydifferentstylesofCindention(Table7-18).
Table7-18.Indentioncommands
Command Result
TAB
Adjuststheindentionofthecurrentline.TABinsertsordeletes
whitespaceatthebeginningofthelineuntiltheindention
conformstothecurrentcontextandrulesineffect.Pointis
notmovedunlessitliesinthewhitespacearea;inthatcaseit
ismovedtotheendofthewhitespace.TABdoesnotinsert
anythingexceptleadingwhitespace,soyoucanhititatany
timeandatanypositionintheline.Ifyoureallywanttoinsert
atabinthetext,useMETA-iorCONTROL-QTAB.
LINEFEED
ShorthandforRETURNfollowedbyTAB.TheLINEFEED
keyisaconvenienceforenteringnewcode,givingyouan
autoindentasyoubegineachline.
Thenexttwocommandsindentmultiplelineswithasinglecommand.

CONTROL-META-q
Reindentsalllinesinsidethenextpairofmatchedbraces.
CONTROL-META-qassumesthattheleftbraceiscorrectly
indentedanddrivestheindentionfromthere.Ifyouneedto
adjusttheleftbracetypeTABjusttotheleftofthebrace
beforegivingthiscommand.Alllinesuptothematchingbrace
areindentedasifyouhadtypedTABoneachone.
CONTROL-META-\
ReindentsalllinesintheRegion(betweenPointandMark).
PutPointjusttotheleftofaleftbraceandthengivethe
command.Alllinesuptothematchingbraceareindentedasif
youhadtypedTABoneachone.
CustomizingIndention
ManystylesofCprogramminghaveevolved,andemacsdoesitsbesttosupportautomaticindentionfor
allofthem.Theindentioncodingwascompletelyrewrittenforemacsversion19;itsupportsC,C++,
Objective-C,andJava.Thenewemacssyntacticanalysisismuchmorepreciseandcanclassifyeach
syntacticelementofeachlineofprogramtextintoasinglesyntacticcategory(outofabout50),suchas
statement,string,orelse-clause.Withtheresultofthatanalysisinhand,emacsgoestoanoffsettable
namedc-offsets-alistandlooksuphowmucheachlineshouldbeindentedfromtheprecedingline.
Tocustomizeindention,youmustchangetheoffsettable.Itispossibletodefineacompletelynewoffset
tableforeachcustomizedstylebutmuchmoreconvenienttofeedinashortlistofexceptionstothe
standardrules.Eachmainstreamstyle(GNU,K&R[KernighanandRitchie],BSD,andsoon)hassuchan
exceptionlist;allarecollectedinc-style-alist.Hereisoneentryfromc-style-alist:
("gnu"
(c-basic-offset.2)
(c-comment-only-line-offset.(0.0))
(c-offsets-alist.((statement-block-intro.+)
(knr-argdecl-intro.5)
(substatement-open.+)
(label.0)
(statement-case-open.+)

(statement-cont.+)
(arglist-intro.c-lineup-arglist-intro-after-paren)
(arglist-close.c-lineup-arglist)
))
)
Constructingacustomstyleisbeyondthescopeofthisbook.Ifyouarecurious,thelongstoryisavailable
inemacsonlineinfobeginningat"CustomizingCIndentation."Thesample.emacsfilegiveninthis
chapter(page239)addsaverysimplecustomstyleandarrangestouseitonevery.cfilethatisedited.
Comments
Eachbufferhasitsowncomment-columnvariable,whichyoucanviewwiththeCONTROL-Hv
comment-columnRETURNhelpcommand.Table7-19listscommandsthatfacilitateworkingwith
comments.
Table7-19.Comments
Command Result
META-;
Insertsacommentonthecurrentlineoralignsanexisting
comment.Thiscommand'sbehaviordiffersaccordingtothe
situation.
Ifnocommentisonthisline,META-;createsan
emptycommentatthevalueofcomment-column.
Iftextalreadyonthislineoverlapsthepositionof
comment-column,META-;createsanempty
commentoneSPACEaftertheendofthetext.
Ifacommentisalreadyonthislinebutnotatthe
currentvalueofcomment-column,META-;realigns
thecommentatthatcolumn.Iftextisintheway,it
placesthecommentoneSPACEaftertheendofthe
text.
Onceanaligned(possiblyempty)commentexistsontheline,
Pointmovestothestartofthecommenttext.
CONTROL-X; Setscomment-columntothecolumnafterPoint.Theleft
marginiscolumn0.
Killsthecommentonthecurrentline.Thiscommandsets

CONTROL-UCONTROL-X; comment-columnfromthefirstcommentfoundabovethis
lineandthenperformsaMETA-;commandtoinsertoraligna
commentatthatposition.
CONTROL-UCONTROL-X;
Setscomment-columntothepositionofthefirstcomment
foundabovethislineandthenexecutesaMETA-;command
toinsertoralignacommentonthisline.
Special-PurposeModes
TheemacseditorincludesathirdfamilyofMajormodesthatarenotorientedtowardaparticular
languageoreventowardordinaryediting.Instead,thesemodesperformsomespecialfunction.The
followingmodesmaydefinetheirownkeybindingsandcommandstoaccomplishthatfunction:
Rmail:reads,archives,andcomposesemail
Dired:movesaroundinanlsldisplayandoperatesonfiles
VIP:simulatesacompletevienvironment
VC:allowsyoutodriveversion-controlsystems(includingRCS,CVS,andSubversion)fromwithin
emacs
GUD:GrandUnifiedDebugger;allowsyoutorunanddebugC(andother)programsfromwithin
emacs
Tramp:allowsyoutoeditfilesonanyremotesystemyoucanreachwithftporscp
Shell:runsaninteractivesubshellfrominsideanemacsbuffer
ThisbookdiscussesonlyShellmode.
ShellMode
One-timeshellcommandsandRegionfilteringwerediscussedearlier;referto"ForegroundShell
Commands"onpage224.InShellmode,however,eachemacsbufferhasanunderlyinginteractiveshell
permanentlyassociatedwithit.Thisshelltakesitsinputfromthelastlineofthebufferandsendsits
outputbacktothebuffer,advancingPointasitgoes.Ifyoudonoteditthebuffer,itholdsarecordofthe
completeshellsession.

Theshellrunsasynchronously,whetherornotyouhaveitsbufferinview.Theemacseditorusesidle
timetoreadtheshell'soutputandaddittothebuffer.
TypeMETA-xshelltocreateabuffernamed*shell*andstartasubshell.Ifabuffernamed*shell*
alreadyexists,emacsjustswitchestothatbuffer.Theshellthatthiscommandrunsistakenfromoneof
thefollowingsources:
TheLispvariableexplicit-shell-file-name
TheenvironmentvariableESHELL
TheenvironmentvariableSHELL
Tostartasecondshell,firstuseMETA-xrename-buffertochangethenameoftheexistingshell'sbuffer,
andthenuseMETA-xshelltostartanothershell.Youcancreateasmanysubshellsandbuffersasyou
like,allrunninginparallel.
AspecialsetofcommandsisdefinedinShellmode(Table7-20).Theyareboundmostlytotwo-key
sequencesstartingwithCONTROL-C.Eachsequenceissimilartotheordinarycontrolcharactersfound
inLinuxbutusesaleadingCONTROL-C.
Table7-20.Shellmode
Command Result
RETURN
IfPointisattheendofthebuffer,emacsinsertsthe
RETURNandsendsthis(thelast)linetotheshell.IfPointis
elsewhere,itcopiesthislinetotheendofthebuffer,peeling
offtheoldshellprompt(seetheregularexpressionshell-
prompt-pattern),ifoneexisted.Thenthiscopiedlinenowthe
lastinthebufferissenttotheshell.
CONTROL-CCONTROL-D SendsCONTROL-Dtotheshelloritssubshell.
CONTROL-CCONTROL-C SendsCONTROL-Ctotheshelloritssubshell.
CONTROL-CCONTROL-\ Sendsaquitsignaltotheshelloritssubshell.
CONTROL-CCONTROL-U Killsthetextonthecurrentlinenotyetcompleted.
CONTROL-CCONTROL-R Scrollsbacktothebeginningofthelastshelloutput,putting
thefirstlineofoutputatthetopofthewindow.
CONTROL-CCONTROL-O Deletesthelastbatchofshelloutput.

optional:Customizingemacs
AttheheartofemacsisaLispinterpreterwritteninC.ThisversionofLispissignificantlyextendedwithmanyspecial
commandsspecificallyorientedtoediting.Theinterpreter'smaintaskistoexecutetheLisp-codedsystemthatimplementsthe
look-and-feelofemacs.
Reducedtoitsessentials,thissystemimplementsacontinuousloopthatwatcheskeystrokesarrive,parsesthemintocommands,
executesthosecommands,andupdatesthescreen.Thisbehaviorcanbecustomizedinanumberofways.
Assinglekeystrokescomein,theyaremappedimmediatelythroughakeyboardtranslationtable.Bychangingtheentriesin
thistable,itispossibletoswapkeys.Ifyouareusedtoviorvim,youcanswapDELETEandCONTROL-H.Then
CONTROL-Hbackspacesasitdoesinvim,andDELETE(whichisnotusedbyvim)isthehelpkey.IfyouuseDELETE
asaninterruptkey,youmaywanttochooseanotherkeytoswapwithCONTROL-H.
Themappedkeystrokesaregatheredintosmallgroupscalledkeysequences.Akeysequencemaybeonlyasinglekey,such
asCONTROL-N,ormayincludetwoormorekeys,suchasCONTROL-XCONTROL-F.Oncegatheredthekey
sequencesareusedtoselectaparticularproceduretobeexecuted.Therulesforgatheringeachkeysequenceandthe
specificprocedurenametobeexecutedwhenthatsequencecomesinarecodifiedinaseriesoftablescalledkeymaps.By
alteringthekeymaps,youcanchangethegatheringrulesorchangewhichprocedureisassociatedwithwhichsequence.If
youareusedtovi'sorvim'suseofCONTROL-Wtobackupoverthewordyouareentering,youmaywanttochange
emacs'sCONTROL-Wbindingfromthestandardkill-regiontodelete-word-backward.
Thecommandbehaviorisoftenconditionedbyoneormoreglobalvariablesoroptions.Itmaybepossibletogetthe
behavioryouwantbysettingsomeofthesevariables.
ThecommanditselfisusuallyaLispprogramthatcanbereprogrammedtomakeitbehaveasdesired.Althoughthistaskis
notappropriateforbeginners,theLispsourcetonearlyallcommandsisavailableandtheinternalLispsystemisfully
documented.Asmentionedearlier,itiscommonpracticetoloadcustomizedLispcodeatstartuptime,evenifyoudidnot
writeityourself.
Mostemacsdocumentationglossesoverallthetranslation,gathering,andprocedureselectionandtalksaboutkeystrokesas
thoughtheywerecommands.However,itisstillimportanttoknowthattheunderlyingmachineryexistsandtounderstandthatits
behaviorcanbechanged.
THE.emacsSTARTUPFILE
Eachtimeyoustartemacs,itloadsthefileofLispcodenamed~/.emacs.Usingthisfileisthemostcommonwaytocustomize
emacs.Twocommandlineoptionscontroltheuseofthe.emacsfile.Theqoptionignoresthe.emacsfilesothatemacsstarts
upwithoutit;thisisonewaytogetpastabad.emacsfile.Theuuseroptionusesthe~user/.emacsfile(the.emacsfilefromthe
homedirectoryofuser).
The.emacsstartupfileisgenerallyconcernedonlywithkeybindingsandoptionsettings;itispossibletowritetheLispstatements
forthisfileinastraightforwardstyle.EachparenthesizedLispstatementisaLispfunctioncall.Insidetheparenthesesthefirst
symbolisthefunctionname;therestoftheSPACE-separatedtokensareargumentstothatfunction.Themostcommonfunction
inthe.emacsfile,setq,isasimpleassignmenttoaglobalvariable.Thefirstargumentisthenameofthevariabletosetandthe
secondargumentisitsvalue.Thefollowingexamplesetsthevariablenamedc-indent-levelto8:
(setqc-indent-level8)
Youcansetthedefaultvalueforavariablethatisbuffer-privatebyusingthefunctionnamesetq-default.Tosetaspecific
elementofavector,usethefunctionnameaset.Thefirstargumentisthenameofthevector,thesecondisthetargetoffset,and
thethirdisthevalueofthetargetentry.Inthestartupfilethenewvaluesareusuallyconstants.Table7-21showstheformatsof
theseconstants.
Table7-21.Formatsofconstantsin.emacs
Command Result

Numbers Decimalintegers,withanoptionalminussign
Strings
SimilartoCstringsbutwithextensionsforCONTROLand
METAcharacters:\C-syieldsCONTROL-S,\M-syields
META-s,and\M-\C-syieldsCONTROL-META-s
Characters
NotlikeCcharacters;startwith?andcontinuewithaprinting
characterorwithabackslashescapesequence(forexample,
?a,?\C-i,?\033)
Booleans Not1and0;usetfortrueandnilforfalse
OtherLispobjects Beginwithasinglequotationmarkandcontinuewiththe
object'sname
REMAPPINGKEYS
Theemacscommandloopbeginseachcyclebytranslatingincomingkeystrokesintothenameofthecommandtobeexecuted.
ThebasictranslationoperationusestheASCIIvalueoftheincomingcharactertoindexa128-elementvectorcalledakeymap.
Sometimesacharacter'seighthbitisinterpretedastheMETAcase,butthiscannotalwaysbereliedon.Atthepointoftranslation
allMETAcharactersappearwiththeESCAPEprefix,whetherornottheywereactuallytypedthatway.
Eachpositioninthisvectorisoneofthefollowing:
Notdefinedatall:Notranslationpossibleinthismap.
Thenameofanotherkeymap:Switchestothatkeymapandwaitsforthenextcharactertoarrive.
ThenameofaLispfunctiontobecalled:Translationprocessisdone;callthiscommand.
Becausekeymapscanreferenceotherkeymaps,anarbitrarilycomplexrecognitiontreecanbesetup.Themainstreamemacs
bindingsuseatmostthreekeys,withaverysmallgroupofwell-knownprefixkeys,eachwithitswell-knownkeymapname.
Eachbuffercanhavealocalkeymapthatisusedfirstforanykeystrokesarrivingwhileawindowintothatbufferisselected.The
localkeymapallowstheregularmappingtobeextendedoroverriddenonaper-bufferbasisandismostoftenusedtoaddbindings
foraMajormode.
Thebasictranslationflowrunsasfollows:
Mapthefirstcharacterthroughthebuffer'slocalkeymap.IfitisdefinedasaLispfunctionname,translationisdoneand
emacsexecutesthatfunction.Ifitisnotdefined,usethissamecharactertoindextheglobaltop-levelkeymap.
Mapthefirstcharacterthroughthetop-levelglobalkeymapglobal-map.Atthisandeachfollowingstage,thefollowing
conditionshold:
Iftheentryforthischaracterisnotdefined,itisanerror.Sendabelltotheterminalanddiscardallthecharacters
enteredinthiskeysequence.
IftheentryforthischaracterisdefinedasaLispfunctionname,translationisdoneandthefunctionisexecuted.
Iftheentryforthischaracterisdefinedasthenameofanotherkeymap,switchtothatkeymapandwaitforanother
charactertoselectoneofitselements.
Everythingmustbeacommandoranerror.Ordinarycharactersthataretobeinsertedinthebufferareusuallyboundtothe
commandself-insert-command.Eachofthewell-knownprefixcharactersiseachassociatedwithakeymap(Table7-22).

Table7-22.Keymapprefixes
Keymapprefix Appliesto
ctl-x-map ForcharactersfollowingCONTROL-X
ctl-x-4-map ForcharactersfollowingCONTROL-X4
esc-map ForcharactersfollowingESCAPE(includingMETA
characters)
help-map ForcharactersfollowingCONTROL-H
mode-specific-map ForcharactersfollowingCONTROL-C
Toseethecurrentstateofthekeymaps,typeCONTROL-Hb.Theyappearinthefollowingorder:local,global,andshortermaps
foreachprefixkey.EachlinespecifiesthenameoftheLispfunctiontobecalled;thedocumentationforthatfunctioncanbe
retrievedwiththecommandsCONTROL-Hffunction-nameorCONTROL-Hkkey-sequence.
Themostcommontypeofkeymapcustomizationismakingsmallchangestotheglobalcommandassignmentswithoutcreating
anynewkeymapsorcommands.Thistypeofcustomizationismosteasilydoneinthe.emacsfileusingtheLispfunctiondefine-
key.Thedefine-keyfunctiontakesthreearguments:
Thekeymapname
Asinglecharacterdefiningapositioninthatmap
Thecommandtobeexecutedwhenthischaracterappears
Forinstance,tobindthecommandbackward-kill-wordtoCONTROL-W,usethestatement
(define-keyglobal-map"\C-w"'backward-kill-word)
Tobindthecommandkill-regiontoCONTROL-XCONTROL-K,usethestatement
(define-keyctl-x-map"\C-k"'kill-region)
The\charactercausesC-wtobeinterpretedasCONTROL-Winsteadofthreeletters(equivalentto\^w).Theunmatchedsingle
quotationmarkinfrontofthecommandnameiscorrect.ThisLispescapecharacterkeepsthenamefrombeingevaluatedtoo
soon.
ASAMPLE.emacsFILE
Thefollowing~/.emacsfileproducesaplaineditingenvironmentthatminimizessurprisesforviandvimusers.Ofcourse,ifany
sectionoranylineisinapplicableornottoyourliking,youcanedititoutorcommentitwithoneormore;commentcharacters,
beginningincolumn1.
;;;PreferenceVariables

(setqmake-backup-filesnil);Donotmakebackupfiles
(setqbackup-by-copyingt);Ifyoudo,atleastdonot
destroylinks
(setqdelete-auto-save-filest);Deleteautosavefileswhen
writingorig
(setqblink-matching-parennil);Donotblinkopeningdelim
(setq-defaultcase-fold-searchnil);Donotfoldcasesinsearch
(setqrequire-final-newline'ask);Askaboutmissingfinal
newline
;;ReversemappingsforC-handDEL.
(keyboard-translate?\C-h?\177)
(keyboard-translate?\177?\C-h)
;;reassigningC-wtokeepondeletingwordsbackward
;;C-wissupposedtobekill-region,butit'sagreatburdenfor
vi-trainedfingers.
;;Binditinsteadtobackward-kill-wordformorefamiliar,
friendlybehavior.
(define-keyglobal-map"\^w"'backward-kill-word)
;;forkill-regionuseatwo-keysequencec-xc-k.
(define-keyctl-x-map"\^k"'kill-region)
;;Cmodecustomization:setvanilla(8-spacebsd)indentionstyle
(require'cc-mode);kiss:besureit'shere
(c-add-style;addindentationstyle
"bsd8";oldbsd(8spaces)
'((c-basic-offset.8)

(c-hanging-comment-ender-p.nil);isolated"*/"endsblk
comments
(c-comment-only-line-offset.0)
(c-offsets-alist.((statement-block-intro.+)
(knr-argdecl-intro.+)
(substatement-open.0)
(label.0)
(statement-cont.+)
))
))
(add-hook;thisisourdefaultstyle,
'c-mode-hook;setitalwaysin
c-mode-hook
(function
(lambda()
(c-set-style"bsd8"))))
;;endofcmodestylesetup
MoreInformation
Alotofemacsdocumentationisavailableinbothpaperandelectronicform.TheGNUemacsWeb
pageisagoodplacetostart:www.gnu.org/software/emacs.
Thecomp.emacsandgnu.emacs.helpnewsgroupsoffersupportforandageneraldiscussionabout
emacs.
Accesstoemacs
TheemacseditorisincludedwithmostLinuxdistributions.Youcandownloadandinstallemacswith
Apt(page850)oryum(page848).Youcandownloadthelatestversionofthesourcecodefrom
www.gnu.org.
TheFreeSoftwareFoundationcanbereachedattheseaddresses:
Mail:
FreeSoftwareFoundation,Inc.
59TemplePlace,Suite330
Boston,MA02111-1307,USA
E-mail: gnu@gnu.org
Phone: 1617-542-5942

ChapterSummary
Youcanprecedemanyofthecommandsinthefollowingtableswithanumericargumenttomakethe
commandrepeatthenumberoftimesspecifiedbytheargument.Precedeanumericargumentwith
CONTROL-Utokeepemacsfromenteringtheargumentastext.
Table7-23listscommandsthatmovethecursor.
Table7-23.Movingthecursor
Command Result
CONTROL-F Forwardbycharacters
CONTROL-B Backwardbycharacters
META-f Forwardbywords
META-b Backwardbywords
META-e Toendofsentence
META-a Tobeginningofsentence
META-} Toendofparagraph
META-{ Tobeginningofparagraph
META-> Forwardtoendofbuffer
META-< Backwardtobeginningofbuffer
CONTROL-ESCAPE Toendofline
CONTROL-A Tobeginningofline
CONTROL-N Forward(down)oneline
CONTROL-P Backward(up)oneline
CONTROL-V Scrollforward(down)onewindow
META-v Scrollbackward(up)onewindow
Clearandrepaintscreen,andscrollcurrentlinetocenterof

CONTROL-L window
META-r Tobeginningofmiddleline
CONTROL-UnumMETA-r Tobeginningoflinenumbernum(0=top,=bottom)
Table7-24listscommandsthatkillanddeletetext.
Table7-24.Killinganddeletingtext
Command Result
CONTROL-DELETE Deletescharacterundercursor
DELETE Deletescharactertoleftofcursor
META-d Killsforwardtoendofcurrentword
META-DELETE Killsbackwardtobeginningofpreviousword
META-k Killsforwardtoendofsentence
CONTROL-XDELETE Killsbackwardtobeginningofsentence
CONTROL-K
Killsforwardto,butnotincluding,line-endingLINEFEED;if
thereisnotextbetweenthecursorandtheLINEFEED,kills
theLINEFEED
CONTROL-U1CONTROL-K KillsfromcursorforwardtoandincludingLINEFEED
CONTROL-U0CONTROL-K Killsfromcursorbackwardtobeginningofline
META-zchar Killsforwardto,butnotincluding,nextoccurrenceofchar
META-w CopiesRegiontoKillRing(doesnotdeleteRegionfrom
buffer)
CONTROL-W KillsRegion(deletesRegionfrombuffer)
CONTROL-Y
YanksmostrecentlykilledtextintocurrentbufferatPoint;
setsMarkatbeginningofthistext,withPointandcursorat
theend
META-y Erasesjust-yankedtext,rotatesKillRing,andyanksnextitem
(onlyafterCONTROL-YorMETA-y)

Table7-25listscommandsthatsearchforstringsandregularexpressions.
Table7-25.Searchcommands
Command Result
CONTROL-S Promptsincrementallyforastringandsearchesforward
CONTROL-SRETURN Promptsforacompletestringandsearchesforward
CONTROL-R Promptsincrementallyforastringandsearchesbackward
CONTROL-RRETURN Promptsforacompletestringandsearchesbackward
META-CONTROL-S Promptsincrementallyforaregularexpressionandsearches
forward
META-CONTROL-SRETURN Promptsforacompleteregularexpressionandsearches
forward
META-xisearch-backward-
regexp
Promptsincrementallyforaregularexpressionandsearches
forward
META-xisearch-backward-
regexpRETURN
Promptsforacompleteregularexpressionandsearches
backward
Table7-26listscommandsthatprovideonlinehelp.
Table7-26.Onlinehelp
Command Result
CONTROL-Ha Promptsforstringanddisplaysalistofcommandswhose
namescontainstring
CONTROL-Hb Displaysa(long)tableofallkeybindingsnowineffect
CONTROL-Hckey-sequence Displaysthenameofthecommandboundtokey-sequence
CONTROL-Hkkey-sequence Displaysthenameofanddocumentationforthecommand
boundtokey-sequence
CONTROL-Hf PromptsforthenameofaLispfunctionanddisplaysthe
documentationforthatfunction

CONTROL-Hi(lowercase"i") Displaysthetopmenuofinfo(page32)
CONTROL-Hl(lowercase"l") Displaysthelast100characterstyped
CONTROL-Hm Displaysthedocumentationandspecialkeybindingsforthe
currentMajormode
CONTROL-Hn Displaystheemacsnewsfile
CONTROL-Ht Startsanemacstutorialsession
CONTROL-Hv PromptsforaLispvariablenameanddisplaysthe
documentationforthatvariable
CONTROL-Hw Promptsforacommandnameanddisplaysthekeysequence,
ifany,boundtothatcommand
Table7-27listscommandsthatworkwithaRegion.
Table7-27.WorkingwithaRegion
Command Result
META-W CopiesRegionnondestructivelytotheKillRing
CONTROL-W Kills(deletes)Region
META-xprint-region CopiesRegiontotheprintspooler
META-xappend-to-buffer PromptsforbuffernameandappendsRegiontothatbuffer
META-xappend-to-file PromptsforfilenameandappendsRegiontothatfile
CONTROL-XCONTROL-U ConvertsRegiontouppercase
CONTROL-XCONTROL-L ConvertsRegiontolowercase
Table7-28listscommandsthatworkwithlines.
Table7-28.Workingwithlines
Command Result

META-xoccur
Promptsforaregularexpressionandlistseachlinecontaining
amatchfortheexpressioninabuffernamed*Occur*
META-xdelete-matching-lines PromptsforaregularexpressionanddeleteslinesfromPoint
forwardthathaveamatchfortheregularexpression
META-xdelete-non-matching-
lines
PromptsforaregularexpressionanddeleteslinesfromPoint
forwardthatdonothaveamatchfortheregularexpression
Table7-29listscommandsthatreplacestringsandregularexpressionsunconditionallyandinteractively.
Table7-29.Commandsthatreplacetext
Command Result
META-xreplace-string
Promptsfortwostringsandreplaceseachinstanceofthe
firststringwiththesecondstringfromMarkforward;sets
Markatthestartofthecommand
META-%orMETA-xquery-replace Asabovebutqueriesforeachreplacement(seeTable7-30
foralistofresponses)
META-xreplace-regexp
Promptsforaregularexpressionandastring,andreplaces
eachmatchfortheregularexpressionwiththestring;sets
Markatthestartofthecommand
META-xquery-replace-regexp Asabovebutqueriesforeachreplacement(seeTable7-30
foralistofresponses)
Table7-30.Responsestoreplacementqueries
Command Result
RETURN Quitssearching(doesnotmakeorqueryforanymore
replacements)
SPACE Makesthisreplacementandcontinuesquerying
DELETE Doesnotmakethisreplacementandcontinuesquerying
,(comma) Makesthisreplacement,displaystheresult,andasksfor
anothercommand
.(period) Makesthisreplacementanddoesnotmakeorqueryfor
anymorereplacements

!(exclamationpoint) Replacesthisandallremaininginstanceswithout
querying
Table7-30listsresponsestoreplacementqueries.
Table7-31listscommandsthatworkwithwindows.
Table7-31.Workingwithwindows
Command Result
CONTROL-Xb Promptsforanddisplaysadifferentbufferincurrentwindow
CONTROL-X2 Splitscurrentwindowverticallyintotwo
CONTROL-X3 Splitscurrentwindowhorizontallyintotwo
CONTROL-Xo(lowercase"o") Selectsotherwindow
META-CONTROL-V Scrollsotherwindow
CONTROL-X4b Promptsforbuffernameandselectsitinotherwindow
CONTROL-X4f Promptsforfilenameandselectsitinotherwindow
CONTROL-X0(zero) Deletescurrentwindow
CONTROL-X1(one) Deletesallwindowsexceptcurrentwindow
META-xshrink-window Makescurrentwindowonelineshorter
CONTROL-X^ Makescurrentwindowonelinetaller
CONTROL-X} Makescurrentwindowonecharacterwider
CONTROL-X{ Makescurrentwindowonecharacternarrower
Table7-32listscommandsthatworkwithfiles.
Table7-32.Workingwithfiles

Command Result
CONTROL-XCONTROL-F Promptsforafilenameandreadsitscontentsintoanew
buffer;assignsthefile'ssimplefilenameasthebuffername.
CONTROL-XCONTROL-V Promptsforafilenameandreadsitscontentsintothecurrent
buffer(overwritingthecontentsofthecurrentbuffer).
CONTROL-X4CONTROL-F
Promptsforafilenameandreadsitscontentsintoanew
buffer;assignsthefile'ssimplefilenameasthebuffername.
Createsanewwindowforthenewbufferandselectsthat
window.Thiscommandsplitsthescreeninhalfifyoubegin
withonlyonewindow.
CONTROL-XCONTROL-S Savesthecurrentbuffertotheoriginalfile.
CONTROL-XS Promptsforwhethertosaveeachmodifiedbuffer(y/n).
META-xset-visited-file-name Promptsforafilenameandsetsthecurrentbuffer's"original"
nametothatfilename.
CONTROL-XCONTROL-W Promptsforafilename,setsthecurrentbuffer's"original"
nametothatfilename,andsavesthecurrentbufferinthatfile.
META-~(tilde) Clearsmodifiedflagfromthecurrentbuffer.Usewith
caution.
Table7-33listscommandsthatworkwithbuffers.
Table7-33.Workingwithbuffers
Command Result
CONTROL-XCONTROL-S Savescurrentbufferinitsassociatedfile.
CONTROL-XCONTROL-F Promptsforfilenameandvisits(opens)thatfile.
CONTROL-Xb Promptsforbuffernameandselectsit.Ifthatbufferdoesnot
exist,createsit.
CONTROL-X4b
Promptsforbuffernameanddisplaysthatbufferinanother
window.Theexistingwindowisnotdisturbed,althoughthe
newwindowmayoverlapit.
CONTROL-XCONTROL-B
Createsabuffernamed*BufferList*anddisplaysitin
anotherwindow.Theexistingwindowisnotdisturbed,
althoughthenewwindowmayoverlapit.Thenewbufferis
notselected.Inthe*BufferList*buffer,eachbuffer'sdatais
displayedwithitsname,size,mode(s),andoriginalfilename.

META-xrename-buffer Promptsforanewbuffernameandassignsthisnewnameto
thecurrentbuffer.
CONTROL-XCONTROL-Q Togglesthecurrentbuffer'sreadonlystatusandtheassociated
%%ModeLineindicator.
META-xappend-to-buffer PromptsforbuffernameandappendsRegiontotheendof
thatbuffer.
META-xprepend-to-buffer PromptsforbuffernameandprependsRegiontobeginningof
thatbuffer.
META-xcopy-to-buffer Promptsforbuffername,deletescontentsofthatbuffer,and
copiestheRegiontothatbuffer.
META-xinsert-buffer Promptsforbuffernameandinsertsentirecontentsofthat
bufferincurrentbufferatPoint.
CONTROL-Xk Promptsforbuffernameanddeletesthatbuffer.
META-xkill-some-buffers Goesthroughtheentirebufferlistandoffersthechanceto
deleteeachbuffer.
Table7-34listscommandsthatrunshellcommandsintheforeground.Thesecommandsmaynotwork
withallshells.
Table7-34.Foregroundshellcommands
Command Result
META-!(exclamationpoint) Promptsforshellcommand,executesit,anddisplaysthe
output
CONTROL-UMETA-!
(exclamationpoint)
Promptsforshellcommand,executesit,andinsertsthe
outputatPoint
META-|(verticalbar) Promptsforshellcommand,suppliesRegionasinputtothat
command,anddisplaysoutputofcommand
CONTROL-UMETA-|(vertical
bar)
Promptsforshellcommand,suppliesRegionasinputtothat
command,deletesoldRegion,andinsertsoutputofcommand
inplaceofRegion
Table7-35listscommandsthatrunshellcommandsinthebackground.

Table7-35.Backgroundshellcommands
Command Result
META-xcompile
Promptsforshellcommandandrunsthatcommandinthe
background,withoutputgoingtothebuffernamed
*compilation*
META-xkill-compilation Killsbackgroundprocess
Table7-36listscommandsthatconverttextfromuppercasetolowercaseandviceversa.
Table7-36.Caseconversioncommands
Command Result
META-l(lowercase"l") ConvertswordtorightofPointtolowercase
META-u ConvertswordtorightofPointtouppercase
META-c ConvertswordtorightofPointtoinitialcaps
CONTROL-XCONTROL-L ConvertsRegiontolowercase
CONTROL-XCONTROL-U ConvertsRegiontouppercase
Table7-37listscommandsthatworkinCmode.
Table7-37.Cmodecommands
Command Result
CONTROL-META-f Movesforwardoverexpression
CONTROL-META-b Movesbackwardoverexpression
CONTROL-META-k Movesforwardoverexpressionandkillsit
CONTROL-META-@ SetsMarkatthepositionCONTROL-META-fwouldmoveto,
withoutchangingPoint
CONTROL-META-a Movestobeginningofthemostrecentfunctiondefinition

CONTROL-META-e Movestotheendofthenextfunctiondefinition
CONTROL-META-h MovesPointtobeginningandMarktoendofcurrent(ornext,
ifbetween)functiondefinition
TypeMETA-xshelltocreateabuffernamed*shell*andstartasubshell.Table7-38listscommandsthat
workonthisbuffer.
Table7-38.Shellmodecommands
Command Result
RETURN Sendscurrentlinetotheshell
CONTROL-CCONTROL-D SendsCONTROL-Dtoshelloritssubshell
CONTROL-CCONTROL-C SendsCONTROL-Ctoshelloritssubshell
CONTROL-CCONTROL-\ Sendsquitsignaltoshelloritssubshell
CONTROL-CCONTROL-U Killstextonthecurrentlinenotyetcompleted
CONTROL-CCONTROL-R Scrollsbacktobeginningoflastshelloutput,puttingfirst
lineofoutputatthetopofthewindow
CONTROL-CCONTROL-O
(uppercase"O") Deleteslastbatchofshelloutput
Exercises
1.
GivenabufferfullofEnglishtext,answerthefollowingquestions:
1. Howwouldyouchangeeveryinstanceofhistohers?
2. Howwouldyoudothisonlyinthefinalparagraph?
3. Isthereawaytolookateveryusageincontextbeforechangingit?
4. HowwouldyoudealwiththepossibilitythatHismightbeginasentence?
2. Whichcommandmovesthecursortotheendofthecurrentparagraph?Canyouusethiscommandtoskipthroughthebufferinone-
paragraphsteps?
3.
Supposethatyougetlostinthemiddleoftypingalongsentence.
1. Isthereaneasywaytokillthebotchedsentenceandstartover?
2. Whatifonlyonewordisincorrect?Isthereanalternativetobackspacingoneletteratatime?
4. Afteryouhavebeenworkingonaparagraphforawhile,mostlikelysomelineswillhavebecometooshortandotherstoolong.Isthere
acommandto"neatenup"theparagraphwithoutrebreakingallthelinesbyhand?
5. Isthereawaytochangetheentirecontentsofthebuffertocapitalletters?Canyouthinkofawaytochangejustoneparagraph?
6. Howwouldyoureversetheorderoftwoparagraphs?
7. Howwouldyoureversetwowords?
8.
ImaginethatyousawaUsenetpostingwithsomethingparticularlyfunnyinitandsavedthepostingtoafile.Howwouldyou
incorporatethisfileintoyourownbuffer?Whatifyouwantedonlyacoupleofparagraphs?Howwouldyouadd>tothebeginningof
eachincludedline?
Onthekeyboardaloneemacshasalwaysofferedafullsetofeditingpossibilities.Generallyseveraltechniqueswillaccomplishthesame
goalforanyeditingtask.IntheXenvironmentthechoiceisenlargedstillfurtherwithanewgroupofmouse-orientedvisualalternatives.
Fromtheseoptionsyoumustselectthewaythatyouliketosolveagiveneditingpuzzlebest.
ConsiderthisShakespeareanfragment:
1.Fullfathomfivethyfatherlies;
2.Ofhisbonesarecoralmade;
3.Thosearepearlsthatwerehiseyes:
4.Nothingofhimthatdothfade,
5.Butdothsufferasea-change
6.Intosomethingrichandstrange.
7.Sea-nymphshourlyringhisknell:
8.Ding-dong.
9.
9.Hark!nowIhearthem--
10.Ding-dong,bell!
Thefollowingfragmenthasbeentypedwithsomeerrors:
1.Fullfathiomfivetyyfatherlies;
2.Thesearepearlsthatwerehiseyes:
3.Ofhisbonesarecoralmade;
4.Nothinofhimthatdothfade,
5.Butdothsusfferasea-change
6.Intosomethingrichandstrange.
7.Sea-nymphshourlyringhisknell:
8.Ding=dong.
9.Hard!nowIhearthem--
10.Ding-dong,bell!
Useonlythekeyboardtoanswerthefollowing:
1. Howmanywayscanyouthinkoftomovethecursortothespellingerrors?
2. Oncethecursorisonorneartheerrors,howmanywayscanyouthinkoftofixthem?
3. Aretherewaystofixerrorswithoutexplicitlynavigatingto/searchingforthem?Howmanycanyouthinkof?
4. Lines2and3aretransposed.Howmanywayscanyouthinkoftocorrectthissituation?

AdvancedExercises
10.
AssumethatyourbuffercontainstheCcodeshownhere,withtheMajormodesetforCandthecursorpositionedattheendofthe
whilelineasshownbytheblacksquare:
/*
*Copystrings2tos1.s1mustbelargeenough
*returns1
*/
char*
strcpy(s1,s2)
registerchar*s1,*s2;
{
registerchar*os1;
os1=s1;
while(*s1++=*s2++)
;
return(os1);
}
/*Copysourceintodest,stoppingafter'\0'iscopied,and
returnapointertothe'\0'attheendofdest.Thenourcaller
canconcatenatetothedeststringwit_outanotherstrlencall.*/
char*
stpcpy(dest,source)
char*dest;
char*source;
{
while((*dest++=*source++)!='\0')
;/*voidloopbody*/
return(dest-1);
}
1. Whichcommandmovesthecursortotheopeningbraceofstrcpy?Whichcommandmovesthecursorpasttheclosingbrace?
Canyouusethesecommandstoskipthroughthebufferinone-proceduresteps?
2. Assumethecursorisjustpasttheclosingparenthesisofthewhilecondition.Howdoyoumovetothematchingopening
parenthesis?Howdoyoumovebacktothematchingcloseparenthesisagain?Doesthesamecommandsetworkformatched[]
and{}?Howdoesthisdifferfromthevim%command?
3. OneprocedureisindentedintheBerkeleyindentionstyle;theotherisindentedintheGNUstyle.Whichcommandreindentsaline
inaccordancewiththecurrentindentionstyleyouhavesetup?Howwouldyoureindentanentireprocedure?
4. Supposethatyouwanttowritefivestringproceduresandintendtousestrcpyasastartingpointforfurtherediting.Howwould
youmakefivecopiesofthestrcpyprocedure?
5. Howwouldyoucompilethecodewithoutleavingemacs?
Chapter8.TheBourneAgainShell
INTHISCHAPTER
StartupFiles257
RedirectingStandardError260
WritingaSimpleShellScript263
JobControl271
ManipulatingtheDirectoryStack274
ParametersandVariables277
Processes292
History295
ReexecutingandEditingCommands297
Aliases312
Functions315
ControllingbashFeaturesandOptions318
ProcessingtheCommandLine322
ThischapterpicksupwhereChapter5leftoffbyfocusingontheBourneAgainShell(bash).Itnotes
wheretcshimplementationofafeaturediffersfromthatofbash;ifappropriate,youaredirectedtothe
pagewherethealternativeimplementationisdiscussed.Chapter11expandsonthischapter,exploring
controlflowcommandsandmoreadvancedaspectsofprogrammingtheBourneAgainShell.Thebash
homepageiswww.gnu.org/software/bash.ThebashinfopageisacompleteBourneAgainShell
reference.
TheBourneAgainShellandTCShell(tcsh)arecommandinterpretersandhigh-levelprogramming
languages.Ascommandinterpreters,theyprocesscommandsyouenteronthecommandlineinresponse
toaprompt.Whenyouusetheshellasaprogramminglanguage,itprocessescommandsstoredinfiles
calledshellscripts.Likeotherlanguages,shellshavevariablesandcontrolflowcommands(for
example,forloopsandifstatements).
Whenyouuseashellasacommandinterpreter,youcancustomizetheenvironmentyouworkin.Youcan
makeyourpromptdisplaythenameoftheworkingdirectory,createafunctionoraliasforcpthatkeepsit
fromoverwritingcertainkindsoffiles,takeadvantageofkeywordvariablestochangeaspectsofhowthe
shellworks,andsoon.Youcanalsowriteshellscriptsthatdoyourbidding,fromaone-linescriptthat
storesalong,complexcommandtoalongerscriptthatrunsasetofreports,printsthem,andmailsyoua
reminderwhenthejobisdone.Morecomplexshellscriptsarethemselvesprograms;theydonotjustrun
otherprograms.Chapter11hassomeexamplesofthesetypesofscripts.
MostsystemshellscriptsarewrittentorunundertheBourneAgainShell.Ifyouwilleverworkinsingle-
usermodeaswhenyoubootyoursystemordosystemmaintenance,administration,orrepairwork,for
exampleitisagoodideatobecomefamiliarwiththisshell.
ThischapterexpandsontheinteractivefeaturesoftheshelldescribedinChapter5,explainshowto
createandrunsimpleshellscripts,discussesjobcontrol,introducesthebasicaspectsofshell
programming,talksabouthistoryandaliases,anddescribescommandlineexpansion.Chapter9covers
interactiveuseoftheTCShellandTCShellprogramming,andChapter11presentssomemore
challengingshellprogrammingproblems.
Background
TheBourneAgainShellisbasedontheBourneShell(theearlyUNIXshell;thisbookreferstoitasthe
originalBourneShelltoavoidconfusion),whichwaswrittenbySteveBourneofAT&T'sBell
Laboratories.OvertheyearstheoriginalBourneShellhasbeenexpandedbutitremainsthebasicshell
providedwithmanycommercialversionsofUNIX.
shShell
Becauseofitslongandsuccessfulhistory,theoriginalBourneShellhasbeenusedtowritemanyofthe
shellscriptsthathelpmanageUNIXsystems.SomeofthesescriptsappearinLinuxasBourneAgain
Shellscripts.AlthoughtheBourneAgainShellincludesmanyextensionsandfeaturesnotfoundinthe
originalBourneShell,bashmaintainscompatibilitywiththeoriginalBourneShellsoyoucanrun
BourneShellscriptsunderbash.OnUNIXsystemstheoriginalBourneShellisnamedsh.OnLinux
systemsshisasymboliclinktobashensuringthatscriptsthatrequirethepresenceoftheBourneShell
stillrun.Whencalledassh,bashdoesitsbesttoemulatetheoriginalBourneShell.
KornShell
SystemVUNIXintroducedtheKornShell(ksh),writtenbyDavidKorn.Thisshellextendedmany
featuresoftheoriginalBourneShellandaddedmanynewfeatures.SomefeaturesoftheBourneAgain
Shell,suchascommandaliasesandcommandlineediting,arebasedonsimilarfeaturesfromtheKorn
Shell.
POSIXstandards
ThePOSIX(thePortableOperatingSystemInterface)familyofrelatedstandardsisbeingdevelopedby
PASC(IEEE'sPortableApplicationStandardsCommittee,www.pasc.org).AcomprehensiveFAQon
POSIX,includingmanylinks,appearsatwww.opengroup.org/austin/papers/posix_faq.html.
POSIXstandard1003.2describesshellfunctionality.TheBourneAgainShellprovidesthefeaturesthat
matchtherequirementsofthisPOSIXstandard.EffortsareunderwaytomaketheBourneAgainShell
fullycomplywiththePOSIXstandard.Inthemeantime,ifyouinvokebashwiththeposixoption,the
behavioroftheBourneAgainShellwillmorecloselymatchthePOSIXrequirements.
ShellBasics
Thissectioncoverswritingandusingstartupfiles,redirectingstandarderror,writingandexecuting
simpleshellscripts,separatingandgroupingcommands,implementingjobcontrol,andmanipulatingthe
directorystack.
StartupFiles
Whenashellstarts,itrunsstartupfilestoinitializeitself.Whichfilestheshellrunsdependsonwhetherit
isaloginshell,aninteractiveshellthatisnotaloginshell(suchasyougetbygivingthecommandbash),
oranoninteractiveshell(oneusedtoexecuteashellscript).Youmusthavereadaccesstoastartupfileto
executethecommandsinit.TypicallyLinuxdistributionsputappropriatecommandsinsomeofthese
files.Thissectioncoversbashstartupfiles.Seepage342forinformationontcshstartupfiles.
LoginShells
Thefilescoveredinthissectionareexecutedbyloginshellsandshellsthatyoustartwiththelogin
option.Loginshellsare,bytheirnature,interactive.
/etc/profile
Theshellfirstexecutesthecommandsin/etc/profile.Superusercansetupthisfiletoestablish
systemwidedefaultcharacteristicsforbashusers.
.bash_profile.bash_login.profile
Nexttheshelllooksfor~/.bash_profile,~/.bash_login,and~/.profile(~/isshorthandforyourhome
directory),inthatorder,executingthecommandsinthefirstofthesefilesitfinds.Youcanputcommands
inoneofthesefilestooverridethedefaultssetin/etc/profile.
.bash_logout
Whenyoulogout,bashexecutescommandsinthe~/.bash_logoutfile.Frequentlycommandsthatclean
upafterasession,suchasthosethatremovetemporaryfiles,gointhisfile.
InteractiveNonloginShells
Thecommandsintheprecedingstartupfilesarenotexecutedbyinteractive,nonloginshells.However,
theseshellsinheritfromtheloginshellvariablesthataresetbythesestartupfiles.
/etc/bashrc
Althoughnotcalledbybashdirectly,many~/.bashrcfilescall/etc/bashrc.ThissetupallowsSuperuser
toestablishsystemwidedefaultcharacteristicsfornonloginbashshells.
.bashrc
Aninteractivenonloginshellexecutescommandsinthe~/.bashrcfile.Typicallyastartupfileforalogin
shell,suchas.bash_profile,runsthisfile,sothatbothloginandnonloginshellsbenefitfromthe
commandsin.bashrc.
NoninteractiveShells
Thecommandsinthepreviouslydescribedstartupfilesarenotexecutedbynoninteractiveshells,suchas
thosethatrunsshellscripts.However,theseshellsinheritfromtheloginshellvariablesthataresetby
thesestartupfiles.
BASH_ENV
NoninteractiveshellslookfortheenvironmentvariableBASH_ENV(orENV,iftheshelliscalledas
sh)andexecutecommandsinthefilenamedbythisvariable.
SettingUpStartupFiles
Althoughmanystartupfilesandtypesofshellsexist,usuallyallyouneedarethe.bash_profileand
.bashrcfilesinyourhomedirectory.Commandssimilartothefollowingin.bash_profileruncommands
from.bashrcforloginshells(when.bashrcexists).Withthissetup,thecommandsin.bashrcare
executedbyloginandnonloginshells.
if[-f~/.bashrc];thensource~/.bashrc;fi
The[f~/.bashrc]testswhetherthefilenamed.bashrcinyourhomedirectoryexists.Seepage794for
moreinformationontestanditssynonym[].
tip:Use.bash_profiletosetPATH
Becausecommandsin.bashrcmaybeexecutedmanytimes,andbecausesubshellsinherit
exportedvariables,itisagoodideatoputcommandsthataddtoexistingvariablesinthe
.bash_profilefile.Forexample,thefollowingcommandaddsthebinsubdirectoryofthe
homedirectorytoPATH(page284)andshouldgoin.bash_profile:
PATH=$PATH:$HOME/bin
Whenyouputthiscommandin.bash_profileandnotin.bashrc,thestringisaddedtothe
PATHvariableonlyonce,whenyoulogin.
Modifyingavariablein.bash_profileallowschangesyoumakeinaninteractivesessionto
propagatetosubshells.Incontrast,modifyingavariablein.bashrcoverrideschanges
inheritedfromaparentshell.
Sample.bash_profileand.bashrcfilesfollow.Someofthecommandsusedinthesefilesarenotcovered
untillaterinthischapter.Inanystartupfile,youmustexportvariablesandfunctionsthatyouwanttobe
availabletochildprocesses.Formoreinformationreferto"LocalityofVariables"onpage475.
$cat~/.bash_profile
if[-f~/.bashrc];then
source~/.bashrc#readlocalstartupfileifit
exists
fi
PATH=$PATH:.#addtheworkingdirectoryto
PATH
exportPS1='[\h\W\!]\$'#setprompt
Thefirstcommandinthepreceding.bash_profilefileexecutesthecommandsintheuser's.bashrcfileif
itexists.ThenextcommandaddstothePATHvariable(page284).TypicallyPATHissetandexported
in/etc/profilesoitdoesnotneedtobeexportedinauser'sstartupfile.Thefinalcommandsetsand
exportsPS1(page286),whichcontrolstheuser'sprompt.
Nextisasample.bashrcfile.Thefirstcommandexecutesthecommandsinthe/etc/bashrcfileifit
exists.NexttheLANG(page290)andVIMINIT(page176)variablesaresetandexportedandseveral
aliases(page312)areestablished.Thefinalcommanddefinesafunction(page315)thatswapsthenames
oftwofiles.
$cat~/.bashrc
if[-f/etc/bashrc];then
source/etc/bashrc#readglobalstartupfileifit
exists
fi
set-onoclobber#preventoverwritingfiles
unsetMAILCHECK#turnoff"youhavenewmail"notice
exportLANG=C#setLANGvariable
exportVIMINIT='setaiaw'#setvimoptions
aliasdf='df-h'#setupaliases
aliasrm='rm-i'#alwaysdointeractiverm's
aliaslt='ls-ltrh|tail'
aliash='history|tail'
aliasch='chmod755'
functionswitch()#afunctiontoexchangethenames
{#oftwofiles
localtmp=$$switch
mv"$1"$tmp
mv"$2""$1"
mv$tmp"$2"
}
.(Dot)ORsource:RunsaStartupFileintheCurrentShell
Afteryoueditastartupfilesuchas.bashrc,youdonothavetologoutandloginagaintoputthechanges
intoeffect.Youcanrunthestartupfileusingthe.(dot)orsourcebuiltin(theyarethesamecommand
underbash;onlysourceisavailableundertcsh[page380]).Aswithallothercommands,the.must
befollowedbyaSPACEonthecommandline.Usingthe.orsourcebuiltinissimilartorunningashell
script,exceptthatthesecommandsrunthescriptaspartofthecurrentprocess.Consequently,whenyou
use.orsourcetorunascript,changesyoumaketovariablesfromwithinthescriptaffecttheshellthat
yourunthescriptfrom.Youcanusethe.orsourcecommandtorunanyshellscriptnotjustastartup
filebutundesirablesideeffects(suchaschangesinthevaluesofshellvariablesyourelyon)mayoccur.If
youranastartupfileasaregularshellscriptanddidnotusethe.orsourcebuiltin,thevariables
createdinthestartupfilewouldremainineffectonlyinthesubshellrunningthescriptnotintheshellyou
ranthescriptfrom.Formoreinformationreferto"LocalityofVariables"onpage475.
Inthefollowingexample,.bashrcsetsseveralvariablesandsetsPS1,theprompt,tothenameofthehost.
The.builtinputsthenewvaluesintoeffect.
$cat~/.bashrc
exportTERM=vt100#settheterminaltype
exportPS1="$(hostname-f):"#setthepromptstring
exportCDPATH=:$HOME#addHOMEtoCDPATHstring
sttykill'^u'#setkilllinetocontrol-u
$.~/.bashrc

bravo.example.com:
CommandsThatAreSymbols
TheBourneAgainShellusesthesymbols(,),[,],and$inavarietyofways.Tominimizeconfusion,
Table8-1liststhemostcommonuseofeachofthesesymbols,eventhoughsomeofthemarenot
introduceduntillater.
Table8-1.Builtincommandsthataresymbols
Symbol Command
() Subshell(page270)
$() Commandsubstitution(page329)
(()) Arithmeticevaluation;asynonymforlet(usewhentheenclosedvalue
containsanequalsign)(page501)
$(()) Arithmeticexpansion(notforusewithanenclosedequalsign)(page327)
[] Thetestcommand.(pages437,440,453,and794)
[[]] Conditionalexpression;similarto[]butaddsstringcomparisons(page
503)
RedirectingStandardError
Chapter5coveredtheconceptofstandardoutputandexplainedhowtoredirectstandardoutputofa
command.Inadditiontostandardoutput,commandscansendoutputtostandarderror.Acommandcan
senderrormessagestostandarderrortokeepthemfromgettingmixedupwiththeinformationitsendsto
standardoutput.
Justasitdoeswithstandardoutput,bydefaulttheshellsendsacommand'sstandarderrortothescreen.
Unlessyouredirectoneortheother,youmaynotknowthedifferencebetweentheoutputacommand
sendstostandardoutputandtheoutputitsendstostandarderror.Thissectioncoversthesyntaxusedby
theBourneAgainShell.Seepage349ifyouareusingtheTCShell.
Filedescriptors
Afiledescriptoristheplaceaprogramsendsitsoutputtoandgetsitsinputfrom.Whenyouexecutea
program,theprocessrunningtheprogramopensthreefiledescriptors:0(standardinput),1(standard
output),and2(standarderror).Theredirectoutputsymbol(>[page116])isshorthandfor1>,whichtells
theshelltoredirectstandardoutput.Similarly<(page118)isshortfor0<,whichredirectsstandard
input.Thesymbols2>redirectstandarderror.Formoreinformationreferto"FileDescriptors"onpage
470.
Thefollowingexamplesdemonstratehowtoredirectstandardoutputandstandarderrortodifferentfiles
andtothesamefile.Whenyourunthecatutilitywiththenameofafilethatdoesnotexistandthename
ofafilethatdoesexist,catsendsanerrormessagetostandarderrorandcopiesthefilethatdoesexist
tostandardoutput.Unlessyouredirectthem,bothmessagesappearonthescreen.
$caty
Thisisy.
$catx
cat:x:Nosuchfileordirectory
$catxy
cat:x:Nosuchfileordirectory
Thisisy.
Whenyouredirectstandardoutputofacommand,outputsenttostandarderrorisnotaffectedandstill
appearsonthescreen.
$catxy>hold
cat:x:Nosuchfileordirectory
$cathold
Thisisy.
Similarly,whenyousendstandardoutputthroughapipe,standarderrorisnotaffected.Thefollowing
examplesendsstandardoutputofcatthroughapipetotr(page804),whichinthisexampleconverts
lowercasecharacterstouppercase.Thetextthatcatsendstostandarderrorisnottranslatedbecauseit
goesdirectlytothescreenratherthanthroughthepipe.
$catxy|tr"[a-z]""[A-Z]"
cat:x:Nosuchfileordirectory
THISISY.
Thefollowingexampleredirectsstandardoutputandstandarderrortodifferentfiles.Thenotation2>
tellstheshellwheretoredirectstandarderror(filedescriptor2).The1>tellstheshellwheretoredirect
standardoutput(filedescriptor1).Youcanuse>inplaceof1>.
$catxy1>hold12>hold2
$cathold1
Thisisy.
$cathold2
cat:x:Nosuchfileordirectory
Duplicatingafiledescriptor
Inthenextexample,1>redirectsstandardoutputtohold.Then2>&1declaresfiledescriptor2tobea
duplicateoffiledescriptor1.Asaresultbothstandardoutputandstandarderrorareredirectedtohold.
$catxy1>hold2>&1
$cathold
cat:x:Nosuchfileordirectory
Thisisy.
Intheprecedingexample,1>holdprecedes2>&1.Iftheyhadbeenlistedintheoppositeorder,standard
errorwouldhavebeenmadeaduplicateofstandardoutputbeforestandardoutputwasredirectedtohold.
Inthatcaseonlystandardoutputwouldhavebeenredirectedtohold.
Thenextexampledeclaresfiledescriptor2tobeaduplicateoffiledescriptor1andsendstheoutputfor
filedescriptor1throughapipetothetrcommand.
$catxy2>&1|tr"[a-z]""[A-Z]"
CAT:X:NOSUCHFILEORDIRECTORY
THISISY.
Sendingerrorstostandarderror
Youcanalsouse1>&2toredirectstandardoutputofacommandtostandarderror.Thistechniqueisoften
usedinshellscriptstosendtheoutputofechotostandarderror.Inthefollowingscript,standardoutput
ofthefirstechoisredirectedtostandarderror:
$catmessage_demo
echoThisisanerrormessage.1>&2
echoThisisnotanerrormessage.
Ifyouredirectstandardoutputofmessage_demo,errormessagessuchastheoneproducedbythefirst
echowillstillgotothescreenbecauseyouhavenotredirectedstandarderror.Becausestandardoutput
ofashellscriptisfrequentlyredirectedtoanotherfile,youcanusethistechniquetodisplayonthescreen

errormessagesgeneratedbythescript.Thelnksscript(page445)usesthistechnique.Youcanalsouse
theexecbuiltintocreateadditionalfiledescriptorsandtoredirectstandardinput,standardoutput,and
standarderrorofashellscriptfromwithinthescript(page491).
TheBourneAgainShellsupportstheredirectionoperatorsshowninTable8-2.
Table8-2.Redirectionoperators
Operator Meaning
<filename Redirectsstandardinputfromfilename.
>filename
Redirectsstandardoutputtofilenameunlessfilenameexistsand
noclobber(page119)isset.Ifnoclobberisnotset,thisredirectioncreates
filenameifitdoesnotexist.
>|filename Redirectsstandardoutputtofilename,evenifthefileexistsandnoclobber
(page119)isset.
>>filename
Redirectsandappendsstandardoutputtofilenameunlessfilenameexists
andnoclobber(page119)isset.Ifnoclobberisnotset,thisredirection
createsfilenameifitdoesnotexist.
<&mDuplicatesstandardinputfromfiledescriptorm(page471).
[n]>&m Duplicatesstandardoutputorfiledescriptornifspecifiedfromfile
descriptorm(page471).
[n]<&Closesstandardinputorfiledescriptornifspecified(page471).
[n]>& Closesstandardoutputorfiledescriptornifspecified.
WritingaSimpleShellScript
Ashellscriptisafilethatcontainscommandsthattheshellcanexecute.Thecommandsinashellscript
canbeanycommandsyoucanenterinresponsetoashellprompt.Forexample,acommandinashell
scriptmightrunaLinuxutility,acompiledprogram,oranothershellscript.Likethecommandsyougive
onthecommandline,acommandinashellscriptcanuseambiguousfilereferencesandcanhaveitsinput
oroutputredirectedfromortoafileorsentthroughapipe(page122).Youcanalsousepipesand
redirectionwiththeinputandoutputofthescriptitself.
Inadditiontothecommandsyouwouldordinarilyuseonthecommandline,controlflowcommands(also
calledcontrolstructures)findmostoftheiruseinshellscripts.Thisgroupofcommandsenablesyouto
altertheorderofexecutionofcommandsinascriptjustasyouwouldaltertheorderofexecutionof
statementsusingastructuredprogramminglanguage.Referto"ControlStructures"onpage436(bash)
andpage368(tcsh)forspecifics.
Theshellinterpretsandexecutesthecommandsinashellscript,oneafteranother.Thusashellscript
enablesyoutosimplyandquicklyinitiateacomplexseriesoftasksorarepetitiveprocedure.
chmod:MakesaFileExecutable
Toexecuteashellscriptbygivingitsnameasacommand,youmusthavepermissiontoreadandexecute
thefilethatcontainsthescript(referto"AccessPermissions"onpage91).Readpermissionenablesyou
toreadthefilethatholdsthescript.Executepermissiontellstheshellandthesystemthattheowner,
group,and/orpublichaspermissiontoexecutethefile;itimpliesthatthecontentofthefileisexecutable.
Whenyoucreateashellscriptusinganeditor,thefiledoesnottypicallyhaveitsexecutepermissionset.
Thefollowingexampleshowsafilenamedwhosonthatcontainsashellscript:
$catwhoson
date
echo"UsersCurrentlyLoggedIn"
who
$whoson
bash:./whoson:Permissiondenied
Youcannotexecutewhosonbygivingitsnameasacommandbecauseyoudonothaveexecutepermission
forthefile.Theshelldoesnotrecognizewhosonasanexecutablefileandissuesanerrormessagewhen
youtrytoexecuteit.Whenyougivethefilenameasanargumenttobash(bashwhoson),bashtakesthe
argumenttobeashellscriptandexecutesit.Inthiscasebashisexecutableandwhosonisanargument
thatbashexecutessoyoudonotneedtohavepermissiontoexecutewhoson.Youcandothesamewith
tcshscriptfiles.
tip:Commandnotfound?
Ifyougetthemessage

$whoson
bash:whoson:commandnotfound
theshellisnotsetuptosearchforexecutablefilesintheworkingdirectory.Givethis
commandinstead:
$./whoson
The./tellstheshellexplicitlytolookforanexecutablefileintheworkingdirectory.To
changetheenvironmentsothattheshellsearchestheworkingdirectoryautomatically,see
page284.
Thechmodutilitychangestheaccessprivilegesassociatedwithafile.Figure8-1showslswiththel
optiondisplayingtheaccessprivilegesofwhosonbeforeandafterchmodgivesexecutepermissionto
thefile'sowner.
Figure8-1.Usingchmodtomakeashellscriptexecutable
Thefirstlsdisplaysahyphen()asthefourthcharacter,indicatingthattheownerdoesnothave
permissiontoexecutethefile.Nextchmodgivestheownerexecutepermission:Theu+xcauseschmod
toadd(+)executepermission(x)fortheowner(u).(Theustandsforuser,althoughitmeanstheownerof
thefilewhomaybetheuserofthefileatanygiventime.)Thesecondargumentisthenameofthefile.
Thesecondlsshowsanxinthefourthposition,indicatingthattheownernowhasexecutepermission.
Ifotheruserswillexecutethefile,youmustalsochangegroupand/orpublicaccesspermissionsforthe
file.Anyusermusthaveexecuteaccesstousethefile'snameasacommand.Ifthefileisashellscript,
theusertryingtoexecutethefilemustalsohavereadaccesstothefile.Youdonotneedreadaccessto
executeabinaryexecutable(compiledprogram).
ThefinalcommandinFigure8-1showstheshellexecutingthefilewhenitsnameisgivenasacommand.
Formoreinformationreferto"AccessPermissions"onpage91andtolsandchmodinPartV.
#!SpecifiesaShell
Youcanputaspecialsequenceofcharactersonthefirstlineofafiletotelltheoperatingsystemwhich
shellshouldexecutethefile.Becausetheoperatingsystemcheckstheinitialcharactersofaprogram
beforeattemptingtoexecit,thesecharacterssavethesystemfrommakinganunsuccessfulattempt.If#!
arethefirsttwocharactersofascript,thesysteminterpretsthecharactersthatfollowastheabsolute
pathnameoftheutilitythatshouldexecutethescript.Thiscanbethepathnameofanyprogram,notjusta
shell.Thefollowingexamplespecifiesthatbashshouldrunthescript:
$catbash_script
#!/bin/bash
echo"ThisisaBourneAgainShellscript."
The#!charactersareusefulifyouhaveascriptthatyouwanttorunwithashellotherthantheshellyou
arerunningthescriptfrom.Thefollowingexampleshowsascriptthatshouldbeexecutedbytcsh:
$cattcsh_script
#!/bin/tcsh
echo"Thisisatcshscript."
setperson=jenny
echo"personis$person"
Becauseofthe#!line,theoperatingsystemensuresthattcshexecutesthescriptnomatterwhichshell
yourunitfrom.
Youcanusepsfwithinashellscripttodisplaythenameoftheshellthatisexecutingthescript.Thethree
linesthatpsdisplaysinthefollowingexampleshowtheprocessrunningtheparentbashshell,the
processrunningthetcshscript,andtheprocessrunningthepscommand:
$cattcsh_script2
#!/bin/tcsh
ps-f
$tcsh_script2
UIDPIDPPIDCSTIMETTYTIMECMD
alex303130300Nov16pts/400:00:00-bash
alex93583031021:13pts/400:00:00/bin/tcsh
./tcsh_script2
alex93759358021:13pts/400:00:00ps-f
Ifyoudonotfollow#!withthenameofanexecutableprogram,theshellreportsthatitcannotfindthe
commandthatyouaskedittorun.Youcanoptionallyfollow#!withSPACEs.Ifyouomitthe#!lineand
trytorun,forexample,atcshscriptfrombash,theshellmaygenerateerrormessagesorthescript
maynotrunproperly.
Seepage576foranexampleofastand-alonesedscriptthatuses#!.
#BeginsAComment
Commentsmakeshellscriptsandallcodeeasiertoreadandmaintainbyyouandothers.Thecomment
syntaxiscommontoboththeBourneAgainandtheTCShells.
Ifapoundsign(#)inthefirstcharacterpositionofthefirstlineofascriptisnotimmediatelyfollowedby
anexclamationpoint(!)orifapoundsignoccursinanyotherlocationinascript,theshellinterpretsitas
thebeginningofacomment.Theshellthenignoreseverythingbetweenthepoundsignandtheendofthe
line(thenextNEWLINEcharacter).
RunningAShellScript
forkandexecsystemcalls
Acommandonthecommandlinecausestheshelltoforkanewprocess,creatingaduplicateoftheshell
process(asubshell).Thenewprocessattemptstoexec(execute)thecommand.Likefork,theexec
routineisexecutedbytheoperatingsystem(asystemcall).Ifthecommandisabinaryexecutable
program,suchasacompiledCprogram,execsucceedsandthesystemoverlaysthenewlycreated
subshellwiththeexecutableprogram.Ifthecommandisashellscript,execfails.Whenexecfails,the
commandisassumedtobeashellscript,andthesubshellrunsthecommandsinthescript.Unlikealogin
shell,whichexpectsinputfromthecommandline,thesubshelltakesitsinputfromafile:theshellscript.
Asdiscussedearlier,ifyouhaveashellscriptinafilethatyoudonothaveexecutepermissionfor,you
canrunthecommandsinthescriptbyusingabashcommandtoexecashelltorunthescriptdirectly.In
thefollowingexample,bashcreatesanewshellthattakesitsinputfromthefilenamedwhoson:
$bashwhoson
Becausethebashcommandexpectstoreadafilecontainingcommands,youdonotneedexecute
permissionforwhoson.(Youdoneedreadpermission.)Eventhoughbashreadsandexecutesthe
commandsinwhoson,standardinput,standardoutput,andstandarderrorremainconnectedtothe
terminal.
Althoughyoucanusebashtoexecuteashellscript,thistechniquecausesthescripttorunmoreslowly
thangivingyourselfexecutepermissionanddirectlyinvokingthescript.Userstypicallyprefertomake
thefileexecutableandrunthescriptbytypingitsnameonthecommandline.Itisalsoeasiertotypethe
name,andthispracticeisconsistentwiththewayotherkindsofprogramsareinvoked(soyoudonot
needtoknowwhetheryouarerunningashellscriptoranotherkindofprogram).However,ifbashisnot
yourinteractiveshellorifyouwanttoseehowthescriptrunswithdifferentshells,youmaywanttoruna
scriptasanargumenttobashortcsh.
caution:shdoesnotcalltheoriginalBourneShell
TheoriginalBourneShellwasinvokedwiththecommandsh.Althoughyoucancallbash
withanshcommand,itisnottheoriginalBourneShell.Theshcommand(/bin/sh)isa
symboliclinkto/bin/bash,soitissimplyanothernameforthebashcommand.Whenyou
callbashusingthecommandsh,bashtriestomimicthebehavioroftheoriginalBourne
Shellascloselyaspossible.Itdoesnotalwayssucceed.
SeparatingandGroupingCommands
Whetheryougivetheshellcommandsinteractivelyorwriteashellscript,youmustseparatecommands
fromoneanother.Thissection,whichappliestotheBourneAgainandtheTCShells,reviewsthewaysto
separatecommandsthatwerecoveredinChapter5andintroducesafewnewones.
;ANDNEWLINESeparateCommands
TheNEWLINEcharacterisauniquecommandseparatorbecauseitinitiatesexecutionofthecommand
precedingit.YouhaveseenthisthroughoutthisbookeachtimeyoupresstheRETURNkeyattheendofa
commandline.
Thesemicolon(;)isacommandseparatorthatdoesnotinitiateexecutionofacommandanddoesnot
changeanyaspectofhowthecommandfunctions.Youcanexecuteaseriesofcommandssequentiallyby
enteringthemonasinglecommandlineandseparatingeachfromthenextwithasemicolon(;).You
initiateexecutionofthesequenceofcommandsbypressingRETURN:
$x;y;z
Ifx,y,andzarecommands,theprecedingcommandlineyieldsthesameresultsasthenextthree
commands.Thedifferenceisthatinthenextexampletheshellissuesapromptaftereachofthecommands
(x,y,andz)finishesexecuting,whereastheprecedingcommandlinecausestheshelltoissueaprompt
onlyafterziscomplete:
$x
$y
$z
Whitespace
Althoughthewhitespacearoundthesemicolonsintheearlierexamplemakesthecommandlineeasierto
read,itisnotnecessary.NoneofthecommandseparatorsneedstobesurroundedbySPACEsorTABs.
\ContinuesaCommand
Whenyouenteralongcommandlineandthecursorreachestherightsideofthescreen,youcanusea
backslash(\)charactertocontinuethecommandonthenextline.Thebackslashquotes,orescapes,the
NEWLINEcharacterthatfollowsitsothattheshelldoesnottreattheNEWLINEasacommand
terminator.Enclosingabackslashwithinsinglequotationmarksturnsoffthepowerofabackslashto
quotespecialcharacterssuchasNEWLINE.Enclosingabackslashwithindoublequotationmarkshasno
effectonthepowerofthebackslash.
Althoughyoucanbreakalineinthemiddleofaword(token),itistypicallyeasiertobreakalinejust
beforeorafterwhitespace.

optional
YoucanenteraRETURNinthemiddleofaquotedstringonacommandlinewithoutusingabackslash.TheNEWLINE
(RETURN)thatyouenterwillthenbepartofthestring:
$echo"Pleaseenterthethreevalues
>requiredtocompletethetransaction."
Pleaseenterthethreevalues
requiredtocompletethetransaction.
Inthethreeexamplesinthissection,theshelldoesnotinterpretRETURNasacommandterminatorbecauseitoccurswithina
quotedstring.The>isasecondarypromptindicatingthattheshelliswaitingforyoutocontinuetheunfinishedcommand.Inthe
nextexample,thefirstRETURNisquoted(escaped)sotheshelltreatsitasaseparatoranddoesnotinterpretitliterally.
$echo"Pleaseenterthethreevalues\
>requiredtocompletethetransaction."
Pleaseenterthethreevaluesrequiredtocompletethetransaction.
Singlequotationmarkscausetheshelltointerpretabackslashliterally:
$echo'Pleaseenterthethreevalues\
>requiredtocompletethetransaction.'
Pleaseenterthethreevalues\
requiredtocompletethetransaction.
|AND&SeparateCommandsandDoSomethingElse
Thepipesymbol(|)andthebackgroundtasksymbol(&)arealsocommandseparators.Theydonotstart
executionofacommandbutdochangesomeaspectofhowthecommandfunctions.Thepipesymbol
altersthesourceofstandardinputorthedestinationofstandardoutput.Thebackgroundtasksymbol
causestheshelltoexecutethetaskinthebackgroundsoyougetapromptimmediatelyandcancontinue
workingonothertasks.
Eachofthefollowingcommandlinesinitiatesasinglejobcomprisingthreetasks:
$x|y|z
$ls-l|greptmp|less
Inthefirstjob,theshellredirectsstandardoutputoftaskxtostandardinputoftaskyandredirectsy's
standardoutputtoz'sstandardinput.Becauseitrunstheentirejobintheforeground,theshelldoesnot
displayapromptuntiltaskzrunstocompletion:Taskzdoesnotfinishuntiltaskyfinishes,andtasky
doesnotfinishuntiltaskxfinishes.Inthesecondjob,taskxisanlslcommand,taskyisgreptmp,and
taskzisthepagerless.Theshelldisplaysalong(wide)listingofthefilesintheworkingdirectorythat
containthestringtmp,pipedthroughless.
Thenextcommandlineexecutestasksdandeinthebackgroundandtaskfintheforeground:
$d&e&f
[1]14271
[2]14272
TheshelldisplaysthejobnumberbetweenbracketsandthePID(processidentification)numberforeach
processrunninginthebackground.Yougetapromptassoonasffinishes,whichmaybebeforedore
finishes.
Beforedisplayingapromptforanewcommand,theshellcheckswhetheranybackgroundjobshave
completed.Foreachjobthathascompleted,theshelldisplaysitsjobnumber,thewordDone,andthe
commandlinethatinvokedthejob;thentheshelldisplaysaprompt.Whenthejobnumbersarelisted,the
numberofthelastjobstartedisfollowedbya+characterandthejobnumberofthepreviousjobis
followedbyacharacter.AnyotherjobslistedshowaSPACEcharacter.Afterrunningthelastcommand,
theshelldisplaysthefollowingbeforeissuingaprompt:
[1]-Doned
[2]+Donee
Thenextcommandlineexecutesallthreetasksasbackgroundjobs.Yougetashellpromptimmediately:
$d&e&f&
[1]14290
[2]14291
[3]14292
Youcanusepipestosendtheoutputfromonetasktothenexttaskandanampersand(&)toruntheentire
jobasabackgroundtask.Againthepromptcomesbackimmediately.Theshellregardsthecommands
joinedbyapipeasbeingasinglejob.Thatis,ittreatsallpipesassinglejobs,nomatterhowmanytasks
areconnectedwiththepipe(|)symbolorhowcomplextheyare.TheBourneAgainShellshowsonlyone
processplacedinthebackground:
$d|e|f&
[1]14295
TheTCShellshowsthreeprocesses(allbelongingtojob1)placedinthebackground:
tcsh$d|e|f&
[1]143021430414306

optional:()GroupsCommands
Youcanuseparenthesestogroupcommands.Theshellcreatesacopyofitself,calledasubshell,foreachgroup.Ittreatseach
groupofcommandsasajobandcreatesanewprocesstoexecuteeachcommand(referto"ProcessStructure"onpage293for
moreinformationoncreatingsubshells).Eachsubshell(job)hasitsownenvironment,meaningthatithasitsownsetofvariables
withvaluesthatcandifferfromthoseofothersubshells.
Thefollowingcommandlineexecutescommandsaandbsequentiallyinthebackgroundwhileexecutingcinthebackground.The
shellpromptreturnsimmediately.
$(a;b)&c&
[1]15520
[2]15521
Theprecedingexamplediffersfromtheearlierexampled&e&f&inthattasksaandbareinitiatedsequentially,not
concurrently.
Similarlythefollowingcommandlineexecutesaandbsequentiallyinthebackgroundand,atthesametime,executescandd
sequentiallyinthebackground.Thesubshellrunningaandbandthesubshellrunningcanddrunconcurrently.Theprompt
returnsimmediately.
$(a;b)&(c;d)&
[1]15528
[2]15529
Thenextscriptcopiesonedirectorytoanother.Thesecondpairofparenthesescreatesasubshelltorunthecommandsfollowing
thepipe.Becauseoftheseparentheses,theoutputofthefirsttarcommandisavailableforthesecondtarcommanddespitethe
interveningcdcommand.Withouttheparentheses,theoutputofthefirsttarcommandwouldbesenttocdandlostbecausecd
doesnotprocessinputfromstandardinput.Theshellvariables$1and$2representthefirstandsecondcommandlinearguments
(page481),respectively.Thefirstpairofparentheses,whichcreatesasubshelltorunthefirsttwocommands,allowsusersto
callcpdirwithrelativepathnames.Withoutthemthefirstcdcommandwouldchangetheworkingdirectoryofthescript(and
consequentlytheworkingdirectoryofthesecondcdcommand).Withthemonlytheworkingdirectoryofthesubshellischanged.
$catcpdir
(cd$1;tar-cf-.)|(cd$2;tar-xvf-)
$cpdir/home/alex/sources/home/alex/memo/biblio
Thecpdircommandlinecopiesthefilesanddirectoriesinthe/home/alex/sourcesdirectorytothedirectorynamed
/home/alex/memo/biblio.Thisshellscriptisalmostthesameasusingcpwiththeroption.RefertoPartVformoreinformation
oncp(page616)andtar(page786).
JobControl
Ajobisacommandpipeline.YourunasimplejobwheneveryougiveLinuxacommand.Forexample,
typedateonthecommandlineandpressRETURN:Youhaverunajob.Youcanalsocreateseveraljobs
withmultiplecommandsonasinglecommandline:
$find.-print|sort|lpr&grep-lalex/tmp/*>alexfiles&
[1]18839
[2]18876
Theportionofthecommandlineuptothefirst&isonejobconsistingofthreeprocessesconnectedby
pipes:find(page655),sort(page50),andlpr(page47).Thesecondjobisasingleprocessrunning
grep.Bothjobshavebeenputintothebackgroundbythetrailing&characters,sobashdoesnotwait
forthemtocompletebeforedisplayingaprompt.
Usingjobcontrolyoucanmovecommandsfromtheforegroundtothebackground(andviceversa),stop
commandstemporarily,andlistallthecommandsthatarerunninginthebackgroundorstopped.
jobs:ListsJobs
Thejobsbuiltinlistsallbackgroundjobs.Thefollowingsequencedemonstrateswhathappenswhen
yougiveajobscommand.Herethesleepcommandrunsinthebackgroundandcreatesabackground
jobthatjobsreportson:
$sleep60&
[1]7809
$jobs
[1]+Runningsleep60&
fg:BringsaJobtotheForeground
Theshellassignsjobnumberstocommandsyouruninthebackground(page269).Severaljobsare
startedinthebackgroundinthenextexample.ForeachjobtheshellliststhejobnumberandPIDnumber
immediately,justbeforeitissuesaprompt.
$xclock&
[1]1246
$date&
[2]1247
$SunDec411:44:40PST2005
[2]+Donedate
$find/usr-nameace-print>findout&
[2]1269
$jobs
[1]-Runningxclock&
[2]+Runningfind/usr-nameace-print>findout&
Jobnumbers,whicharediscardedwhenajobisfinished,canbereused.Whenyoustartorputajobin
thebackground,theshellassignsajobnumberthatisonemorethanthehighestjobnumberinuse.
Intheprecedingexample,thejobscommandliststhefirstjob,xclock,asjob1.Thedatecommand
doesnotappearinthejobslistbecauseitfinishedbeforejobswasrun.Becausethedatecommand
wascompletedbeforefindwasrun,thefindcommandbecamejob2.
Tomoveabackgroundjobintotheforeground,usethefgbuiltinfollowedbythejobnumber.
Alternatively,youcangiveapercentsign(%)followedimmediatelybythejobnumberasacommand.
Eitherofthefollowingcommandsmovesjob2intotheforeground:
$fg2
or
$%2
Youcanalsorefertoajobbyfollowingthepercentsignwithastringthatuniquelyidentifiesthe
beginningofthecommandlineusedtostartthejob.Insteadoftheprecedingcommand,youcouldhave
usedeitherfg%findorfg%fbecausebothuniquelyidentifyjob2.Ifyoufollowthepercentsignwitha
questionmarkandastring,thestringcanmatchanypartofthecommandline.Intheprecedingexample,
fg%?acealsobringsjob2intotheforeground.
Oftenthejobyouwishtobringintotheforegroundistheonlyjobrunninginthebackgroundoristhejob
thatjobslistswithaplus(+).Inthesecasesyoucanusefgwithoutanargument.
bg:SendsaJobtotheBackground
Tomovetheforegroundjobtothebackground,youmustfirstsuspend(temporarilystop)thejobby
pressingthesuspendkey(usuallyCONTROL-Z).Pressingthesuspendkeyimmediatelysuspendsthejob
intheforeground.Youcanthenusethebgbuiltintoresumeexecutionofthejobinthebackground.
$bg
Ifabackgroundjobattemptstoreadfromtheterminal,theshellstopsitandnotifiesyouthatthejobhas
beenstoppedandiswaitingforinput.Youmustthenmovethejobintotheforegroundsothatitcanread
fromtheterminal.Theshelldisplaysthecommandlinewhenitmovesthejobintotheforeground.
$(sleep5;cat>mytext)&
[1]1343
$date
SunDec411:58:20PST2005
[1]+Stopped(sleep5;cat>mytext)
$fg
(sleep5;cat>mytext)
Remembertoletthecatout!
CONTROL-D
$
Intheprecedingexample,theshelldisplaysthejobnumberandPIDnumberofthebackgroundjobas
soonasitstarts,followedbyaprompt.Demonstratingthatyoucangiveacommandatthispoint,theuser
givesthecommanddateanditsoutputappearsonthescreen.Theshellwaitsuntiljustbeforeitissuesa
prompt(afterdatehasfinished)tonotifyyouthatjob1isstopped.Whenyougiveanfgcommand,the
shellputsthejobintheforegroundandyoucanentertheinputthatthecommandiswaitingfor.Inthiscase
theinputneedstobeterminatedwithaCONTROL-DtosignifyEOF(endoffile).Theshellthendisplays
anotherprompt.
Theshellkeepsyouinformedaboutchangesinthestatusofajob,notifyingyouwhenabackgroundjob
starts,completes,orisstopped,perhapswaitingforinputfromtheterminal.Theshellalsoletsyouknow
whenaforegroundjobissuspended.Becausenoticesaboutajobbeingruninthebackgroundcandisrupt
yourwork,theshelldelaysdisplayingthesenoticesuntiljustbeforeitdisplaysaprompt.Youcanset
notify(page321)tomaketheshelldisplaythesenoticeswithoutdelay.
Ifyoutrytoexitfromashellwhilejobsarestopped,theshellissuesawarninganddoesnotallowyouto
exit.Ifyouthenusejobstoreviewthelistofjobsoryouimmediatelytrytoleavetheshellagain,the
shellallowsyoutoleaveandterminatesthestoppedjobs.Jobsthatarerunning(notstopped)inthe
backgroundcontinuetorun.Inthefollowingexample,find(job1)continuestorunafterthesecond
exitterminatestheshell,butcat(job2)isterminated:
$find/-size+100k>$HOME/bigfiles2>&1&
[1]1426
$cat>mytest&
[2]1428
$exit
exit
Therearestoppedjobs.
$exit
exit
login:
ManipulatingtheDirectoryStack
BoththeBourneAgainandtheTCShellsallowyoutostorealistofdirectoriesyouareworkingwith,
enablingyoutomoveeasilyamongthem.Thislistisreferredtoasastack.Itisanalogoustoastackof
dinnerplates:Youtypicallyaddplatestoandremoveplatesfromthetopofthestack,creatingafirst-in
last-out,(FILO)stack.
dirs:DisplaystheStack
Thedirsbuiltindisplaysthecontentsofthedirectorystack.Ifyoucalldirswhenthedirectorystack
isempty,itdisplaysthenameoftheworkingdirectory:
$dirs
~/literature
Thedirsbuiltinusesatilde(~)torepresentthenameofthehomedirectory.Theexamplesinthenext
severalsectionsassumethatyouarereferringtothedirectorystructureshowninFigure8-2.
Figure8-2.Thedirectorystructureintheexamples

pushd:PushesaDirectoryontheStack
Tochangedirectoriesandatthesametimeaddanewdirectorytothetopofthestack,usethepushd
(pushdirectory)builtin.Inadditiontochangingdirectories,thepushdbuiltindisplaysthecontentsofthe
stack.ThefollowingexampleisillustratedinFigure8-3:
$pushd../demo
~/demo~/literature
$pwd
/home/sam/demo
$pushd../names
~/names~/demo~/literature
$pwd
/home/sam/names
Figure8-3.Creatingadirectorystack

Whenyouusepushdwithoutanargument,itswapsthetoptwodirectoriesonthestackandmakesthe
newtopdirectory(whichwastheseconddirectory)becomethenewworkingdirectory(Figure8-4):
$pushd
~/demo~/names~/literature
$pwd
/home/sam/demo
Figure8-4.Usingpushdtochangeworkingdirectories
Usingpushdinthisway,youcaneasilymovebackandforthbetweentwodirectories.Youcanalsouse
cdtochangetothepreviousdirectory,whetherornotyouhaveexplicitlycreatedadirectorystack.To
accessanotherdirectoryinthestack,callpushdwithanumericargumentprecededbyaplussign.The
directoriesinthestackarenumberedstartingwiththetopdirectory,whichisnumber0.Thefollowing
pushdcommandcontinueswiththepreviousexample,changingtheworkingdirectorytoliteratureand
movingliteraturetothetopofthestack:
$pushd+2
~/literature~/demo~/names
$pwd
/home/sam/literature
popd:PopsaDirectoryOfftheStack
Toremoveadirectoryfromthestack,usethepopd(popdirectory)builtin.Asthefollowingexampleand
Figure8-5show,popdusedwithoutanargumentremovesthetopdirectoryfromthestackandchanges
theworkingdirectorytothenewtopdirectory:
$dirs
~/literature~/demo~/names
$popd
~/demo~/names
$pwd
/home/sam/demo
Figure8-5.Usingpopdtoremoveadirectoryfromthestack

Toremoveadirectoryotherthanthetoponefromthestack,usepopdwithanumericargumentpreceded
byaplussign.Thefollowingexampleremovesdirectorynumber1,demo:
$dirs
~/literature~/demo~/names
$popd+1
~/literature~/names
Removingadirectoryotherthandirectorynumber0doesnotchangetheworkingdirectory.
ParametersandVariables
Variables
Withinashell,ashellparameterisassociatedwithavaluethatisaccessibletotheuser.Thereare
severalkindsofshellparameters.Parameterswhosenamesconsistofletters,digits,andunderscoresare
oftenreferredtoasshellvariables,orsimplyvariables.Avariablenamemuststartwithaletteror
underscore,notwithanumber.ThusA76,MY_CAT,and___X___arevalidvariablenames,
whereas69TH_STREET(startswithadigit)andMY-NAME(containsahyphen)arenot.
User-createdvariables
Shellvariablesthatyounameandassignvaluestoareuser-createdvariables.Youcanchangethevalues
ofuser-createdvariablesatanytime,oryoucanmakethemreadonlysothattheirvaluescannotbe
changed.Youcanalsomakeuser-createdvariablesglobal.Aglobalvariable(alsocalledanenvironment
variable)isavailabletoallshellsandotherprogramsyouforkfromtheoriginalshell.Onenaming
conventionistouseonlyuppercaselettersforglobalvariablesandtousemixed-caseorlowercase
lettersforothervariables.Referto"LocalityofVariables"onpage475formoreinformationonglobal
variables.
ToassignavaluetoavariableintheBourneAgainShell,usethefollowingsyntax:
VARIABLE=value
Therecanbenowhitespaceoneithersideoftheequalsign(=).Anexampleassignmentfollows:
$myvar=abc
UndertheTCShelltheassignmentmustbeprecededbythewordsetandtheSPACEsoneithersideof
theequalsignareoptional:
$setmyvar=abc
TheBourneAgainShellpermitsyoutoputvariableassignmentsonacommandline.Theseassignments
arelocaltothecommandshellthatis,theyapplytothecommandonly.Themy_scriptshellscriptdisplays
thevalueofTEMPDIR.Thefollowingcommandrunsmy_scriptwithTEMPDIRsetto
/home/sam/temp.TheechobuiltinshowsthattheinteractiveshellhasnovalueforTEMPDIRafter
runningmy_script.IfTEMPDIRhadbeensetintheinteractiveshell,runningmy_scriptinthismanner
wouldhavehadnoeffectonitsvalue.
$catmy_script
echo$TEMPDIR
$TEMPDIR=/home/sam/tempmy_script
/home/sam/temp
$echo$TEMPDIR
$
Keywordvariables
Keywordshellvariables(orsimplykeywordvariables)havespecialmeaningtotheshellandusually
haveshort,mnemonicnames.Whenyoustartashell(byloggingin,forexample),theshellinherits
severalkeywordvariablesfromtheenvironment.AmongthesevariablesareHOME,whichidentifies
yourhomedirectory,andPATH,whichdetermineswhichdirectoriestheshellsearchesandinwhatorder
tolocatecommandsthatyougivetheshell.Theshellcreatesandinitializes(withdefaultvalues)other
keywordvariableswhenyoustartit.Stillothervariablesdonotexistuntilyousetthem.
Youcanchangethevaluesofmostofthekeywordshellvariablesatanytimebutitisusuallynot
necessarytochangethevaluesofkeywordvariablesinitializedinthe/etc/profileor/etc/csh.cshrc
systemwidestartupfiles.Ifyouneedtochangethevalueofabashkeywordvariable,dosoinoneof
yourstartupfiles(forbashseepage257;fortcshseepage342).Justasyoucanmakeuser-created
variablesglobal,soyoucanmakekeywordvariablesglobal;thisisusuallydoneautomaticallyinthe
startupfiles.Youcanalsomakeakeywordvariablereadonly.
Positionalparameters
Specialparameters
Thenamesofonegroupofparametersdonotresemblevariablenames.Mostoftheseparametershave
one-characternames(forexample,1,?,and#)andarereferenced(asareallvariables)byprecedingthe
namewithadollarsign($1,$?,and$#).Thevaluesoftheseparametersreflectdifferentaspectsofyour
ongoinginteractionwiththeshell.
Wheneveryougiveacommand,eachargumentonthecommandlinebecomesthevalueofapositional
parameter.Positionalparameters(page480)enableyoutoaccesscommandlinearguments,acapability
thatyouwilloftenrequirewhenyouwriteshellscripts.Thesetbuiltin(page484)enablesyoutoassign
valuestopositionalparameters.
Otherfrequentlyneededshellscriptvalues,suchasthenameofthelastcommandexecuted,thenumberof
commandlinearguments,andthestatusofthemostrecentlyexecutedcommand,areavailableasspecial
parameters.Youcannotassignvaluestospecialparameters.
User-CreatedVariables
Thefirstlineinthefollowingexampledeclaresthevariablenamedpersonandinitializesitwiththe
valuealex(usesetperson=alexintcsh):
$person=alex
$echoperson
person
$echo$person
alex
Becausetheechobuiltincopiesitsargumentstostandardoutput,youcanuseittodisplaythevaluesof
variables.Thesecondlineoftheprecedingexampleshowsthatpersondoesnotrepresentalex.Instead,
thestringpersonisechoedasperson.Theshellsubstitutesthevalueofavariableonlywhenyouprecede
thenameofthevariablewithadollarsign($).Thecommandecho$persondisplaysthevalueofthe
variableperson;itdoesnotdisplay$personbecausetheshelldoesnotpass$persontoechoasan
argument.Becauseoftheleading$,theshellrecognizesthat$personisthenameofavariable,
substitutesthevalueofthevariable,andpassesthatvaluetoecho.Theechobuiltindisplaysthevalue
ofthevariablenotitsnameneverknowingthatyoucalleditwithavariable.
Quotingthe$
Youcanpreventtheshellfromsubstitutingthevalueofavariablebyquotingtheleading$.Double
quotationmarksdonotpreventthesubstitution;singlequotationmarksorabackslash(\)do.
$echo$person
alex
$echo"$person"
alex
$echo'$person'
$person
$echo\$person
$person
SPACEs
Becausetheydonotpreventvariablesubstitutionbutdoturnoffthespecialmeaningsofmostother
characters,doublequotationmarksareusefulwhenyouassignvaluestovariablesandwhenyouusethose
values.ToassignavaluethatcontainsSPACEsorTABstoavariable,usedoublequotationmarksaround
thevalue.Althoughdoublequotationmarksarenotrequiredinallcases,usingthemisagoodhabit.
$person="alexandjenny"
$echo$person
alexandjenny
$person=alexandjenny
bash:and:commandnotfound
WhenyoureferenceavariablethatcontainsTABsormultipleadjacentSPACEs,youneedtouse
quotationmarkstopreservethespacing.Ifyoudonotquotethevariable,theshellcollapseseachstringof
blankcharactersintoasingleSPACEbeforepassingthevariabletotheutility:
$person="alexandjenny"
$echo$person
alexandjenny
$echo"$person"
alexandjenny
Whenyouexecuteacommandwithavariableasanargument,theshellreplacesthenameofthevariable
withthevalueofthevariableandpassesthatvaluetotheprogrambeingexecuted.Ifthevalueofthe
variablecontainsaspecialcharacter,suchas*or?,theshellmayexpandthatvariable.
Pathnameexpansioninassignments
Thefirstlineinthefollowingsequenceofcommandsassignsthestringalex*tothevariablememo.The
BourneAgainShelldoesnotexpandthestringbecausebashdoesnotperformpathnameexpansion
(page127)whenassigningavaluetoavariable.Allshellsprocessacommandlineinaspecificorder.
Withinthisorderbash(butnottcsh)expandsvariablesbeforeitinterpretscommands.Inthefollowing
echocommandline,thedoublequotationmarksquotetheasterisk(*)intheexpandedvalueof$memo
andpreventbashfromperformingpathnameexpansionontheexpandedmemovariablebeforepassing
itsvaluetotheechocommand:
$memo=alex*
$echo"$memo"
alex*
Allshellsinterpretspecialcharactersasspecialwhenyoureferenceavariablethatcontainsanunquoted
specialcharacter.Inthefollowingexample,theshellexpandsthevalueofthememovariablebecauseit
isnotquoted:
$ls
alex.report
alex.summary
$echo$memo
alex.reportalex.summary
Heretheshellexpands$memotoalex*,expandsalex*toalex.reportandalex.summary,andpasses
thesetwovaluestoecho.

optional:Braces
The$VARIABLEsyntaxisaspecialcaseofthemoregeneralsyntax${VARIABLE},inwhichthevariablenameisenclosedby
${}.Thebracesinsulatethevariablename.Bracesarenecessarywhencatenatingavariablevaluewithastring:
$PREF=counter
$WAY=$PREFclockwise
$FAKE=$PREFfeit
$echo$WAY$FAKE
$
Theprecedingexampledoesnotworkasplanned.Onlyablanklineisoutputbecause,althoughthesymbolsPREFclockwiseand
PREFfeitarevalidvariablenames,theyarenotset.Bydefaulttheshellevaluatesanunsetvariableasanempty(null)stringand
displaysthisvalue(bash)orgeneratesanerrormessage(tcsh).Toachievetheintentofthesestatements,refertothePREF
variableusingbraces:
$PREF=counter
$WAY=${PREF}clockwise
$FAKE=${PREF}feit
$echo$WAY$FAKE
counterclockwisecounterfeit
TheBourneAgainShellreferstotheargumentsonitscommandlinebyposition,usingthespecialvariables$1,$2,$3,andso
forthupto$9.Ifyouwishtorefertoargumentspasttheninthargument,youmustusebraces:${10}.Thenameofthecommand
isheldin$0(page481).
unset:RemovesaVariable
Unlessyouremoveavariable,itexistsaslongastheshellinwhichitwascreatedexists.Toremovethe
valueofavariablebutnotthevariableitself,setthevaluetonull(usesetperson=intcsh):
$person=
$echo$person
$
Youcanremoveavariablewiththeunsetbuiltin.Toremovethevariableperson,givethefollowing
command:
$unsetperson
VariableAttributes
Thissectiondiscussesattributesandexplainshowtoassignthemtovariables.
readonly:MakestheValueofaVariablePermanent
Youcanusethereadonlybuiltin(notintcsh)toensurethatthevalueofavariablecannotbe
changed.Thenextexampledeclaresthevariablepersontobereadonly.Youmustassignavaluetoa
variablebeforeyoudeclareittobereadonly;youcannotchangeitsvalueafterthedeclaration.Whenyou
attempttounsetorchangethevalueofareadonlyvariable,theshelldisplaysanerrormessage:
$person=jenny
$echo$person
jenny
$readonlyperson
$person=helen
bash:person:readonlyvariable

Ifyouusethereadonlybuiltinwithoutanargument,itdisplaysalistofallreadonlyshellvariables.
Thislistincludeskeywordvariablesthatareautomaticallysetasreadonlyaswellaskeywordoruser-
createdvariablesthatyouhavedeclaredasreadonly.See"Listingvariableattributes"onpage282foran
example(readonlyanddeclarerproducethesameoutput).
declareANDtypeset:AssignAttributestoVariables
Thedeclareandtypesetbuiltins(twonamesforthesamecommand,neitherofwhichisavailable
intcsh)setattributesandvaluesforshellvariables.Table8-3listsfiveoftheseattributes.
Table8-3.Variableattributes(typesetordeclare)
Attribute Meaning
aDeclaresavariableasanarray(page474)
fDeclaresavariabletobeafunctionname(page315)
iDeclaresavariabletobeoftypeinteger(page283)
rMakesavariablereadonly;alsoreadonly(page281)
xExportsavariable(makesitglobal);alsoexport(page475)
Thefollowingcommandsdeclareseveralvariablesandsetsomeattributes.Thefirstlinedeclares
person1andassignsitavalueofalex.Thiscommandhasthesameeffectwithorwithouttheword
declare.
$declareperson1=alex
$declare-rperson2=jenny
$declare-rxperson3=helen
$declare-xperson4
Thereadonlyandexportbuiltinsaresynonymsforthecommandsdeclareranddeclarex,
respectively.Itislegaltodeclareavariablewithoutassigningavaluetoit,astheprecedingdeclaration
ofthevariableperson4illustrates.Thisdeclarationmakesperson4availabletoallsubshells(makesit
global).Untilanassignmentismadetothevariable,ithasanullvalue.
Youcanlisttheoptionstodeclareseparatelyinanyorder.Thefollowingisequivalenttothe
precedingdeclarationofperson3:
$declare-x-rperson3=helen
Usethe+characterinplaceofwhenyouwanttoremoveanattributefromavariable.Youcannotremove
areadonlyattribute,however.Afterthefollowingcommandisgiven,thevariableperson3isnolonger
exportedbutitisstillreadonly.
$declare+xperson3
Youcanalsousetypesetinsteadofdeclare.
Listingvariableattributes
Withoutanyargumentsoroptions,thedeclarebuiltinlistsallshellvariables.Thesamelistisoutput
whenyourunset(page484)withoutanyarguments.
Ifyouuseadeclarebuiltinwithoptionsbutnovariablenamesasarguments,thecommandlistsall
shellvariablesthathavetheindicatedattributesset.Forexample,theoptionrwithdeclaregivesalist
ofallreadonlyshellvariables.Thislististhesameasthatproducedbyareadonlycommandwithoutany
arguments.Afterthedeclarationsintheprecedingexamplehavebeengiven,theresultsareasfollows:
$declare-r
declare-arBASH_VERSINFO='([0]="2"[1]="05b"[2]="0"[3]="1"...)'
declare-irEU
declare-irPP
declare-r
SHELLOPTS="braceexpand:emacs:hashall:histexpand:history:..."
declare-irU

declare-rperson2="jenny"
declare-rxperson3="helen"
Thefirstfiveentriesarekeywordvariablesthatareautomaticallydeclaredasreadonly.Someofthese
variablesarestoredasintegers(i).TheaoptionindicatesthatBASH_VERSINFOisanarrayvariable;
thevalueofeachelementofthearrayislistedtotherightofanequalsign.
Integer
Bydefaultthevaluesofvariablesarestoredasstrings.Whenyouperformarithmeticonastringvariable,
theshellconvertsthevariableintoanumber,manipulatesit,andthenconvertsitbacktoastring.A
variablewiththeintegerattributeisstoredasaninteger.Assigntheintegerattributeasfollows:
$typeset-iCOUNT
KeywordVariables
Keywordvariableseitherareinheritedoraredeclaredandinitializedbytheshellwhenitstarts.Youcan
assignvaluestothesevariablesfromthecommandlineorfromastartupfile.Typicallyyouwantthese
variablestoapplytoallsubshellsyoustartaswellastoyourloginshell.Forthosevariablesnot
automaticallyexportedbytheshell,youmustuseexport(bash,page475)orsetenv(tcsh,page
356)tomakethemavailabletochildshells.
HOME:YourHomeDirectory
Bydefaultyourhomedirectoryisyourworkingdirectorywhenyoulogin.Yourhomedirectoryis
determinedwhenyouestablishyouraccount;itsnameisstoredinthe/etc/passwdfile.
$grepsam/etc/passwd
sam:x:501:501:SamS.x301:/home/sam:/bin/bash
Whenyoulogin,theshellinheritsthepathnameofyourhomedirectoryandassignsittothevariable
HOME.Whenyougiveacdcommandwithoutanargument,cdmakesthedirectorywhosenameis
storedinHOMEtheworkingdirectory:
$pwd
/home/alex/laptop
$echo$HOME
/home/alex
$cd
$pwd
/home/alex
ThisexampleshowsthevalueoftheHOMEvariableandtheeffectofthecdbuiltin.Afteryouexecute
cdwithoutanargument,thepathnameoftheworkingdirectoryisthesameasthevalueofHOME:your
homedirectory.
Tilde(~)
TheshellusesthevalueofHOMEtoexpandpathnamesthatusetheshorthandtilde(~)notation(page
89)todenoteauser'shomedirectory.Thefollowingexampleusesechotodisplaythevalueofthis
shortcutandthenuseslstolistthefilesinAlex'slaptopdirectory,whichisasubdirectoryofhishome
directory:
$echo~
/home/alex
$ls~/laptop
testercountlineup
PATH:WheretheShellLooksforPrograms
Whenyougivetheshellanabsoluteorrelativepathnameratherthanasimplefilenameasacommand,it
looksinthespecifieddirectoryforanexecutablefilewiththespecifiedfilename.Ifthefilewiththe
pathnameyouspecifieddoesnotexist,theshellreportscommandnotfound.Ifthefileexistsasspecified
butyoudonothaveexecutepermissionforit,orinthecaseofashellscriptyoudonothavereadand
executepermissionforit,theshellreportsPermissiondenied.
Ifyougiveasimplefilenameasacommand,theshellsearchesthroughcertaindirectoriesfortheprogram
youwanttoexecute.Itlooksinseveraldirectoriesforafilethathasthesamenameasthecommandand
thatyouhaveexecutepermissionfor(acompiledprogram)orreadandexecutepermissionfor(ashell
script).ThePATHshellvariablecontrolsthissearch.
ThedefaultvalueofPATHisdeterminedwhenbashortcshiscompiled.Itisnotsetinastartupfile,
althoughitmaybemodifiedthere.Normallythedefaultspecifiesthattheshellsearchseveralsystem
directoriesusedtoholdcommoncommandsandthensearchtheworkingdirectory.Thesesystem
directoriesinclude/binand/usr/binandotherdirectoriesappropriatetothelocalsystem.Whenyougive
acommand,iftheshelldoesnotfindtheexecutableand,inthecaseofashellscript,readablefilenamed
bythecommandinanyofthedirectorieslistedinPATH,theshellgeneratesoneoftheaforementioned
errormessages.
Workingdirectory
ThePATHvariablespecifiesthedirectoriesintheordertheshellshouldsearchthem.Eachdirectory
mustbeseparatedfromthenextbyacolon.ThefollowingcommandsetsPATHsothatasearchforan
executablefilestartswiththe/usr/local/bindirectory.Ifitdoesnotfindthefileinthisdirectory,theshell
firstlooksin/bin,andthenin/usr/bin.Ifthesearchfailsinthosedirectories,theshelllooksinthebin
director,asubdirectoryoftheuser'shomedirectory.Finallytheshelllooksintheworkingdirectory.
ExportingPATHmakesitsvalueaccessibletosubshells:
$exportPATH=/usr/local/bin:/bin:/usr/bin:~/bin:
Anullvalueinthestringindicatestheworkingdirectory.Intheprecedingexample,anullvalue(nothing
betweenthecolonandtheendoftheline)appearsasthelastelementofthestring.Theworkingdirectory
isrepresentedbyaleadingcolon(notrecommended;seethefollowingsecuritytip),atrailingcolon(as
intheexample),ortwocolonsnexttoeachotheranywhereinthestring.Youcanalsorepresentthe
workingdirectoryexplicitlywithaperiod(.).
See"PATH"onpage363foratcshexample.BecauseLinuxstoresmanyexecutablefilesindirectories
namedbin(binary),userstypicallyputtheirownexecutablefilesintheirown~/bindirectories.Ifyou
putyourownbindirectoryattheendofyourPATH,asintheprecedingexample,theshelllookstherefor
anycommandsthatitcannotfindindirectorieslistedearlierinPATH.
security:PATHandsecurity
DonotputtheworkingdirectoryfirstinPATHwhensecurityisaconcern.Ifyouare
runningasSuperuser,youshouldneverputtheworkingdirectoryfirstinPATH.Itis
commonforSuperuserPATHtoomittheworkingdirectoryentirely.Youcanalways
executeafileintheworkingdirectorybyprepending./tothename:./ls.
PuttingtheworkingdirectoryfirstinPATHcancreateasecurityhole.Mostpeopletypels
asthefirstcommandwhenenteringadirectory.Iftheownerofadirectoryplacesan
executablefilenamedlsinthedirectory,andtheworkingdirectoryappearsfirstinauser's
PATH,theusergivinganlscommandfromthedirectoryexecutesthelsprograminthe
workingdirectoryinsteadofthesystemlsutility,possiblywithundesirableresults.
IfyouwanttoadddirectoriestoPATH,youcanreferencetheoldvalueofthePATHvariablewhileyou
aresettingPATHtoanewvalue(butseetheprecedingsecuritytip).Thefollowingcommandadds
/usr/X11R6/bintothebeginningofthecurrentPATHand/usr/local/binandtheworkingdirectorytothe
end:
$PATH=/usr/X11R6/bin:$PATH:/usr/local/bin:
MAIL:WhereYourMailIsKept
TheMAILvariable(mailundertcsh)containsthepathnameofthefilethatholdsyourmail(your
mailbox,usually/var/spool/mail/name,wherenameisyourloginname).IfMAILissetand
MAILPATH(next)isnotset,theshellinformsyouwhenmailarrivesinthefilespecifiedbyMAIL.Ina
graphicalenvironmentyoucanunsetMAILsothattheshelldoesnotdisplaymailremindersinaterminal
emulatorwindow(assumingyouareusingagraphicalmailprogram).
TheMAILPATHvariable(notavailableundertcsh)containsalistoffilenamesseparatedbycolons.If
thisvariableisset,theshellinformsyouwhenanyoneofthefilesismodified(forexample,whenmail
arrives).Youcanfollowanyofthefilenamesinthelistwithaquestionmark(?),followedbyamessage.
Themessagereplacestheyouhavemailmessagewhenyougetmailwhileyouareloggedin.
TheMAILCHECKvariable(notavailableundertcsh)specifieshowoften,inseconds,theshell
checksfornewmail.Thedefaultis60seconds.Ifyousetthisvariabletozero,theshellchecksbefore
eachprompt.
PS1:UserPrompt(Primary)
ThedefaultBourneAgainShellpromptisadollarsign($).Whenyourunbashasroot,youmayhavea
poundsign(#)prompt.ThePS1variable(promptundertcsh,page363)holdsthepromptstringthatthe
shellusestoletyouknowthatitiswaitingforacommand.WhenyouchangethevalueofPS1orprompt,
youchangetheappearanceofyourprompt.
YoucancustomizethepromptdisplayedbyPS1.Forexample,theassignment
$PS1="[\u@\h\W\!]$"
displaysthefollowingprompt:
[user@hostdirectoryevent]$
whereuseristheusername,hostisthehostnameuptothefirstperiod,directoryisthebasenameofthe
workingdirectory,andeventistheeventnumberofthecurrentcommand.
Ifyouareworkingonmorethanonesystem,itcanbehelpfultoincorporatethesystemnameintoyour
prompt.Forexample,youmightchangetheprompttothenameofthesystemyouareusing,followedbya
colonandaSPACE(aSPACEattheendofthepromptmakesthecommandsthatyouenterafterthe
prompteasiertoread):
$PS1="$(hostname):"
bravo.example.com:echotest
test
bravo.example.com:
Usethefollowingcommandundertcsh:
tcsh$setprompt="`hostname`:"

Thefirstexamplethatfollowschangestheprompttothenameofthelocalhost,aSPACE,andadollar
sign(or,iftheuserisrunningasroot,apoundsign).Thesecondexamplechangestheprompttothetime
followedbythenameoftheuser.Thethirdexamplechangestheprompttotheoneusedinthisbook(a
poundsignforrootandadollarsignotherwise):
$PS1='\h\$'
bravo$
$PS1='\@\u$'
09:44PMalex$
$PS1='\$'
$
Table8-4describessomeofthesymbolsyoucanuseinPS1.Foracompletelistofspecialcharacters
youcanuseinthepromptstrings,openthebashmanpageandsearchforthesecondoccurrenceof
PROMPTING(givethecommand/PROMPTINGandthenpressn).
Table8-4.PS1symbols
Symbol Displayinprompt
\$ #iftheuserisrunningasroot;otherwise,$
\w Pathnameoftheworkingdirectory
\W Basenameoftheworkingdirectory
\! Currentevent(history)number(page300)
\d DateinWeekdayMonthDateformat
\h Machinehostname,withoutthedomain

\H Fullmachinehostname,includingthedomain
\u Usernameofthecurrentuser
\@ Currenttimeofdayin12-hour,AM/PMformat
\T Currenttimeofdayin12-hourHH:MM:SSformat
\A Currenttimeofdayin24-hourHH:MMformat
\t Currenttimeofdayin24-hourHH:MM:SSformat
PS2:UserPrompt(Secondary)
PromptString2isasecondarypromptthattheshellstoresinPS2(notundertcsh).Onthefirstlineof
thenextexample,anunclosedquotedstringfollowsecho.Theshellassumesthatthecommandisnot
finishedand,onthesecondline,givesthedefaultsecondaryprompt(>).Thispromptindicatesthatthe
shelliswaitingfortheusertocontinuethecommandline.Theshellwaitsuntilitreceivesthequotation
markthatclosesthestringandthenexecutesthecommand:
$echo"demonstrationofpromptstring
>2"
demonstrationofpromptstring
2
$PS2="secondaryprompt:"
$echo"thisdemonstrates
secondaryprompt:promptstring2"
thisdemonstrates
promptstring2
Thesecondcommandchangesthesecondaryprompttosecondaryprompt:followedbyaSPACE.A
multilineechodemonstratesthenewprompt.
PS3:MenuPrompt
PS3holdsthemenupromptfortheselectcontrolstructure(page467).
PS4:DebuggingPrompt
PS4holdsthebashdebuggingsymbol(page449).
caution:BecarefulwhenchangingIFS
ChangingIFShasavarietyofsideeffectssoworkcautiously.Youmayfinditusefultofirst
savethevalueofIFSbeforechangingit;youcaneasilythenrestoretheoriginalvalueif
yougetunexpectedresults.Alternatively,youcanforkanewshellwithabashcommand
beforeexperimentingwithIFS;ifyougetintotrouble,youcanexitbacktotheoldshell,
whereIFSisworkingproperly.YoucanalsosetIFStoitsdefaultvaluewiththefollowing
command:
$IFS='\t\n'
IFS:SeparatesInputFields(WordSplitting)
TheIFS(InternalFieldSeparator)shellvariable(notundertcsh)specifiesthecharactersthatyoucan
usetoseparateargumentsonacommandlineandhasthedefaultvalueofSPACETABNEWLINE.
RegardlessofthevalueofIFS,youcanalwaysuseoneormoreSPACEorTABcharacterstoseparate
argumentsonthecommandline,providedthatthesecharactersarenotquotedorescaped.Whenyou
assignIFScharactervalues,thesecharacterscanalsoseparatefieldsbutonlyiftheyundergoexpansion.
Thistypeofinterpretationofthecommandlineiscalledwordsplitting.
ThefollowingexampledemonstrateshowsettingIFScanaffecttheinterpretationofacommandline:
$a=w:x:y:z
$cat$a
cat:w:x:y:z:Nosuchfileordirectory
$IFS=":"
$cat$a
cat:w:Nosuchfileordirectory
cat:x:Nosuchfileordirectory
cat:y:Nosuchfileordirectory
cat:z:Nosuchfileordirectory
Thefirsttimecatiscalled,theshellexpandsthevariablea,interpretingthestringw:x:y:zasasingle
wordtobeusedastheargumenttocat.Thecatutilitycannotfindafilenamedw:x:y:zandreportsan
errorforthatfilename.AfterIFSissettoacolon(:),theshellexpandsthevariableaintofourwords,
eachofwhichisanargumenttocat.Nowcatreportsanerrorforfourseparatefiles:w,x,y,andz.
Wordsplittingbasedonthecolon(:)takesplaceonlyafterthevariableaisexpanded.
Theshellsplitsallexpandedwordsonacommandlineaccordingtotheseparatingcharactersfoundin
IFS.Whenthereisnoexpansion,thereisnosplitting.Considerthefollowingcommands:
$IFS="p"
$exportVAR
AlthoughIFSissettop,thepontheexportcommandlineisnotexpandedsothewordexportisnot
split.
Thenextexampleusesvariableexpansioninanattempttoproduceanexportcommand:
$IFS="p"
$aa=export
$echo$aa
exort
Thistimeexpansionoccurssothatthecharacterpinthetokenexportisinterpretedasaseparatorasthe
precedingechocommandshows.Nowwhenyoutrytousethevalueoftheaavariabletoexportthe
VARvariable,theshellparsesthe$aaVARcommandlineasexortVAR.Theeffectisthatthecommand
linestartstheexeditorwithtwofilenames:ortandVAR.
$$aaVAR
2filestoedit
"ort"[NewFile]
EnteringExmode.Type"visual"togotoNormalmode.
:q
E173:1morefiletoedit
:q
$
IfyouunsetIFS,onlySPACEsandTABsworkasfieldseparators.
CDPATH:BroadenstheScopeofcd
TheCDPATHvariable(cdpathundertcsh)allowsyoutouseasimplefilenameasanargumenttothe
cdbuiltintochangetheworkingdirectorytoadirectoryotherthanachildoftheworkingdirectory.Ifyou
haveseveraldirectoriesyouliketoworkoutof,thisvariablecanspeedthingsupandsaveyouthetedium
ofusingcdwithlongerpathnamestoswitchamongthem.
WhenCDPATHorcdpathisnotsetandyouspecifyasimplefilenameasanargumenttocd,cd
searchestheworkingdirectoryforasubdirectorywiththesamenameastheargument.Ifthesubdirectory
doesnotexist,cddisplaysanerrormessage.WhenCDPATHorcdpathisset,cdsearchesforan
appropriatelynamedsubdirectoryinthedirectoriesintheCDPATHlist.Ifcdfindsone,thatdirectory

becomestheworkingdirectory.WithCDPATHorcdpathset,youcanusecdandasimplefilenameto
changetheworkingdirectorytoachildofanyofthedirectorieslistedinCDPATHorcdpath.
TheCDPATHorcdpathvariabletakesonthevalueofacolon-separatedlistofdirectorypathnames
(similartothePATHvariable).Itisusuallysetinthe~/.bash_profile(bash)or~/.tcshrc(tcsh)
startupfilewithacommandlinesuchasthefollowing:
exportCDPATH=$HOME:$HOME/literature
Usethefollowingformatfortcsh:
setenvcdpath$HOME\:$HOME/literature
Thesecommandscausecdtosearchyourhomedirectory,theliteraturedirectory,andthentheworking
directorywhenyougiveacdcommand.IfyoudonotincludetheworkingdirectoryinCDPATHor
cdpath,cdsearchestheworkingdirectoryifthesearchofalltheotherdirectoriesinCDPATHor
cdpathfails.Ifyouwantcdtosearchtheworkingdirectoryfirst(whichyoushouldneverdowhenyou
areloggedinasrootrefertothesecuritytiponpage285),includeanullstring,representedbytwocolons
(::),asthefirstentryinCDPATH:
exportCDPATH=::$HOME:$HOME/literature
Iftheargumenttothecdbuiltinisanabsolutefilenameonestartingwithaslash(/)theshelldoesnot
consultCDPATHorcdpath.
KeywordVariables:ASummary
Table8-5liststhebashkeywordvariables.
Table8-5.bashkeywordvariables
Variable Value

BASH_ENV Thepathnameofthestartupfilefornoninteractiveshells(page258)
CDPATH Thecdsearchpath(page289)
COLUMNS Thewidthofthedisplayusedbyselect(page466)
FCEDIT Thenameoftheeditorthatfcusesbydefault(page298)
HISTFILE Thepathnameofthefilethatholdsthehistorylist(default:~/.bash_history;
page295)
HISTFILESIZE ThemaximumnumberofentriessavedinHISTFILE(default:500;page
295)
HISTSIZE Themaximumnumberofentriessavedinthehistorylist(default:500;page
295)
HOME Thepathnameoftheuser'shomedirectory(page283);usedasthedefault
argumentforcdandintildeexpansion(page89)
IFS InternalFieldSeparator(page288);usedforwordsplitting(page330)
INPUTRC ThepathnameoftheReadlinestartupfile(default:~/.inputrc;page309)
LANG ThelocalecategorywhenthatcategoryisnotspecificallysetwithanLC_*
variable
LC_*
Agroupofvariablesthatspecifylocalecategoriesincluding
LC_COLLATE,LC_CTYPE,LC_MESSAGES,andLC_NUMERIC;use
thelocalebuiltintodisplayacompletelistwithvalues
LINES Theheightofthedisplayusedbyselect(page466)
MAIL Thepsathnameofthefilethatholdsauser'smail(page285)
MAILCHECK Howoften,inseconds,bashchecksformail(page285)
MAILPATH Acolon-separatedlistoffilepathnamesthatbashchecksformailin(page
285)
PATH Acolon-separatedlistofdirectorypathnamesthatbashlooksfor
commandsin(page284)
PROMPT_COMMAND Acommandthatbashexecutesjustbeforeitdisplaystheprimaryprompt
PS1 PromptString1;theprimaryprompt(default:'\s\v\$';page286)
PS2 PromptString2;thesecondaryprompt(default:'>';page287)

PS3 Thepromptissuedbyselect(page466)
PS4 Thebashdebuggingsymbol(page449)
REPLY Holdsthelinethatreadaccepts(page488);alsousedbyselect(page466)
SpecialCharacters
Table8-6listsmostofthecharactersthatarespecialtothebashandtcshshells.
Table8-6.Shellspecialcharacters
Character Use
NEWLINE Initiatesexecutionofacommand(page267)
; Separatescommands(page267)
() Groupscommands(page270)forexecutionbyasubshell
oridentifiesafunction(page315)
&Executesacommandinthebackground(pages125and
269)
|Sendsstandardoutputofprecedingcommandtostandard
inputoffollowingcommand(pipe;page269)
>Redirectsstandardoutput(page116)
>> Appendsstandardoutput(page121)
<Redirectsstandardinput(page118)
<< Heredocument(page468)
*Anystringofzeroormorecharactersinanambiguousfile
reference(page129)
?Anysinglecharacterinanambiguousfilereference(page
128)
\Quotesthefollowingcharacter(page42)
'Quotesastring,preventingallsubstitution(page42)

"Quotesastring,allowingonlyvariableandcommand
substitution(pages42and279)
'...'Performscommandsubstitution(page329)
[] Characterclassinanambiguousfilereference(page130)
$Referencesavariable(page277)
.(dotbuiltin) Executesacommand(onlyatthebeginningofaline,page
259)
#Beginsacomment(page266)
{} Usedtosurroundthecontentsofafunction(page315)
:(nullbuiltin) Returnstrue(page495)
&&(BooleanAND) Executescommandonrightonlyifcommandonleft
succeeds(returnsazeroexitstatus,page507)
||(BooleanOR) Executescommandonrightonlyifcommandonleftfails
(returnsanonzeroexitstatus;page507)
!(BooleanNOT) Reversesexitstatusofacommand
$()(notintcsh)Performscommandsubstitution(preferredform;page329)
[] Evaluatesanarithmeticexpression(page327)
Processes
AprocessistheexecutionofacommandbyLinux.Theshellthatstartswhenyouloginisacommand,or
aprocess,likeanyother.WhenyougivethenameofaLinuxutilityonthecommandline,youinitiatea
process.Whenyourunashellscript,anothershellprocessisstartedandadditionalprocessesarecreated
foreachcommandinthescript.Dependingonhowyouinvoketheshellscript,thescriptisruneitherby
thecurrentshellor,moretypically,byasubshell(child)ofthecurrentshell.Aprocessisnotstartedwhen
yourunashellbuiltin,suchascd.
ProcessStructure
forksystemcall
Likethefilestructure,theprocessstructureishierarchical,withparents,children,andevenaroot.A
parentprocessforksachildprocess,whichinturncanforkotherprocesses.(Thetermforkindicatesthat,
aswithaforkintheroad,oneprocessturnsintotwo.Initiallythetwoforksareidenticalexceptthatone
isidentifiedastheparentandoneasthechild.Youcanalsousethetermspawn;thewordsare
interchangeable.)Theoperatingsystemroutine,orsystemcall,thatcreatesanewprocessisnamedfork.
WhenLinuxbeginsexecutionwhenasystemisstarted,itstartsinit,asingleprocesscalleda
spontaneousprocess,withPIDnumber1.Thisprocessholdsthesamepositionintheprocessstructureas
therootdirectorydoesinthefilestructure:Itistheancestorofallprocessesthatthesystemandusers
workwith.Whenthesystemisinmultiusermode,initrunsgettyormingettyprocesses,which
displaylogin:promptsonterminalsandvirtualconsoles.Whensomeonerespondstothepromptand
pressesRETURN,gettyhandscontrolovertoautilitynamedlogin,whichcheckstheusernameand
passwordcombination.Aftertheuserlogsin,theloginprocessbecomestheuser'sshellprocess.
ProcessIdentification
PIDnumber
LinuxassignsauniquePID(processidentification)numberattheinceptionofeachprocess.Aslongasa
processexists,itkeepsthesamePIDnumber.Duringonesessionthesameprocessisalwaysexecuting
theloginshell.Whenyouforkanewprocessforexample,whenyouuseaneditorthePIDnumberofthe
new(child)processisdifferentfromthatofitsparentprocess.Whenyoureturntotheloginshell,itis
stillbeingexecutedbythesameprocessandhasthesamePIDnumberaswhenyouloggedin.
Thefollowingexampleshowsthattheprocessrunningtheshellforked(istheparentof)theprocess
runningps(page127).Whenyoucallitwiththefoption,psdisplaysafulllistingofinformationabout
eachprocess.ThelineofthepsdisplaywithbashintheCMDcolumnreferstotheprocessrunningthe
shell.ThecolumnheadedbyPIDidentifiesthePIDnumber.ThecolumnheadedPPIDidentifiesthePID
numberoftheparentoftheprocess.FromthePIDandPPIDcolumnsyoucanseethattheprocessrunning
theshell(PID21341)istheparentoftheprocessrunningsleep(PID22789).TheparentPIDnumberof
sleepisthesameasthePIDnumberoftheshell(21341).
$sleep10&
[1]22789
$ps-f
UIDPIDPPIDCSTIMETTYTIMECMD
alex2134121340010:42pts/1600:00:00bash
alex2278921341017:30pts/1600:00:00sleep10
alex2279021341017:30pts/1600:00:00ps-f
Refertopage746formoreinformationonpsandthecolumnsitdisplayswiththefoption.Asecondpair
ofsleepandpsfcommandsshowsthattheshellisstillbeingrunbythesameprocessbutthatitforked
anotherprocesstorunsleep:
$sleep10&
[1]22791
$ps-f
UIDPIDPPIDCSTIMETTYTIMECMD
alex2134121340010:42pts/1600:00:00bash
alex2279121341017:31pts/1600:00:00sleep10
alex2279221341017:31pts/1600:00:00ps-f
Youcanalsousepstree(orpsforest,withorwithouttheeoption)toseetheparentchildrelationship
ofprocesses.Thenextexampleshowsthepoptiontopstree,whichcausesittodisplayPIDnumbers:
$pstree-p
init(1)-+-acpid(1395)
|-atd(1758)
|-crond(1702)
...
|-kdeinit(2223)-+-firefox(8914)---run-mozilla.sh(8920)---
firefox-bin(8925)
||-gaim(2306)
||-gqview(14062)
||-kdeinit(2228)
||-kdeinit(2294)
||-kdeinit(2314)-+-bash(2329)---ssh(2561)
|||-bash(2339)
||'-bash(15821)---bash(16778)
||-kdeinit(16448)
||-kdeinit(20888)
||-oclock(2317)
|'-pam-panel-icon(2305)---
pam_timestamp_c(2307)
...
|-login(1823)---bash(20986)-+-pstree(21028)
|'-sleep(21026)
...
Theprecedingoutputisabbreviated.Thelinethatstartswithkdeinitshowsagraphicaluserrunning
manyprocesses,includingfirefox,gaim,andoclock.Thelinethatstartswithloginshowsatextualuser
runningsleepinthebackgroundwhilerunningpstreeintheforeground.Referto"$$:PIDNumber:
PIDNumber"onpage478foradescriptionofhowtoinstructtheshelltoreportonPIDnumbers.
ExecutingACommand
forkandsleep
Whenyougivetheshellacommand,itusuallyforks(spawns)achildprocesstoexecutethecommand.
Whilethechildprocessisexecutingthecommand,theparentprocesssleeps.Whileaprocessissleeping,
itdoesnotuseanycomputertimebutremainsinactive,waitingtowakeup.Whenthechildprocess
finishesexecutingthecommand,ittellsitsparentofitssuccessorfailureviaitsexitstatusandthendies.
Theparentprocess(whichisrunningtheshell)wakesupandpromptsforanothercommand.
Backgroundprocess
Whenyourunaprocessinthebackgroundbyendingacommandwithanampersand(&),theshellforksa
childprocesswithoutgoingtosleepandwithoutwaitingforthechildprocesstoruntocompletion.The
parentprocess,whichisexecutingtheshell,reportsthejobnumberandPIDnumberofthechildand
promptsforanothercommand.Thechildprocessrunsinthebackground,independentofitsparent.
Builtins
Althoughtheshellforksaprocesstorunmostofthecommandsyougiveit,somecommandsarebuiltinto
theshell.Theshelldoesnotneedtoforkaprocesstorunbuiltins.Formoreinformationreferto
"Builtins"onpage132.
Variables
Withinagivenprocess,suchasyourloginshellorasubshell,youcandeclare,initialize,read,and
changevariables.Bydefault,however,avariableislocaltoaprocess.Whenaprocessforksachild
process,theparentdoesnotpassthevalueofavariabletothechild.Youcanmakethevalueofavariable
availabletochildprocesses(global)byusingtheexportbuiltinunderbash(page475)orthe

History
Thehistorymechanism,afeatureadaptedfromtheCShell,maintainsalistofrecentlyissuedcommand
lines,alsocalledevents,providingaquickwaytoreexecuteanyoftheeventsinthelist.Thismechanism
alsoenablesyoutoexecutevariationsofpreviouscommandsandtoreuseargumentsfromthem.Youcan
replicatecomplicatedcommandsandargumentsthatyouusedearlierinthisloginsessionorinaprevious
oneandenteraseriesofcommandsthatdifferfromoneanotherinminorways.Thehistorylistalso
servesasarecordofwhatyouhavedone.Itcanprovehelpfulwhenyouhavemadeamistakeandarenot
surewhatyoudidorwhenyouwanttokeeparecordofaprocedurethatinvolvedaseriesofcommands.
Thehistorybuiltin(bothinbashandtcsh)displaysthehistorylist.Ifitdoesnot,readonyouneed
tosetsomevariables.
tip:historycanhelptrackdownmistakes
Whenyouhavemadeacommandlinemistake(notanerrorwithinascriptorprogram)and
arenotsurewhatyoudidwrong,lookatthehistorylisttoreviewyourrecentcommands.
Sometimesthislistcanhelpyoufigureoutwhatwentwrongandhowtofixthings.
VariablesThatControlHistory
TheTCShell'shistorymechanismissimilartobash'sbutusesdifferentvariablesandhasother
differences.Seepage344formoreinformation.
ThevalueoftheHISTSIZEvariabledeterminesthenumberofeventspreservedinthehistorylistduring
asession.Avalueintherangeof100to1,000isnormal.
Whenyouexitfromtheshell,themostrecentlyexecutedcommandsaresavedinthefilegivenbythe
HISTFILEvariable(thedefaultis~/.bash_history).Thenexttimeyoustarttheshell,thisfileinitializes
thehistorylist.ThevalueoftheHISTFILESIZEvariabledeterminesthenumberoflinesofhistorysaved
inHISTFILE(notnecessarilythesameasHISTSIZE).HISTSIZEholdsthenumberofevents
rememberedduringasession,HISTFILESIZEholdsthenumberrememberedbetweensessions,andthe
filedesignatedbyHISTFILEholdsthehistorylist.SeeTable8-7.
Table8-7.Historyvariables
Variable Default Function
HISTSIZE 500events Maximumnumberofeventssavedduringa
session

HISTFILE ~/.bash_history Locationofthehistoryfile
HISTFILESIZE 500events Maximumnumberofeventssavedbetween
sessions
Eventnumber
TheBourneAgainShellassignsasequentialeventnumbertoeachcommandline.Youcandisplaythis
eventnumberaspartofthebashpromptbyincluding\!inPS1(page286).Examplesinthissection
shownumberedpromptswhentheyhelptoillustratethebehaviorofacommand.
Givethefollowingcommandmanuallyorplaceitin~/.bash_profile(toaffectfuturesessions)to
establishahistorylistofthe100mostrecentevents:
$HISTSIZE=100
Thefollowingcommandcausesbashtosavethe100mostrecenteventsacrossloginsessions:
$HISTFILESIZE=100
AfteryousetHISTFILESIZE,youcanlogoutandloginagain,andthe100mostrecenteventsfromthe
previousloginsessionwillappearinyourhistorylist.
Givethecommandhistorytodisplaytheeventsinthehistorylist.Thelistofeventsisorderedwith
oldesteventsatthetopofthelist.Atcshhistorylistincludesthetimethecommandwasexecuted.The
followinghistorylistincludesacommandtomodifythebashpromptsothatitdisplaysthehistoryevent
number.Thelasteventinthehistorylististhehistorycommandthatdisplayedthelist.
32$history|tail
23PS1="\!bash$"
24ls-l
25cattemp
26rmtemp
27vimmemo
28lprmemo
29vimmemo
30lprmemo
31rmmemo
32history|tail
Asyouruncommandsandyourhistorylistbecomeslonger,itmayrunoffthetopofthescreenwhenyou
usethehistorybuiltin.Pipetheoutputofhistorythroughlesstobrowsethroughit,orgivethe
commandhistory10tolookatthetenmostrecentcommands.
ReexecutingandEditingCommands
Youcanreexecuteanyeventinthehistorylist.Thisfeaturecansaveyoutime,effort,andaggravation.Not
havingtoreenterlongcommandlinesallowsyoutoreexecuteeventsmoreeasily,quickly,andaccurately
thanyoucouldifyouhadtoretypetheentirecommandline.Youcanrecall,modify,andreexecute
previouslyexecutedeventsinthreeways:Youcanusethefcbuiltin(coverednext);theexclamation
pointcommands(page300);ortheReadlineLibrary,whichusesaone-linevi-oremacs-likeeditorto
editandexecuteevents(page305).
tip:Whichmethodtouse?
IfyouaremorefamiliarwithvioremacsandlessfamiliarwiththeCorTCShell,use
fcortheReadlineLibrary.IfyouaremorefamiliarwiththeCorTCShellandless
familiarwithviandemacs,usetheexclamationpointcommands.Ifitisatoss-up,trythe
ReadlineLibrary;itwillbenefityouinotherareasofLinuxmorethanlearningthe
exclamationpointcommandswill.
fc:Displays,Edits,andReexecutesCommands
Thefc(fixcommand)builtin(notintcsh)enablesyoutodisplaythehistorylistandtoeditand
reexecutepreviouscommands.Itprovidesmanyofthesamecapabilitiesasthecommandlineeditors.
ViewingtheHistoryList
Whenyoucallfcwiththeloption,itdisplayscommandsfromthehistorylist.Withoutanyarguments,fc
lliststhe16mostrecentcommandsinanumberedlist,withtheoldestappearingfirst:
$fc-l
1024cd
1025viewcalendar
1026vimletter.adams01
1027aspell-cletter.adams01
1028vimletter.adams01
1029lprletter.adams01
1030cd../memos
1031ls
1032rm*0405
1033fc-l
1034cd
1035whereisaspell
1036manaspell
1037cd/usr/share/doc/*aspell*
1038pwd
1039ls
1040lsman-html
Thefcbuiltincantakezero,one,ortwoargumentswiththeloption.Theargumentsspecifythepartof
thehistorylisttobedisplayed:
fcl[first[last]]
Thefcbuiltinlistscommandsbeginningwiththemostrecenteventthatmatchesfirst.Theargumentcan
beaneventnumber,thefirstfewcharactersofthecommandline,oranegativenumber,whichistakento
bethenthpreviouscommand.Ifyouprovidelast,fcdisplayscommandsfromthemostrecenteventthat
matchesfirstthroughthemostrecenteventthatmatcheslast.Thenextcommanddisplaysthehistorylist
fromevent1030throughevent1035:
$fc-l10301035
1030cd../memos
1031ls
1032rm*0405
1033fc-l
1034cd
1035whereisaspell
Thefollowingcommandliststhemostrecenteventthatbeginswithviewthroughthemostrecent
commandlinethatbeginswithwhereis:
$fc-lviewwhereis
1025viewcalendar
1026vimletter.adams01
1027aspell-cletter.adams01
1028vimletter.adams01
1029lprletter.adams01
1030cd../memos
1031ls
1032rm*0405
1033fc-l
1034cd
1035whereisaspell
Tolistasinglecommandfromthehistorylist,usethesameidentifierforthefirstandsecondarguments.
Thefollowingcommandlistsevent1027:
$fc-l10271027
1027aspell-cletter.adams01
EditingandReexecutingPreviousCommands
Youcanusefctoeditandreexecutepreviouscommands.
fc[eeditor][first[last]]
Whenyoucallfcwiththeeoptionfollowedbythenameofaneditor,fccallstheeditorwithevent(s)
intheWorkbuffer.Withoutfirstandlast,fcdefaultstothemostrecentcommand.Thenextexample
invokesthevi(m)editortoeditthemostrecentcommand:
$fc-evi
Thefcbuiltinusesthestand-alonevi(m)editor.IfyousettheFCEDITvariable,youdonotneedto
usetheeoptiontospecifyaneditoronthecommandline.BecausethevalueofFCEDIThasbeen
changedto/usr/bin/emacsandfchasnoarguments,thefollowingcommandeditsthemostrecent
commandwiththeemacseditor:
$exportFCEDIT=/usr/bin/emacs
$fc
Ifyoucallitwithasingleargument,fcinvokestheeditoronthespecifiedcommand.Thefollowing
examplestartstheeditorwithevent21intheWorkbuffer.Whenyouexitfromtheeditor,theshell
executesthecommand:
$fc21
Againyoucanidentifycommandswithnumbersorbyspecifyingthefirstfewcharactersofthecommand
name.Thefollowingexamplecallstheeditortoworkoneventsfromthemostrecenteventthatbegins
withthelettersvimthroughevent206:
$fcvim206
caution:Cleanupthefcbuffer
Whenyouexecuteanfccommand,theshellexecuteswhateveryouleaveintheeditor
buffer,possiblywithunwantedresults.Ifyoudecideyoudonotwanttoexecutea
command,deleteeverythingfromthebufferbeforeyouexitfromtheeditor.
ReexecutingCommandsWithoutCallingtheEditor
Youcanreexecutepreviouscommandswithoutgoingintoaneditor.Ifyoucallfcwiththesoption,it
skipstheeditingphaseandreexecutesthecommand.Thefollowingexamplereexecutesevent1029:
$fc-s1029
lprletter.adams01
Thenextexamplereexecutesthepreviouscommand:
$fc-s
Whenyoureexecuteacommandyoucantellfctosubstituteonestringforanother.Thenextexample
substitutesthestringjohnforthestringadamsinevent1029andexecutesthemodifiedevent:
$fc-sadams=john1029
lprletter.john01
UsinganExclamationPoint(!)toReferenceEvents
TheCShellhistorymechanismusesanexclamationpointtoreferenceeventsandisavailableunder
bashandtcsh.Itisfrequentlymorecumbersometousethanfcbutneverthelesshassomeuseful
features.Forexample,the!!commandreexecutesthepreviousevent,andthe!$tokenrepresentsthelast
wordonthepreviouscommandline.
Youcanreferenceaneventbyusingitsabsoluteeventnumber,itsrelativeeventnumber,orthetextit
contains.Allreferencestoevents,calledeventdesignators,beginwithanexclamationpoint(!).Oneor
morecharactersfollowtheexclamationpointtospecifyanevent.
Youcanputhistoryeventsanywhereonacommandline.Toescapeanexclamationpointsothatitis
treatedliterallyinsteadofasthestartofahistoryevent,precedeitwithabackslash(\)orencloseit
withinsinglequotationmarks.
EventDesignators

Aneventdesignatorspecifiesacommandinthehistorylist.SeeTable8-8onpage301foralistofevent
designators.
Table8-8.Eventdesignators
Designator Meaning
!StartsahistoryeventunlessfollowedimmediatelybySPACE,NEWLINE,=,
or(.
!! Thepreviouscommand.
!nCommandnumberninthehistorylist.
!nThenthprecedingcommand.
!string Themostrecentcommandlinethatstartedwithstring.
!?string[?] Themostrecentcommandthatcontainedstring.Thelast?isoptional.
!# Thecurrentcommand(asyouhaveittypedsofar).
!{event}
Theeventisaneventdesignator.Thebracesisolateeventfromthe
surroundingtext.Forexample,!{3}3isthethirdmostrecentlyexecuted
commandfollowedbya3.
!!reexecutesthepreviousevent
Youcanalwaysreexecutethepreviouseventbygivinga!!command.Inthefollowingexample,event45
reexecutesevent44:
44$ls-ltext
-rw-rw-r--1alexgroup45Apr3014:53text
45$!!
ls-ltext
-rw-rw-r--1alexgroup45Apr3014:53text
The!!commandworkswhetherornotyourpromptdisplaysaneventnumber.Asthisexampleshows,
whenyouusethehistorymechanismtoreexecuteanevent,theshelldisplaysthecommanditis
reexecuting.
!neventnumber
Anumberfollowinganexclamationpointreferstoanevent.Ifthateventisinthehistorylist,theshell
executesit.Otherwise,theshelldisplaysanerrormessage.Anegativenumberfollowinganexclamation
pointreferencesaneventrelativetothecurrentevent.Forexample,thecommand!3referstothethird
precedingevent.Afteryouissueacommand,therelativeeventnumberofagiveneventchanges(event3
becomesevent4).Bothofthefollowingcommandsreexecuteevent44:
51$!44
ls-ltext
-rw-rw-r--1alexgroup45Nov3014:53text
52$!-8
ls-ltext
-rw-rw-r--1alexgroup45Nov3014:53text
!stringeventtext
Whenastringoftextfollowsanexclamationpoint,theshellsearchesforandexecutesthemostrecent
eventthatbeganwiththatstring.Ifyouenclosethestringbetweenquestionmarks,theshellexecutesthe
mostrecenteventthatcontainedthatstring.ThefinalquestionmarkisoptionalifaRETURNwould
immediatelyfollowit.
68$history10
59ls-ltext*
60tailtext5
61cattext1text5>letter
62vimletter
63catletter
64catmemo
65lprmemo
66pinejenny
67ls-l
68history
69$!l
ls-l
...
70$!lpr
lprmemo
71$!?letter?
catletter
...

optional:WORDDESIGNATORS
Aworddesignatorspecifiesawordorseriesofwordsfromanevent.Table8-9onpage303listsworddesignators.
Table8-9.Worddesignators
Designator Meaning
nThenthword.Word0isnormallythecommandname.
^Thefirstword(afterthecommandname).
$Thelastword.
mnAllwordsfromwordnumbermthroughwordnumbern;mdefaultsto0if
youomitit(0n).
n* Allwordsfromwordnumbernthroughthelastword.
*Allwordsexceptthecommandname.Thesameas1*.
%Thewordmatchedbythemostrecent?string?search.
Thewordsarenumberedstartingwith0(thefirstwordonthelineusuallythecommand),continuingwith1(thefirstword
followingthecommand),andgoingthroughn(thelastwordontheline).
Tospecifyaparticularwordfromapreviousevent,followtheeventdesignator(suchas!14)withacolonandthenumberofthe
wordinthepreviousevent.Forexample,!14:3specifiesthethirdwordfollowingthecommandfromevent14.Youcanspecify
thefirstwordfollowingthecommand(wordnumber1)byusingacaret(^)andthelastwordbyusingadollarsign($).Youcan
specifyarangeofwordsbyseparatingtwoworddesignatorswithahyphen.
72$echoapplegrapeorangepear
applegrapeorangepear
73$echo!72:2
echogrape
grape
74$echo!72:^
echoapple
apple
75$!72:0!72:$
echopear
pear

76$echo!72:2-4
echograpeorangepear
grapeorangepear
77$!72:0-$
echoapplegrapeorangepear
applegrapeorangepear
Asthenextexampleshows,!$referstothelastwordofthepreviousevent.Youcanusethisshorthandtoedit,forexample,afile
youjustdisplayedwithcat:
$catreport.718
...
$vim!$
vimreport.718
...
Ifaneventcontainsasinglecommand,thewordnumberscorrespondtotheargumentnumbers.Ifaneventcontainsmorethan
onecommand,thiscorrespondencedoesnotholdtrueforcommandsafterthefirst.Inthefollowingexampleevent78contains
twocommandsseparatedbyasemicolonsothattheshellexecutesthemsequentially;thesemicoloniswordnumber5.
78$!72;echohelenjennybarbara
echoapplegrapeorangepear;echohelenjennybarbara
applegrapeorangepear
helenjennybarbara
79$echo!78:7
echohelen
helen
80$echo!78:4-7
echopear;echohelen
pear
helen
MODIFIERS
Onoccasionyoumaywanttochangeanaspectofaneventyouarereexecuting.Perhapsyouenteredacomplexcommandline
withatypoorincorrectpathnameoryouwanttospecifyadifferentargument.Youcanmodifyaneventorawordofaneventby

puttingoneormoremodifiersaftertheworddesignator,oraftertheeventdesignatorifthereisnoworddesignator.Eachmodifier
mustbeprecededbyacolon(:).
Substitutemodifier
Thesubstitutemodifierismorecomplexthantheothermodifiers.Thefollowingexampleshowsthesubstitutemodifiercorrecting
atypointhepreviousevent:
$car/home/jenny/memo.0507/home/alex/letter.0507
bash:car:commandnotfound
$!!:s/car/cat
cat/home/jenny/memo.0507/home/alex/letter.0507
...
Thesubstitutemodifierhasthefollowingsyntax:
[g]s/old/new/
whereoldistheoriginalstring(notaregularexpression),andnewisthestringthatreplacesold.Thesubstitutemodifier
substitutesthefirstoccurrenceofoldwithnew.Placingagbeforethes(asings/old/new/)causesaglobalsubstitution,replacing
alloccurrencesofold.The/isthedelimiterintheexamplesbutyoucanuseanycharacterthatisnotineitheroldornew.The
finaldelimiterisoptionalifaRETURNwouldimmediatelyfollowit.AswiththevimSubstitutecommand,thehistorymechanism
replacesanampersand(&)innewwithold.Theshellreplacesanulloldstring(s//new/)withthepreviousoldstringorstring
withinacommandthatyousearchedforwith?string?
Quicksubstitution
Anabbreviatedformofthesubstitutemodifierisquicksubstitution.Useittoreexecutethemostrecenteventwhilechangingsome
oftheeventtext.Thequicksubstitutioncharacteristhecaret(^).Forexample,thecommand
$^old^new^
producesthesameresultsas
$!!:s/old/new/
Thussubstitutingcatforcarinthepreviouseventcouldhavebeenenteredas
$^car^cat
cat/home/jenny/memo.0507/home/alex/letter.0507
...
YoucanomitthefinalcaretifitwouldbefollowedimmediatelybyaRETURN.Aswithothercommandlinesubstitutions,theshell
displaysthecommandlineasitappearsafterthesubstitution.
Othermodifiers

Modifiers(otherthanthesubstitutemodifier)performsimpleeditsonthepartoftheeventthathasbeenselectedbytheevent
designatorandtheoptionalworddesignators.Youcanusemultiplemodifiers,eachprecededbyacolon(:).
Thefollowingseriesofcommandsuseslstolistthenameofafile,repeatsthecommandwithoutexecutingit(pmodifier),and
repeatsthelastcommand,removingthelastpartofthepathname(hmodifier)againwithoutexecutingit:
$ls/etc/sysconfig/harddisks
/etc/sysconfig/harddisks
$!!:p
ls/etc/sysconfig/harddisks
$!!:h:p
ls/etc/sysconfig
$
Table8-10listseventmodifiersotherthanthesubstitutemodifier.
Table8-10.Modifiers
Modifier Function
e(extension) Removesallbutthefilenameextension
h(head) Removesthelastpartofapathname
p(print-not) Displaysthecommand,butdoesnotexecuteit
q(quote) Quotesthesubstitutiontopreventfurther
substitutionsonit
r(root) Removesthefilenameextension
t(tail) Removesallelementsofapathnameexceptthe
last
xLikeqbutquoteseachwordinthesubstitution
individually
TheReadlineLibrary
CommandlineeditingundertheBourneAgainShellisimplementedthroughtheReadlineLibrary,which
isavailabletoanyapplicationwritteninC.AnyapplicationthatusestheReadlineLibrarysupportsline
editingthatisconsistentwiththatprovidedbybash.ProgramsthatusetheReadlineLibrary,including
bash,read~/.inputrc(page309)forkeybindinginformationandconfigurationsettings.Thenoediting
commandlineoptionturnsoffcommandlineeditinginbash.
vimode
YoucanchooseoneoftwoeditingmodeswhenusingtheReadlineLibraryinbash:emacsorvi(m).
Bothmodesprovidemanyofthecommandsavailableinthestand-aloneversionsofthevi(m)and
emacseditors.YoucanalsousetheARROWkeystomovearound.Upanddownmovementsmoveyou
backwardandforwardthroughthehistorylist.Inaddition,Readlineprovidesseveraltypesofinteractive
wordcompletion(page307).Thedefaultmodeisemacs;youcanswitchtovimodewiththefollowing
command:
$set-ovi
emacsmode
Thenextcommandswitchesbacktoemacsmode:
$set-oemacs
viEditingMode
Beforeyoustartmakesureyouareinvimode.
Whenyouenterbashcommandswhileinvieditingmode,youareinInputmode(page142).Asyou
enteracommand,ifyoudiscoveranerrorbeforeyoupressRETURN,youcanpressESCAPEtoswitch
toviCommandmode.Thissetupisdifferentfromthestand-alonevi(m)editor'sinitialmode.Whilein
Commandmodeyoucanusemanyvi(m)commandstoeditthecommandline.Itisasthoughyouwere
usingvi(m)toeditacopyofthehistoryfilewithascreenthathasroomforonlyonecommand.Whenyou
usethekcommandortheUPARROWtomoveupaline,youaccessthepreviouscommand.Ifyouthen
usethejcommandortheDOWNARROWtomovedownaline,youwillreturntotheoriginalcommand.
TousethekandjkeystomovebetweencommandsyoumustbeinCommandmode;youcanusethe
ARROWkeysinbothCommandandInputmodes.
tip:Thestand-aloneeditorstartsinCommandmode
Thestand-alonevimeditorstartsinCommandmode,whereasthecommandlinevi(m)
editorstartsinInputmode.Ifcommandsdisplaycharactersanddonotworkproperly,you
areinInputmode.PressESCAPEandenterthecommandagain.
Inadditiontocursor-positioningcommands,youcanusethesearch-backward(?)commandfollowedby
asearchstringtolookbackthroughyourhistorylistforthemostrecentcommandcontainingthatstring.If
youhavemovedbackinyourhistorylist,useaforwardslash(/)tosearchforwardtowardyourmost
recentcommand.Unlikethesearchstringsinthestand-alonevi(m)editor,thesesearchstringscannot
containregularexpressions.Youcan,however,startthesearchstringwithacaret(^)toforcetheshellto
locatecommandsthatstartwiththesearchstring.Asinvi(m),pressingnafterasuccessfulsearchlooks
forthenextoccurrenceofthesamestring.
Youcanalsoaccesseventsinthehistorylistbyusingeventnumbers.WhileyouareinCommandmode
(pressESCAPE),entertheeventnumberfollowedbyaGtogotothecommandwiththateventnumber.
Whenyouuse/,?,orGtomovetoacommandline,youareinCommandmode,notInputmode.Nowyou
caneditthecommandasyoulikeorpressRETURNtoexecuteit.
Oncethecommandyouwanttoeditisdisplayed,youcanmodifythecommandlineusingvi(m)
Commandmodeeditingcommandssuchasx(deletecharacter),r(replacecharacter),~(changecase),
and.(repeatlastchange).TochangetoInputmode,useanInsert(i,I),Append(a,A),Replace(R),or
Change(c,C)command.YoudonothavetoreturntoCommandmodetorunacommand;simplypress
RETURN,evenifthecursorisinthemiddleofthecommandline.
Refertopage188forasummaryofvimcommands.
emacsEditingMode
Unlikethevi(m)editor,emacsismodeless.YouneednotswitchbetweenCommandmodeandInput
modebecausemostemacscommandsarecontrolcharacters(page204),allowingemacstodistinguish
betweeninputandcommands.Likevi(m),theemacscommandlineeditorprovidescommandsfor
movingthecursoronthecommandlineandthroughthecommandhistorylistandformodifyingpartorall
ofacommand.Theemacscommandlineeditorcommandsdifferinafewcasesfromthecommandsin
thestand-aloneemacseditor.
InemacsyouperformcursormovementbyusingbothCONTROLandESCAPEcommands.Tomovethe
cursoronecharacterbackwardonthecommandline,pressCONTROL-B.PressCONTROL-Ftomove
onecharacterforward.Asinvi,youmayprecedethesemovementswithcounts.Touseacountyoumust
firstpressESCAPE;otherwise,thenumbersyoutypewillappearonthecommandline.
Likevi(m),emacsprovideswordandlinemovementcommands.Tomovebackwardorforwardone
wordonthecommandline,pressESCAPEborESCAPEf.Tomoveseveralwordsbyusingacount,
pressESCAPEfollowedbythenumberandtheappropriateescapesequence.Togettothebeginningof
theline,pressCONTROL-A;totheendoftheline,pressCONTROL-E;andtothenextinstanceofthe
characterc,pressCONTROL-XCONTROL-Ffollowedbyc.
Youcanaddtexttothecommandlinebymovingthecursortothecorrectplaceandtypingthedesiredtext.
Todeletetext,movethecursorjusttotherightofthecharactersthatyouwanttodeleteandpressthe
erasekey(page26)onceforeachcharacteryouwanttodelete.
tip:CONTROL-Dcanterminateyourscreensession
Ifyouwanttodeletethecharacterdirectlyunderthecursor,pressCONTROL-D.Ifyou
enterCONTROL-Datthebeginningoftheline,itmayterminateyourshellsession.
Ifyouwanttodeletetheentirecommandline,typethelinekillcharacter(page27).Youcantypethis
characterwhilethecursorisanywhereinthecommandline.Ifyouwanttodeletefromthecursortothe
endoftheline,useCONTROL-K.
Refertopage241forasummaryofemacscommands.
ReadlineCompletionCommands
YoucanusetheTABkeytocompletewordsyouareenteringonthecommandline.Thisfacility,called
completion,worksinbothviandemacseditingmodesandissimilartothecompletionfacility
availableintcsh.Severaltypesofcompletionarepossible,andwhichoneyouusedependsonwhich
partofacommandlineyouaretypingwhenyoupressTAB.
CommandCompletion
Ifyouaretypingthenameofacommand(thefirstwordonthecommandline),pressingTABresultsin
commandcompletion.Thatis,bashlooksforacommandwhosenamestartswiththepartoftheword
youhavetyped.Ifnocommandstartswithwhatyouhaveentered,bashbeeps.Ifthereisonesuch
command,bashcompletesthecommandnameforyou.Ifthereismorethanonechoice,bashdoes
nothinginvimodeandbeepsinemacsmode.PressingTABasecondtimecausesbashtodisplaya
listofcommandswhosenamesstartwiththeprefixyoutypedandallowsyoutofinishtypingthe
commandname.
Inthefollowingexample,theusertypesbzandpressesTAB.Theshellbeeps(theuserisinemacs
mode)toindicatethatseveralcommandsstartwiththelettersbz.TheuserentersanotherTABtocause

theshelltodisplayalistofcommandsthatstartwithbzfollowedbythecommandlineastheuserhad
entereditsofar:
$bz TAB(beep) TAB
bzcatbzdiffbzip2bzless
bzcmpbzgrepbzip2recoverbzmore
$bz
NexttheusertypescandpressesTABtwice.Theshelldisplaysthetwocommandsthatstartwithbzc.
TheusertypesafollowedbyTABandtheshellthencompletesthecommandbecauseonlyonecommand
startswithbzca.
$bzc TAB(beep) TAB
bzcatbzcmp
$bzca TAB t
PathnameCompletion
Pathnamecompletion,whichalsousesTABs,allowsyoutotypeaportionofapathnameandhavebash
supplytherest.Iftheportionofthepathnamethatyouhavetypedissufficienttodetermineaunique
pathname,bashdisplaysthatpathname.Ifmorethanonepathnamewouldmatchit,bashcompletesthe
pathnameuptothepointwheretherearechoicessothatyoucantypemore.
Whenyouareenteringapathname,includingasimplefilename,andpressTAB,theshellbeeps(ifthe
shellisinemacsmodeinvimodethereisnobeep).Itthenextendsthecommandlineasfarasitcan.
$catfilms/dar TAB(beep)catfilms/dark_
Inthefilmsdirectoryeveryfilethatstartswithdarhask_asthenextcharacters,sobashcannotextend
thelinefurtherwithoutmakingachoiceamongfiles.Youareleftwiththecursorjustpastthe_character.

AtthispointyoucancontinuetypingthepathnameorpressTABtwice.Inthelattercasebashbeeps,
displaysyourchoices,redisplaysthecommandline,andagainleavesthecursorjustafterthe_character.
$catfilms/dark_ TAB(beep) TAB
dark_passagedark_victory
$catfilms/dark_
WhenyouaddenoughinformationtodistinguishbetweenthetwopossiblefilesandpressTAB,bash
displaystheuniquepathname.IfyouenterpfollowedbyTABafterthe_character,theshellcompletes
thecommandline:
$catfilms/dark_p TAB assage
Becausethereisnofurtherambiguity,theshellappendsaSPACEsoyoucanfinishtypingthecommand
lineorjustpressRETURNtoexecutethecommand.Ifthecompletepathnameisthatofadirectory,bash
appendsaslash(/)inplaceofaSPACE.
VariableCompletion
Whentypingavariablename,pressingTABresultsinvariablecompletion,wherebashtriesto
completethenameofthevariable.Incaseofanambiguity,pressingTABtwicedisplaysalistofchoices:
$echo$HO TAB TAB
$HOME$HOSTNAME$HOSTTYPE
$echo$HOM TAB E
caution:PressingRETURNexecutesthecommand
PressingRETURNcausestheshelltoexecutethecommandregardlessofwherethecursor
isonthecommandline.

.inputrc:ConfiguringReadline
TheBourneAgainShellandotherprogramsthatusetheReadlineLibraryreadthefilespecifiedbythe
INPUTRCenvironmentvariabletoobtaininitializationinformation.IfINPUTRCisnotset,these
programsreadthe~/.inputrcfile.Theyignorelinesof.inputrcthatareblankorthatstartwithapound
sign(#).
Variables
Youcansetvariablesin.inputrctocontrolthebehavioroftheReadlineLibraryusingthefollowing
syntax:
setvariablevalue
Table8-11listssomevariablesandvaluesyoucanuse.SeeReadlineVariablesinthebashmanor
infopageforacompletelist.
Table8-11.Readlinevariables
Variable Effect
editing-mode
SettovitostartReadlineinvimode.Settoemacstostart
Readlineinemacsmode(thedefault).Similartothesetovi
andsetoemacsshellcommands(page305).
horizontal-scroll-mode
Settoontocauselonglinestoextendofftherightedgeofthe
displayarea.Movingthecursortotherightwhenitisatthe
rightedgeofthedisplayareashiftsthelinetotheleftsoyou
canseemoreoftheline.Youcanshiftthelinebackby
movingthecursorbackpasttheleftedge.Thedefaultvalueis
off,whichcauseslonglinestowrapontomultiplelinesofthe
display.
mark-directories SettoofftocauseReadlinenottoplaceaslash(/)attheend
ofdirectorynamesitcompletes.Normallyitison.
mark-modified-lines SettoontocauseReadlinetoprecedemodifiedhistorylines
withanasterisk.Thedefaultvalueisoff.
KeyBindings
YoucanspecifybindingsthatmapkeystrokesequencestoReadlinecommands,allowingyoutochangeor
extendthedefaultbindings.Asinemacs,theReadlineLibraryincludesmanycommandsthatarenot
boundtoakeystrokesequence.Touseanunboundcommand,youmustmapitusingoneofthefollowing
forms:
keyname:command_name
"keystroke_sequence":command_name
Inthefirstform,youspelloutthenameforasinglekey.Forexample,CONTROL-Uwouldbewrittenas
control-u.Thisformisusefulforbindingcommandstosinglekeys.
Inthesecondform,youspecifyastringthatdescribesasequenceofkeysthatwillbeboundtothe
command.Youcanusetheemacs-stylebackslashescapesequencestorepresentthespecialkeys
CONTROL(\C),META(\M),andESCAPE(\e).Specifyabackslashbyescapingitwithanother
backslash:\\.Similarly,adoubleorsinglequotationmarkcanbeescapedwithabackslash:\"or\'.
Thekill-whole-linecommand,availableinemacsmodeonly,deletesthecurrentline.Putthefollowing
commandin.inputrctobindthekill-whole-linecommand(whichisunboundbydefault)tothekeystroke
sequenceCONTROL-R.
control-r:kill-whole-line
bind
GivethecommandbindPtodisplayalistofallReadlinecommands.Ifacommandisboundtoakey
sequence,thatsequenceisshown.Commandsyoucanuseinvimodestartwithvi.Forexample,vi-next-
wordandvi-prev-wordmovethecursortothebeginningofthenextandpreviouswords,respectively.
Commandsthatdonotbeginwithviaregenerallyavailableinemacsmode.
Usebindqtodeterminewhichkeysequenceisboundtoacommand:
$bind-qkill-whole-line
kill-whole-linecanbeinvokedvia"\C-r".
Youcanalsobindtextbyenclosingitwithindoublequotationmarks(emacsmodeonly):
"QQ":"TheLinuxOperatingSystem"
ThiscommandcausesbashtoinsertthestringTheLinuxOperatingSystemwhenyoutypeQQ.
ConditionalConstructs
Youcanconditionallyselectpartsofthe.inputrcfileusingthe$ifdirective.Thesyntaxoftheconditional
constructis
$if[test[=value]]
commands
[$else
commands
$endif
wheretestismode,term,orbash.Iftestequalsvalueoriftestistrue,thisstructureexecutesthefirst
setofcommands.Iftestdoesnotequalvalueoriftestisfalse,itexecutesthesecondsetofcommands
iftheyarepresentorexitsfromthestructureiftheyarenotpresent.
Thepowerofthe$ifdirectiveliesinthethreetypesoftestsitcanperform.
1. Youcantesttoseewhichmodeiscurrentlyset.
$ifmode=vi
TheprecedingtestistrueifthecurrentReadlinemodeisviandfalseotherwise.Youcantestforvi
oremacs.
2. Youcantestthetypeofterminal.
$ifterm=xterm
TheprecedingtestistrueiftheTERMvariableissettoxterm.Youcantestforanyvalueof
TERM.
3. Youcantesttheapplicationname.
$ifbash
Theprecedingtestistruewhenyouarerunningbashandnotanotherprogramthatusesthe
ReadlineLibrary.Youcantestforanyapplicationname.
ThesetestscancustomizetheReadlineLibrarybasedonthecurrentmode,thetypeofterminal,andthe
applicationyouareusing.TheygiveyouagreatdealofpowerandflexibilitywhenusingtheReadline
Librarywithbashandotherprograms.
Thefollowingcommandsin.inputrccauseCONTROL-Ytomovethecursortothebeginningofthenext
wordregardlessofwhetherbashisinvioremacsmode:
$cat~/.inputrc
setediting-modevi
$ifmode=vi
"\C-y":vi-next-word
$else
"\C-y":forward-word
$endif
Becausebashreadstheprecedingconditionalconstructwhenitisstarted,youmustsettheeditingmode
in.inputrc.ChangingmodesinteractivelyusingsetwillnotchangethebindingofCONTROL-Y.
FormoreinformationontheReadlineLibrary,openthebashmanpageandgivethecommand
/^READLINE,whichsearchesforthewordREADLINEatthebeginningofaline.
tip:IfReadlinecommandsdonotwork,logoutandloginagain
TheBourneAgainShellreads~/.inputrcwhenyoulogin.Afteryoumakechangestothis
file,youshouldlogoutandloginagainbeforetestingthechanges.
Aliases
Analiasisa(usuallyshort)namethattheshelltranslatesintoanother(usuallylonger)nameor(complex)
command.Aliasesallowyoutodefinenewcommandsbysubstitutingastringforthefirsttokenofa
simplecommand.Theyaretypicallyplacedinthe~/.bashrc(bash)or~/.tcshrc(tcsh)startupfilesso
thattheyareavailabletointeractivesubshells.
Underbashthesyntaxofthealiasbuiltinis
alias[name[=value]]
Undertcshthesyntaxis
alias[name[value]]
InthebashsyntaxtherearenoSPACEsaroundtheequalsign.IfvaluecontainsSPACEsorTABs,you
mustenclosevaluebetweenquotationmarks.Unlikealiasesundertcsh,abashaliasdoesnotaccept
anargumentfromthecommandlineinvalue.Useabashfunction(page315)whenyouneedtousean
argument.
Analiasdoesnotreplaceitself,whichavoidsthepossibilityofinfiniterecursioninhandlinganalias
suchasthefollowing:
$aliasls='ls-F'
Youcannestaliases.Aliasesaredisabledfornoninteractiveshells(thatis,shellscripts).Toseealistof
thecurrentaliases,givethecommandalias.Toviewthealiasforaparticularname,usealiasfollowed
bythenameandnothingelse.Youcanusetheunaliasbuiltintoremoveanalias.
Whenyougiveanaliasbuiltinwithoutanyarguments,theshelldisplaysalistofalldefinedaliases:
$alias
aliasll='ls-l'
aliasl='ls-ltr'
aliasls='ls-F'
aliaszap='rm-i'
MostLinuxdistributionsdefineatleastsomealiases.Giveanaliascommandtoseewhichaliasesarein
effect.Youcandeletethealiasesyoudonotwantfromtheappropriatestartupfile.
SingleVersusDoubleQuotationMarksinAliases
Thechoiceofsingleordoublequotationmarksissignificantinthealiassyntaxwhenthealiasincludes
variables.Ifyouenclosevaluewithindoublequotationmarks,anyvariablesthatappearinvalueare
expandedwhenthealiasiscreated.Ifyouenclosevaluewithinsinglequotationmarks,variablesarenot
expandeduntilthealiasisused.Thefollowingexampleillustratesthedifference.
ThePWDkeywordvariableholdsthepathnameoftheworkingdirectory.Alexcreatestwoaliaseswhile
heisworkinginhishomedirectory.BecauseheusesdoublequotationmarkswhenhecreatesthedirA
alias,theshellsubstitutesthevalueoftheworkingdirectorywhenhecreatesthisalias.ThealiasdirA
commanddisplaysthedirAaliasandshowsthatthesubstitutionhasalreadytakenplace:
$echo$PWD
/home/alex
$aliasdirA="echoWorkingdirectoryis$PWD"
$aliasdirA
aliasdirA='echoWorkingdirectoryis/home/alex'
WhenAlexcreatesthedirBalias,heusessinglequotationmarks,whichpreventtheshellfromexpanding
the$PWDvariable.ThealiasdirBcommandshowsthatthedirBaliasstillholdstheunexpanded$PWD
variable:
$aliasdirB='echoWorkingdirectoryis$PWD'
$aliasdirB
aliasdirB='echoWorkingdirectoryis$PWD'
AftercreatingthedirAanddirBaliases,Alexusescdtomakecarshisworkingdirectoryandgiveseach
ofthealiasesascommands.Thealiasthathecreatedwithdoublequotationmarksdisplaysthenameof
thedirectorythathecreatedthealiasinastheworkingdirectory(whichiswrong)andthedirBalias
displaysthepropernameoftheworkingdirectory:
$cdcars
$dirA
Workingdirectoryis/home/alex
$dirB
Workingdirectoryis/home/alex/cars
tip:Howtopreventtheshellfrominvokinganalias
Theshellchecksonlysimple,unquotedcommandstoseeiftheyarealiases.Commands
givenasrelativeorabsolutepathnamesandquotedcommandsarenotchecked.Whenyou
wanttogiveacommandthathasanaliasbutdonotwanttousethealias,precedethe
commandwithabackslash,specifythecommand'sabsolutepathname,orgivethecommand
as./command.
ExamplesofAliases
Thefollowingaliasallowsyoutotypertorepeatthepreviouscommandorrabctorepeatthelast
commandlinethatbeganwithabc:
$aliasr='fc-s'
Ifyouusethecommandlsltrfrequently,youcancreateanaliasthatsubstituteslsltrwhenyougivethe
commandl:
$aliasl='ls-ltr'
$l
total41
-rw-r--r--1alexgroup30015Mar12004flute.ps
-rw-r-----1alexgroup3089Feb112005XTerm.ad
-rw-r--r--1alexgroup641Apr12005fixtax.icn
-rw-r--r--1alexgroup484Apr92005maptax.icn
drwxrwxr-x2alexgroup1024Aug917:41Tiger
drwxrwxr-x2alexgroup1024Sep1011:32testdir
-rwxr-xr-x1alexgroup485Oct2108:03floor
drwxrwxr-x2alexgroup1024Oct2720:19Test_Emacs
Anothercommonuseofaliasesistoprotectyourselffrommistakes.Thefollowingexamplesubstitutes
theinteractiveversionofthermutilitywhenyougivethecommandzap:
$aliaszap='rm-i'
$zapf*
rm:remove'fixtax.icn'?n
rm:remove'flute.ps'?n
rm:remove'floor'?n
Theioptioncausesrmtoaskyoutoverifyeachfilethatwouldbedeleted,tohelpyouavoidaccidentally
deletingthewrongfile.Youcanalsoaliasrmwiththermicommand:aliasrm='rmi'.
ThealiasesinthenextexamplecausetheshelltosubstitutelsleachtimeyougiveanllcommandandlsF
whenyouusels:
$aliasls='ls-F'
$aliasll='ls-l'
$ll
total41
drwxrwxr-x2alexgroup1024Oct2720:19Test_Emacs/
drwxrwxr-x2alexgroup1024Aug917:41Tiger/
-rw-r-----1alexgroup3089Feb112005XTerm.ad
-rw-r--r--1alexgroup641Apr12005fixtax.icn
-rw-r--r--1alexgroup30015Mar12004flute.ps
-rwxr-xr-x1alexgroup485Oct2108:03floor*
-rw-r--r--1alexgroup484Apr92005maptax.icn
drwxrwxr-x2alexgroup1024Sep1011:32testdir/
TheFoptioncauseslstoprintaslash(/)attheendofdirectorynamesandanasterisk(*)attheendof
thenamesofexecutablefiles.Inthisexample,thestringthatreplacesthealiasll(lsl)itselfcontainsan
alias(ls).Whenitreplacesanaliaswithitsvalue,theshelllooksatthefirstwordofthereplacement
stringtoseewhetheritisanalias.Intheprecedingexample,thereplacementstringcontainsthealiasls,
soasecondsubstitutionoccurstoproducethefinalcommandlsFl.(Toavoidarecursiveplunge,thels
inthereplacementtext,althoughanalias,isnotexpandedasecondtime.)
Whengivenalistofaliaseswithoutthe=valueorvaluefield,thealiasbuiltinrespondsbydisplaying
thevalueofeachdefinedalias.Thealiasbuiltinreportsanerrorifanaliashasnotbeendefined:
$aliasllllszapwx
aliasll='ls-l'
aliasl='ls-ltr'
aliasls='ls-F'
aliaszap='rm-i'
bash:alias:wx:notfound
Youcanavoidaliassubstitutionbyprecedingthealiasedcommandwithabackslash(\):
$\ls
Test_EmacsXTerm.adflute.psmaptax.icn
Tigerfixtax.icnfloortestdir
Becausethereplacementofanaliasnamewiththealiasvaluedoesnotchangetherestofthecommand
line,anyargumentsarestillreceivedbythecommandthatgetsexecuted:
$llf*
-rw-r--r--1alexgroup641Apr12005fixtax.icn
-rw-r--r--1alexgroup30015Mar12004flute.ps
-rwxr-xr-x1alexgroup485Oct2108:03floor*
Youcanremoveanaliaswiththeunaliasbuiltin.Whenthezapaliasisremoved,itisnolonger
displayedwiththealiasbuiltinanditssubsequentuseresultsinanerrormessage:
$unaliaszap
$alias
aliasll='ls-l'
aliasl='ls-ltr'
aliasls='ls-F'
$zapmaptax.icn
bash:zap:commandnotfound
Functions
Ashellfunction(tcshdoesnothavefunctions)issimilartoashellscriptinthatitstoresaseriesof
commandsforexecutionatalatertime.However,becausetheshellstoresafunctioninthecomputer's
mainmemory(RAM)insteadofinafileonthedisk,theshellcanaccessitmorequicklythantheshellcan
accessascript.Theshellalsopreprocesses(parses)afunctionsothatitstartsupmorequicklythana
script.Finallytheshellexecutesashellfunctioninthesameshellthatcalledit.Ifyoudefinetoomany
functions,theoverheadofstartingasubshell(aswhenyourunascript)canbecomeunacceptable.
Youcandeclareashellfunctioninthe~/.bash_profilestartupfile,inthescriptthatusesit,ordirectly
fromthecommandline.Youcanremovefunctionswiththeunsetbuiltin.Theshelldoesnotkeep
functionsonceyoulogout.
tip:Removingvariablesandfunctions
Ifyouhaveashellvariableandafunctionwiththesamename,usingunsetremovesthe
shellvariable.Ifyouthenuseunsetagainwiththesamename,itremovesthefunction.
Thesyntaxthatdeclaresashellfunctionis
[function]function-name()
{
commands
}
wherethewordfunctionisoptional,function-nameisthenameyouusetocallthefunction,and
commandscomprisethelistofcommandsthefunctionexecuteswhenyoucallit.Thecommandscanbe
anythingyouwouldincludeinashellscript,includingcallstootherfunctions.
Thefirstbrace({)canappearonthesamelineasthefunctionname.Aliasesandvariablesareexpanded
whenafunctionisread,notwhenitisexecuted.Youcanusethebreakstatement(page459)withina
functiontoterminateitsexecution.
Shellfunctionsareusefulasashorthandaswellastodefinespecialcommands.Thefollowingfunction
startsaprocessnamedprocessinthebackground,withtheoutputnormallydisplayedbyprocessbeing
savedin.process.out:
start_process(){
process>.process.out2>&1&
}
Thenextexampleshowshowtocreateasimplefunctionthatdisplaysthedate,aheader,andalistofthe
peoplewhoareusingthesystem.Thisfunctionrunsthesamecommandsasthewhosonscriptdescribed
onpage264.Inthisexamplethefunctionisbeingenteredfromthekeyboard.Thegreater-than(>)signs
aresecondaryshellprompts(PS2);donotenterthem.
$functionwhoson()
>{
>date
>echo"UsersCurrentlyLoggedOn"
>who
>}
$whoson
SunAug715:44:58PDT2005
UsersCurrentlyLoggedOn
hlsconsoleAug608:59(:0)
alexpts/4Aug609:33(0.0)
jennypts/7Aug609:23(bravo.example.com)
Functionsinstartupfiles
Ifyouwanttohavethewhosonfunctionalwaysbeavailablewithouthavingtoenteriteachtimeyoulog
in,putitsdefinitionin~/.bash_profile.Thenrun.bash_profile,usingthe.(dot)commandtoputthe
changesintoeffectimmediately:
$cat~/.bash_profile
exportTERM=vt100
sttykill'^u'
whoson()
{
date
echo"UsersCurrentlyLoggedOn"
who
}
$.~/.bash_profile
Youcanspecifyargumentswhenyoucallafunction.Withinthefunctiontheseargumentsareavailableas
positionalparameters(page480).Thefollowingexampleshowsthearg1functionenteredfromthe
keyboard.
$arg1(){
>echo"$1"
>}
$arg1first_arg
first_arg
Seethefunctionswitch()onpage259foranotherexampleofafunction."Functions"onpage477
discussestheuseoflocalandglobalvariableswithinafunction.

optional
Thefollowingfunctionallowsyoutoexportvariablesusingtcshsyntax.Theenvbuiltinlistsallenvironmentvariablesandtheir
valuesandverifiesthatsetenvworkedcorrectly:
$cat.bash_profile
...
#setenv-keeptcshusershappy
functionsetenv()
{
if[$#-eq2]
then
eval$1=$2
export$1
else
echo"Usage:setenvNAMEVALUE"1>&2
fi
}
$.~/.bash_profile
$setenvTCL_LIBRARY/usr/local/lib/tcl
$env|grepTCL_LIBRARY
TCL_LIBRARY=/usr/local/lib/tcl
eval
The$#specialparameter(page480)takesonthevalueofthenumberofcommandlinearguments.Thisfunctionusestheeval
builtintoforcebashtoscanthecommand$1=$2twice.Because$1=$2beginswithadollarsign($),theshelltreatstheentire
stringasasingletokenacommand.Withvariablesubstitutionperformed,thecommandnamebecomes
TCL_LIBRARY=/usr/local/lib/tcl,whichresultsinanerror.Usingeval,asecondscanningsplitsthestringintothethree
desiredtokens,andthecorrectassignmentoccurs.

ControllingbashFeaturesandOptions
Thissectionexplainshowtocontrolbashfeaturesandoptionsusingcommandlineoptionsandtheset
andshoptbuiltins.
CommandLineOptions
Twokindsofcommandlineoptionsareavailable:shortandlong.Shortoptionsconsistofahyphen
followedbyaletter;longoptionshavetwohyphensfollowedbymultiplecharacters.Longoptionsmust
appearbeforeshortoptionsonacommandlinethatcallsbash.Table8-12listssomecommonlyused
commandlineoptions.
Table8-12.Commandlineoptions
Option Explanation Syntax
Help Displaysausagemessage. help
Noedit PreventsusersfromusingtheReadlineLibrary(page305)toedit
commandlinesinaninteractiveshell. noediting
No
profile
Preventsreadingthesestartupfiles(page257):/etc/profile,
~/.bash_profile,~/.bash_login,and~/.profile.noprofile
Norc Preventsreadingthe~/.bashrcstartupfile(page258).Thisoptionis
onbydefaultiftheshelliscalledassh.norc
POSIX RunsbashinPOSIXmode. posix
Version Displaysbashversioninformationandexits. version
Login Causesbashtorunasthoughitwerealoginshell. l(lowercase"l")
shopt Runsashellwiththeoptshoptoption(page319).AO(uppercase
"O")setstheoption;+Ounsetsit. [±]O[opt]
Endof
options
Onthecommandline,signalstheendofoptions.Subsequenttokens
aretreatedasargumentseveniftheybeginwithahyphen().
ShellFeatures
YoucancontrolthebehavioroftheBourneAgainShellbyturningfeaturesonandoff.Differentfeatures
usedifferentmethodstoturnfeaturesonandoff.Thesetbuiltincontrolsonegroupoffeatures,whilethe
shoptbuiltincontrolsanothergroup.Youcanalsocontrolmanyfeaturesfromthecommandlineyouuse
tocallbash.
tip:Features,options,variables?
Toavoidconfusingterminology,thisbookreferstothevariousshellbehaviorsthatyoucan
controlasfeatures.Thebashinfopagereferstothemas"options"and"valuesof
variablescontrollingoptionalshellbehavior."
set±o:TurnsShellFeaturesOnandOff
Thesetbuiltin(thereisasetbuiltinintcsh,butitworksdifferently),whenusedwiththeoor+o
option,enables,disables,andlistscertainbashfeatures.Forexample,thefollowingcommandturnson
thenoclobberfeature(page119):
$set-onoclobber
Youcanturnthisfeatureoff(thedefault)bygivingthecommand
$set+onoclobber
Thecommandsetowithoutanoptionlistseachofthefeaturescontrolledbysetfollowedbyitsstate
(onoroff).Thecommandset+owithoutanoptionliststhesamefeaturesinaformthatyoucanuseas
inputtotheshell.Table8-13listsbashfeatures.
Table8-13.bashfeatures
Feature Description Syntax Alternatesyntax
allexport
Automaticallyexportsallvariablesand
functionsthatyoucreateormodifyafter
givingthiscommand.
setoallexport seta
braceexpand Causesbashtoperformbraceexpansion(the setobraceexpand setB
default;page324).
cdspell Correctsminorspellingerrorsindirectory
namesusedasargumentstocd.shoptscdspell
cmdhist
Savesalllinesofamultilinecommandinthe
samehistoryentry,addingsemicolonsas
needed.
shoptscmdhist
dotglob
Causesshellspecialcharacters(wildcards;
page127)inanambiguousfilereferenceto
matchaleadingperiodinafilename.Bydefault
specialcharactersdonottomatchaleading
period.Youmustalwaysspecifythefilenames
.and..explicitlybecausenopatternever
matchesthem.
shoptsdotglob
emacs Specifiesemacseditingmodeforcommand
lineediting(thedefault;page306). setoemacs
errexit Causesbashtoexitwhenasimplecommand
(notacontrolstructure)fails. setoerrexit sete
execfail
Causesashellscripttocontinuerunningwhen
itcannotfindthefilethatisgivenasan
argumenttoexec.Bydefaultascript
terminateswhenexeccannotfindthefilethat
isgivenasitsargument.
shoptsexecfail
expand_aliases
Causesaliases(page312)tobeexpanded(by
defaultitisonforinteractiveshellsandofffor
noninteractiveshells).
shoptsexpand_alias
hashall
Causesbashtorememberwherecommandsit
hasfoundusingPATH(page284)arelocated
(default).
setohashall seth
histappend
Causesbashtoappendthehistorylisttothe
filenamedbyHISTFILE(page295)whenthe
shellexits.Bydefaultbashoverwritesthis
file.
shoptshistappend
histexpand
Causesthehistorymechanism(whichuses
exclamationpoints;page300)towork
(default).Turnthisfeatureofftoturnoff
historyexpansion.
setohistexpand setH
history Enablecommandhistory(onbydefault;page
295). setohistory
ignoreeof
SpecifiesthatbashmustreceivetenEOF
charactersbeforeitexits.Usefulonnoisydial-
uplines.
setoignoreeof
monitor Enablesjobcontrol(onbydefault,page271). setomonitor setm
nocaseglob
Causesambiguousfilereferences(page127)
tomatchfilenameswithoutregardtocase(off
bydefault).
shoptsnocaseglob
noclobber Helpspreventoverwritingfiles(offbydefault;
page119). setonoclobber setC
noglob Disablespathnameexpansion(offbydefault;
page127). setonoglob setf
notify
Withjobcontrol(page271)enabled,reports
theterminationstatusofbackgroundjobs
immediately.Thedefaultbehavioristodisplay
thestatusjustbeforethenextprompt.
setonotify setb
nounset
Displaysanerrorandexitsfromashellscript
whenyouuseanunsetvariableinan
interactiveshell.Thedefaultistodisplayanull
valueforanunsetvariable.
setonounset setu
nullglob
Causesbashtoexpandambiguousfile
references(page127)thatdonotmatcha
filenametoanullstring.Bydefaultbash
passesthesefilereferenceswithoutexpanding
them.
shoptsnullglob
posix RunsbashinPOSIXmode. setoposix
verbose Displayscommandlinesasbashreadsthem. setoverbose setv
vi Specifiesvieditingmodeforcommandline
editing(page305). setovi
xpg_echo
Causestheechobuiltintoexpandbackslash
escapesequenceswithouttheneedforthee
option(page463).
shoptsxpg_echo
xtrace Turnsonshelldebugging(page448). setoxtrace setx
shopt:TurnsShellFeaturesOnandOff
Theshopt(shelloption)builtin(notavailableintcsh)enables,disables,andlistscertainbash
featuresthatcontrolthebehavioroftheshell.Forexample,thefollowingcommandcausesbashto
includefilenamesthatbeginwithaperiod(.)whenitexpandsambiguousfilereferences(thesstandsfor
set):
$shopt-sdotglob
Youcanturnthisfeatureoff(thedefault)bygivingthecommand(theustandsforunset)
$shopt-udotglob
Theshelldisplayshowafeatureissetifyougivethenameofthefeatureastheonlyargumenttoshopt:
$shoptdotglob
dotgloboff
Thecommandshoptwithoutanyoptionsorargumentsliststhefeaturescontrolledbyshoptandtheir
state.Thecommandshoptswithoutanargumentliststhefeaturescontrolledbyshoptthataresetoron.
Thecommandshoptuliststhefeaturesthatareunsetoroff.Table8-13listsbashfeatures.
tip:Settingset±ofeaturesusingshopt
Youcanuseshopttoset/unsetfeaturesthatareotherwisecontrolledbyset±o.Usethe
regularshoptsyntaxwithsoruandincludetheooption.Forexample,thefollowing
commandturnsonthenoclobberfeature:
$shopt-o-snoclobber
ProcessingTheCommandLine
Whetheryouareworkinginteractivelyorrunningashellscript,bashneedstoreadacommandline
beforeitcanstartprocessingitbashalwaysreadsatleastonelinebeforeprocessingacommand.Some
bashbuiltins,suchasifandcase,aswellasfunctionsandquotedstrings,spanmultiplelines.When
bashrecognizesacommandthatcoversmorethanoneline,itreadstheentirecommandbefore
processingit.Ininteractivesessionsbashpromptsyouwiththesecondaryprompt(PS2,>bydefault;
page287)asyoutypeeachlineofamultilinecommanduntilitrecognizestheendofthecommand:
$echo'hi
>end'
hi
end
$functionhello(){
>echohellothere
>}
$
Afterreadingacommandline,bashapplieshistoryexpansionandaliassubstitutiontotheline.
HistoryExpansion
"ReexecutingandEditingCommands"onpage297discussesthecommandsyoucangivetomodifyand
reexecutecommandlinesfromthehistorylist.Historyexpansionistheprocessthatbashusestoturna
historycommandintoanexecutablecommandline.Forexample,whenyougivethecommand!!,history
expansionchangesthatcommandlinesoitisthesameasthepreviousone.Historyexpansionisturnedon
bydefaultforinteractiveshells;set+ohistexpandturnsitoff.Historyexpansiondoesnotapplyto
noninteractiveshells(shellscripts).
AliasSubstitution
Aliases(page312)substituteastringforthefirstwordofasimplecommand.Bydefaultaliasesare
turnedonforinteractiveshellsandofffornoninteractiveshells.Givethecommandshoptu
expand_aliasestoturnaliasesoff.
ParsingandScanningtheCommandLine
Afterprocessinghistorycommandsandaliases,bashdoesnotexecutethecommandimmediately.Oneof
thefirstthingstheshelldoesistoparse(isolatestringsofcharactersin)thecommandlineintotokensor
words.Theshellthenscanseachtokenforspecialcharactersandpatternsthatinstructtheshelltotake
certainactions.Theseactionscaninvolvesubstitutingonewordorwordsforanother.Whentheshell
parsesthefollowingcommandline,itbreaksitintothreetokens(cp,~/letter,and.):
$cp~/letter.
Afterseparatingtokensandbeforeexecutingthecommand,theshellscansthetokensandperforms
commandlineexpansion.
CommandLineExpansion
Inbothinteractiveandnoninteractiveuse,theshelltransformsthecommandlineusingcommandline
expansionbeforepassingthecommandlinetotheprogrambeingcalled.Youcanuseashellwithout
knowingmuchaboutcommandlineexpansion,butyoucanusewhatashellhastooffertoabetter
advantagewithanunderstandingofthistopic.ThissectioncoversBourneAgainShellcommandline
expansion;TCShellcommandlineexpansioniscoveredstartingonpage344.
TheBourneAgainShellscanseachtokenforthevarioustypesofexpansionandsubstitutioninthe
followingorder.Mostoftheseprocessesexpandawordintoasingleword.Onlybraceexpansion,word
splitting,andpathnameexpansioncanchangethenumberofwordsinacommand(exceptforthe
expansionofthevariable"$@"page482).
1. Braceexpansion(page324)
2. Tildeexpansion(page326)
3. Parameterandvariableexpansion(page326)
4. Arithmeticexpansion(page327)
5. Commandsubstitution(page329)
6. Wordsplitting(page330)
7. Pathnameexpansion(page330)
8. Processsubstitution(page332)
Quoteremoval
Afterbashfinisheswiththeprecedinglist,itremovesfromthecommandlinesinglequotationmarks,
doublequotationmarks,andbackslashesthatarenotaresultofanexpansion.Thisprocessiscalled
quoteremoval.
OrderofExpansion
Theorderinwhichbashcarriesoutthesestepsaffectstheinterpretationofcommands.Forexample,if
yousetavariabletoavaluethatlooksliketheinstructionforoutputredirectionandthenenteracommand
thatusesthevariable'svaluetoperformredirection,youmightexpectbashtoredirecttheoutput.
$SENDIT=">/tmp/saveit"
$echoxxx$SENDIT
xxx>/tmp/saveit
$cat/tmp/saveit
cat:/tmp/saveit:Nosuchfileordirectory
Infact,theshelldoesnotredirecttheoutputitrecognizesinputandoutputredirectionbeforeitevaluates
variables.Whenitexecutesthecommandline,theshellchecksforredirectionand,findingnone,
evaluatestheSENDITvariable.Afterreplacingthevariablewith>/tmp/saveit,bashpassesthe
argumentstoecho,whichdutifullycopiesitsargumentstostandardoutput.No/tmp/saveitfileis
created.
Thefollowingsectionsprovidemoredetaileddescriptionsofthestepsinvolvedincommandprocessing.
Keepinmindthatdoubleandsinglequotationmarkscausetheshelltobehavedifferentlywhen
performingexpansions.Doublequotationmarkspermitparameterandvariableexpansionbutsuppress
othertypesofexpansion.Singlequotationmarkssuppressalltypesofexpansion.
BraceExpansion
Braceexpansion,whichoriginatedintheCShell,providesaconvenientwaytospecifyfilenameswhen
pathnameexpansiondoesnotapply.Althoughbraceexpansionisalmostalwaysusedtospecify
filenames,themechanismcanbeusedtogeneratearbitrarystrings;theshelldoesnotattempttomatchthe
bracenotationwiththenamesofexistingfiles.
Braceexpansionisturnedonininteractiveandnoninteractiveshellsbydefault;youcanturnitoffwith
set+obraceexpand.Theshellalsousesbracestoisolatevariablenames(page280).
Thefollowingexampleillustrateshowbraceexpansionworks.Thelscommanddoesnotdisplayany
outputbecausetherearenofilesintheworkingdirectory.Theechobuiltindisplaysthestringsthatthe
shellgenerateswithbraceexpansion.Inthiscasethestringsdonotmatchfilenames(therearenofilesin
theworkingdirectory.)
$ls
$echochap_{one,two,three}.txt
chap_one.txtchap_two.txtchap_three.txt
Theshellexpandsthecomma-separatedstringsinsidethebracesintheechocommandintoaSPACE-
separatedlistofstrings.Eachstringfromthelistisprependedwiththestringchap_,calledthepreamble,
andappendedwiththestring.txt,calledthepostscript.Boththepreambleandthepostscriptareoptional.
Theleft-to-rightorderofthestringswithinthebracesispreservedintheexpansion.Fortheshelltotreat
theleftandrightbracesspeciallyandforbraceexpansiontooccur,atleastonecommaandnounquoted
whitespacecharactersmustbeinsidethebraces.Youcannestbraceexpansions.
Braceexpansionisusefulwhenthereisalongpreambleorpostscript.Thefollowingexamplecopiesthe
fourfilesmain.c,f1.c,f2.c,andtmp.clocatedinthe/usr/local/src/Cdirectorytotheworkingdirectory:
$cp/usr/local/src/C/{main,f1,f2,tmp}.c.
Youcanalsousebraceexpansiontocreatedirectorieswithrelatednames:
$ls-F
file1file2file3
$mkdirvrs{A,B,C,D,E}
$ls-F
file1file2file3vrsA/vrsB/vrsC/vrsD/vrsE/
TheFoptioncauseslstodisplayaslash(/)afteradirectoryandanasterisk(*)afteranexecutablefile.
Ifyoutriedtouseanambiguousfilereferenceinsteadofbracestospecifythedirectories,theresult
wouldbedifferent(andnotwhatyouwanted):
$rmdirvrs*
$mkdirvrs[A-E]
$ls-F
file1file2file3vrs[A-E]/
Anambiguousfilereferencematchesthenamesofexistingfiles.Becauseitfoundnofilenamesmatching
vrs[AE],bashpassedtheambiguousfilereferencetomkdir,whichcreatedadirectorywiththatname.
Page130hasadiscussionofbracketsinambiguousfilereferences.
TildeExpansion
Chapter4(page89)showedashorthandnotationtospecifyyourhomedirectoryorthehomedirectoryof
anotheruser.Thissectionprovidesamoredetailedexplanationoftildeexpansion.
Thetilde(~)isaspecialcharacterwhenitappearsatthestartofatokenonacommandline.Whenitsees
atildeinthisposition,bashlooksatthefollowingstringofcharactersuptothefirstslash(/)ortothe
endofthewordifthereisnoslashasapossibleloginname.Ifthispossibleloginnameisnull(thatis,if
thetildeappearsasawordbyitselforifitisimmediatelyfollowedbyaslash),theshellsubstitutesthe
valueoftheHOMEvariableforthetilde.Thefollowingexampledemonstratesthisexpansion,wherethe
lastcommandcopiesthefilenamedletterfromAlex'shomedirectorytotheworkingdirectory:
$echo$HOME
/home/alex
$echo~
/home/alex
$echo~/letter
/home/alex/letter
$cp~/letter.
Ifthestringofcharactersfollowingthetildeformsavalidloginname,theshellsubstitutesthepathofthe
homedirectoryassociatedwiththatloginnameforthetildeandname.Ifitisnotnullandnotavalidlogin
name,theshelldoesnotmakeanysubstitution:
$echo~jenny
/home/jenny
$echo~root
/root
$echo~xx
~xx
Tildesarealsousedindirectorystackmanipulation(page274).Inaddition,~+isasynonymforPWD
(thenameoftheworkingdirectory),and~isasynonymforOLDPWD(thenameoftheprevious
workingdirectory).
ParameterandVariableExpansion
Onacommandlineadollarsign($)thatisnotfollowedbyanopenparenthesisintroducesparameteror
variableexpansion.Parametersincludecommandline,orpositional,parameters(page480)andspecial
parameters(page478).Variablesincludeuser-createdvariables(page278)andkeywordvariables(page
283).Thebashmanandinfopagesdonotmakethisdistinction,however.
Parametersandvariablesarenotexpandediftheyareenclosedwithinsinglequotationmarksorifthe
leadingdollarsignisescaped(precededwithabackslash).Iftheyareenclosedwithindoublequotation
marks,theshellexpandsparametersandvariables.
ArithmeticExpansion
Theshellperformsarithmeticexpansionbyevaluatinganarithmeticexpressionandreplacingitwiththe
result.Seepage358forinformationonarithmeticexpansionundertcsh.Underbashthesyntaxfor
arithmeticexpansionis
$((expression))
Theshellevaluatesexpressionandreplaces$((expression))withtheresultoftheevaluation.Thissyntax
issimilartothesyntaxusedforcommandsubstitution[$(...)]andperformsaparallelfunction.Youcan
use$((expression))asanargumenttoacommandorinplaceofanynumericvalueonacommandline.
TherulesforformingexpressionarethesameasthosefoundintheCprogramminglanguage;allstandard
Carithmeticoperatorsareavailable(seeTable11-8onpage505).Arithmeticinbashisdoneusing
integers.Unlessyouusevariablesoftypeinteger(page283)oractualintegers,however,theshellmust
convertstring-valuedvariablestointegersforthepurposeofthearithmeticevaluation.
Youdonotneedtoprecedevariablenameswithinexpressionwithadollarsign($).Inthefollowing
example,anarithmeticexpressiondetermineshowmanyyearsareleftuntilage60:
$catage_check
#!/bin/bash
echo-n"Howoldareyou?"
readage
echo"Wow,in$((60-age))years,you'llbe60!"
$age_check
Howoldareyou?55
Wow,in5years,you'llbe60!
Youdonotneedtoenclosetheexpressionwithinquotationmarksbecausebashdoesnotperform
filenameexpansiononit.Thisfeaturemakesiteasierforyoutouseanasterisk(*)formultiplication,as
thefollowingexampleshows:
$echoThereare$((60*60*24*365))secondsinanon-leapyear.
Thereare31536000secondsinanon-leapyear.
Thenextexampleuseswc,cut,arithmeticexpansion,andcommandsubstitutiontoestimatethenumber
ofpagesrequiredtoprintthecontentsofthefileletter.txt.Theoutputofthewcutility(page816)used
withtheloptionisthenumberoflinesinthefile,incolumns1through4,followedbyaSPACEandthe
nameofthefile(thefirstcommandfollowing).Thecututility(page627)withthec1-4optionextracts
thefirstfourcolumns.
tip:Fewerdollarsigns($)
Whenyouusevariableswithin$((and)),thedollarsignsthatprecedeindividualvariable
referencesareoptional:
$x=23y=37
$echo$((2*$x+3*$y))
157
$echo$((2*x+3*y))
157
$wc-lletter.txt
351letter.txt
$wc-lletter.txt|cut-c1-4
351
Thedollarsignandsingleparenthesisinstructtheshelltoperformcommandsubstitution;thedollarsign
anddoubleparenthesesindicatearithmeticexpansion:
$echo$(($(wc-lletter.txt|cut-c1-4)/66+1))
6
Theprecedingexamplesendsstandardoutputfromwctostandardinputofcutviaapipe.Becauseof
commandsubstitution,theoutputofbothcommandsreplacesthecommandsbetweenthe$(andthe
matching)onthecommandline.Arithmeticexpansionthendividesthisnumberby66,thenumberoflines
onapage.A1isaddedattheendbecausetheintegerdivisionresultsinanyremainderbeingdiscarded.
Anotherwaytogetthesameresultwithoutusingcutistoredirecttheinputtowcinsteadofhavingwc
getitsinputfromafileyounameonthecommandline.Whenyouredirectitsinput,wcdoesnotdisplay
thenameofthefile:
$wc-l<letter.txt
351
Itiscommonpracticetoassigntheresultofarithmeticexpansiontoavariable:
$numpages=$(($(wc-l<letter.txt)/66+1))
letbuiltin
Theletbuiltin(notavailableintcsh)evaluatesarithmeticexpressionsjustasthe$(())syntaxdoes.
Thefollowingcommandisequivalenttotheprecedingone:
$let"numpages=$(wc-l<letter.txt)/66+1"
ThedoublequotationmarkskeeptheSPACEs(boththoseyoucanseeandthosethatresultfromthe
commandsubstitution)fromseparatingtheexpressionintoseparateargumentstolet.Thevalueofthe
lastexpressiondeterminestheexitstatusoflet.Ifthevalueofthelastexpressionis0,theexitstatusof
letis1;otherwise,theexitstatusis0.
Youcangivemultipleargumentstoletonasinglecommandline:
$leta=5+3b=7+2
$echo$a$b
89
Whenyourefertovariableswhendoingarithmeticexpansionwithletor$(()),theshelldoesnot
requireyoutobeginthevariablenamewithadollarsign($).Nevertheless,itisagoodpracticetodoso,
asinmostplacesyoumustincludethissymbol.
CommandSubstitution
Commandsubstitutionreplacesacommandwiththeoutputofthatcommand.Thepreferredsyntaxfor
commandsubstitutionunderbashfollows:
$(command)
Underbashyoucanalsousethefollowingsyntax,whichistheonlysyntaxallowedundertcsh:
'command'
Theshellexecutescommandwithinasubshellandreplacescommand,alongwiththesurrounding
punctuation,withstandardoutputofcommand.
Inthefollowingexample,theshellexecutespwdandsubstitutestheoutputofthecommandforthe
commandandsurroundingpunctuation.Thentheshellpassestheoutputofthecommand,whichisnowan
argument,toecho,whichdisplaysit.
$echo$(pwd)
/home/alex
Thenextscriptassignstheoutputofthepwdbuiltintothevariablewhereanddisplaysamessage
containingthevalueofthisvariable:
$catwhere
where=$(pwd)
echo"Youareusingthe$wheredirectory."
$where
Youareusingthe/home/jennydirectory.
Althoughitillustrateshowtoassigntheoutputofacommandtoavariable,thisexampleisnotrealistic.
Youcanmoredirectlydisplaytheoutputofpwdwithoutusingavariable:
$catwhere2
echo"Youareusingthe$(pwd)directory."
$where2
Youareusingthe/home/jennydirectory.
ThefollowingcommandusesfindtolocatefileswiththenameREADMEinthedirectorytreewithits
rootattheworkingdirectory.Thislistoffilesisstandardoutputoffindandbecomesthelistof
argumentstols.
$ls-l$(find.-nameREADME-print)
Thenextcommandlineshowstheolder'command'syntax:
$ls-l'find.-nameREADME-print'
Oneadvantageofthenewersyntaxisthatitavoidstheratherarcanerulesfortokenhandling,quotation
markhandling,andescapedbacktickswithintheoldsyntax.Anotheradvantageofthenewsyntaxisthatit
canbenested,unliketheoldsyntax.Forexample,youcanproducealonglistingofallREADMEfiles
whosesizeexceedsthesizeof./READMEwiththefollowingcommand:
$ls-l$(find.-nameREADME-size+$(echo$(cat./README|wc-c)c
)-print)
Trygivingthiscommandaftergivingasetxcommand(page448)toseehowbashexpandsit.Ifthereis
noREADMEfile,youjustgettheoutputoflsl.
Foradditionalscriptsthatusecommandsubstitution,seepages444,464,and496.
tip:$((Versus$(
Thesymbols$((constituteaseparatetoken.Theyintroduceanarithmeticexpression,nota
commandsubstitution.Thus,ifyouwanttouseaparenthesizedsubshell(page270)within
$(),youmustinsertaSPACEbetweenthe$(andthenext(.
WordSplitting
Theresultsofparameterandvariableexpansion,commandsubstitution,andarithmeticexpansionare
candidatesforwordsplitting.UsingeachcharacterofIFS(page288)asapossibledelimiter,bash
splitsthesecandidatesintowordsortokens.IfIFSisunset,bashusesitsdefaultvalue(SPACE-TAB-
NEWLINE).IfIFSisnull,bashdoesnotsplitwords.
PathnameExpansion
Pathnameexpansion(page127),alsocalledfilenamegenerationorglobbing,istheprocessof
interpretingambiguousfilereferencesandsubstitutingtheappropriatelistoffilenames.Unlessnoglob
(page321)isset,theshellperformsthisfunctionwhenitencountersanambiguousfilereferenceatoken
containinganyoftheunquotedcharacters*,?,[,or].Ifbashcannotlocateanyfilesthatmatchthe
specifiedpattern,thetokenwiththeambiguousfilereferenceisleftalone.Theshelldoesnotdeletethe
tokenorreplaceitwithanullstringbutratherpassesittotheprogramasis(exceptseenullglob,page
322).TheTCShellgeneratesanerrormessage.
Inthefirstechocommandinthefollowingexample,theshellexpandstheambiguousfilereferencetmp*
andpassesthreetokens(tmp1,tmp2,andtmp3)toecho.Theechobuiltindisplaysthethreefilenames
itwaspassedbytheshell.Afterrmremovesthethreetmp*files,theshellfindsnofilenamesthatmatch
tmp*whenittriestoexpandit.Thusitpassestheunexpandedstringtotheechobuiltin,whichdisplays
thestringitwaspassed.
$ls
tmp1tmp2tmp3
$echotmp*
tmp1tmp2tmp3
$rmtmp*
$echotmp*
tmp*
BydefaultthesamecommandcausestheTCShelltodisplayanerrormessage:
tcsh$echotmp*
echo:Nomatch
Aperiodthateitherstartsapathnameorfollowsaslash(/)inapathnamemustbematchedexplicitly
unlessyouhavesetdotglob(page320).Theoptionnocaseglob(page321)causesambiguousfile
referencestomatchfilenameswithoutregardtocase.
Quotationmarks
Puttingdoublequotationmarksaroundanargumentcausestheshelltosuppresspathnameandallother
expansionexceptparameterandvariableexpansion.Puttingsinglequotationmarksaroundanargument
suppressesalltypesofexpansion.Thesecondechocommandinthefollowingexampleshowsthe
variable$alexbetweendoublequotationmarks,whichallowvariableexpansion.Asaresulttheshell
expandsthevariabletoitsvalue:sonar.Thisexpansiondoesnotoccurinthethirdechocommand,
whichusessinglequotationmarks.Becauseneithersinglenordoublequotationmarksallowpathname
expansion,thelasttwocommandsdisplaytheunexpandedargumenttmp*.
$echotmp*$alex
tmp1tmp2tmp3sonar
$echo"tmp*$alex"
tmp*sonar
$echo'tmp*$alex'
tmp*$alex
Theshelldistinguishesbetweenthevalueofavariableandareferencetothevariableanddoesnot
expandambiguousfilereferencesiftheyoccurinthevalueofavariable.Asaconsequenceyoucan
assigntoavariableavaluethatincludesspecialcharacters,suchasanasterisk(*).
Levelsofexpansion
Inthenextexample,theworkingdirectoryhasthreefileswhosenamesbeginwithletter.Whenyou
assignthevalueletter*tothevariablevar,theshelldoesnotexpandtheambiguousfilereference
becauseitoccursinthevalueofavariable(intheassignmentstatementforthevariable).Noquotation
markssurroundthestringletter*;contextalonepreventstheexpansion.Aftertheassignmenttheset
builtin(withthehelpofgrep)showsthevalueofvartobeletter*.
Thethreeechocommandsdemonstratethreelevelsofexpansion.When$varisquotedwithsingle
quotationmarks,theshellperformsnoexpansionandpassesthecharacterstring$vartoecho,which
displaysit.Whenyouusedoublequotationmarks,theshellperformsvariableexpansiononlyand
substitutesthevalueofthevarvariableforitsname,precededbyadollarsign.Nopathnameexpansionis
performedonthiscommandbecausedoublequotationmarkssuppressit.Inthefinalcommand,theshell,
withoutthelimitationsofquotationmarks,performsvariablesubstitutionandthenpathnameexpansion
beforepassingtheargumentstoecho.
$lsletter*
letter1letter2letter3
$var=letter*
$set|grepvar
var='letter*'
$echo'$var'
$var
$echo"$var"
letter*
$echo$var
letter1letter2letter3
ProcessSubstitution
AspecialfeatureoftheBourneAgainShellistheabilitytoreplacefilenameargumentswithprocesses.
Anargumentwiththesyntax<(command)causescommandtobeexecutedandtheoutputwrittentoa
namedpipe(FIFO).Theshellreplacesthatargumentwiththenameofthepipe.Ifthatargumentisthen
usedasthenameofaninputfileduringprocessing,theoutputofcommandisread.Similarlyanargument
withthesyntax>(command)isreplacedbythenameofapipethatcommandreadsasstandardinput.
Thefollowingexampleusessort(page762)withthem(merge,whichworkscorrectlyonlyiftheinput
filesarealreadysorted)optiontocombinetwowordlistsintoasinglelist.Eachwordlistisgenerated
byapipethatextractswordsmatchingapatternfromafileandsortsthewordsinthatlist.
$sort-m-f<(grep"[^A-Z]..$"memo1|sort)<(grep".*aba.*"memo2
|sort)
ChapterSummary
Theshellisbothacommandinterpreterandaprogramminglanguage.Asacommandinterpreter,theshell
executescommandsyouenterinresponsetoitsprompt.Asaprogramminglanguage,theshellexecutes
commandsfromfilescalledshellscripts.Whenyoustartashell,ittypicallyrunsoneormorestartup
files.
Runningashellscript
Assumingthatthefileholdingashellscriptisintheworkingdirectory,therearethreebasicwaysto
executetheshellscriptfromthecommandline.
1. Typethesimplefilenameofthefilethatholdsthescript.
2. Typearelativepathname,includingthesimplefilenameprecededby./.
3. Typebashortcshfollowedbythenameofthefile.
Technique1requiresthattheworkingdirectorybeinthePATHvariable.Techniques1and2requirethat
youhaveexecuteandreadpermissionforthefileholdingthescript.Technique3requiresthatyouhave
readpermissionforthefileholdingthescript.
Jobcontrol
Ajobisoneormorecommandsconnectedbypipes.Youcanbringajobrunninginthebackgroundinto
theforegroundbyusingthefgbuiltin.Youcanputaforegroundjobintothebackgroundbyusingthebg
builtin,providedthatyoufirstsuspendthejobbypressingthesuspendkey(typicallyCONTROL-Z).Use
thejobsbuiltintoseewhichjobsarerunningorsuspended.
Variables
Theshellallowsyoutodefinevariables.Youcandeclareandinitializeavariablebyassigningavalueto
it;youcanremoveavariabledeclarationbyusingunset.Variablesarelocaltoaprocessunlessthey
areexportedusingtheexport(bash)orsetenv(tcsh)builtintomakethemavailabletochild
processes.Variablesyoudeclarearecalleduser-createdvariables.Theshellalsodefinescalled
keywordvariables.Withinashellscriptyoucanworkwiththecommandline(positional)parametersthe
scriptwascalledwith.
Process
Eachprocesshasauniqueidentification(PID)numberandistheexecutionofasingleLinuxcommand.
Whenyougiveitacommand,theshellforksanew(child)processtoexecutethecommand,unlessthe
commandisbuiltintotheshell(page132).Whilethechildprocessisrunning,theshellisinastatecalled
sleep.Byendingacommandlinewithanampersand(&),youcanrunachildprocessinthebackground
andbypassthesleepstatesothattheshellpromptreturnsimmediatelyafteryoupressRETURN.Each
commandinashellscriptforksaseparateprocess,eachofwhichmayinturnforkotherprocesses.When
aprocessterminates,itreturnsitsexitstatustoitsparentprocess.Anexitstatusofzerosignifiessuccess
andnonzerosignifiesfailure.
History
Thehistorymechanism,afeatureadaptedfromtheCShell,maintainsalistofrecentlyissuedcommand
lines,alsocalledevents,thatprovidesawaytoreexecutepreviouscommandsquickly.Thereareseveral
waystoworkwiththehistorylist;oneoftheeasiestistouseacommandlineeditor.
Commandlineeditors
WhenusinganinteractiveBourneAgainShell,youcanedityourcommandlineandcommandsfromthe
historyfile,usingeitheroftheBourneAgainShell'scommandlineeditors(vi[m]oremacs).Whenyou
usethevi(m)commandlineeditor,youstartinInputmode,unlikethewayyounormallyentervi(m).You
canswitchbetweenCommandandInputmodes.Theemacseditorismodelessanddistinguishes
commandsfromeditorinputbyrecognizingcontrolcharactersascommands.
Aliases
Analiasisanamethattheshelltranslatesintoanothernameor(complex)command.Aliasesallowyouto
definenewcommandsbysubstitutingastringforthefirsttokenofasimplecommand.TheBourneAgain
andTCShellsusedifferentsyntaxestodefineanalias,butaliasesinbothshellsworksimilarly.
Functions
Ashellfunctionisaseriesofcommandsthat,unlikeashellscript,areparsedpriortobeingstoredin
memorysothattheyrunfasterthanshellscripts.Shellscriptsareparsedatruntimeandarestoredon
disk.Afunctioncanbedefinedonthecommandlineorwithinashellscript.Ifyouwantthefunction
definitiontoremainineffectacrossloginsessions,youcandefineitinastartupfile.Likethefunctionsof
aprogramminglanguage,ashellfunctioniscalledbygivingitsnamefollowedbyanyarguments.
Shellfeatures
Thereareseveralwaystocustomizetheshell'sbehavior.Youcanuseoptionsonthecommandlinewhen
youcallbashandyoucanusethebashsetandshoptbuiltinstoturnfeaturesonandoff.
Commandlineexpansion
Whenitprocessesacommandline,theBourneAgainShellmayreplacesomewordswithexpandedtext.
Mosttypesofcommandlineexpansionareinvokedbytheappearanceofaspecialcharacterwithina
word(forexample,aleadingdollarsigndenotesavariable).SeeTable8-6onpage291foralistof
specialcharacters.Theexpansionstakeplaceinaspecificorder.Followingthehistoryandalias
expansions,thecommonexpansionsareparameterandvariableexpansion,commandsubstitution,and
pathnameexpansion.Surroundingawordwithdoublequotationmarkssuppressesalltypesofexpansion
exceptparameterandvariableexpansion.Singlequotationmarkssuppressalltypesofexpansion,asdoes
quoting(escaping)aspecialcharacterbyprecedingitwithabackslash.

Exercises
1.
Explainthefollowingunexpectedresult:
$whereisdate
date:/bin/date
$echo$PATH
.:/usr/local/bin:/usr/bin:/bin
$cat>date
echo"Thisismyownversionofdate."
$date
TueMay2411:45:49PDT2005
2. Whataretwowaysyoucanexecuteashellscriptwhenyoudonothaveexecuteaccesspermissionforthefilecontainingthescript?
Canyouexecuteashellscriptifyoudonothavereadaccesspermissionforthefilecontainingthescript?
3.
WhatisthepurposeofthePATHvariable?
1. SetthePATHvariablesothatitcausestheshelltosearchthefollowingdirectoriesinorder:
/usr/local/bin
/usr/bin/X11
/usr/bin
/bin
/usr/kerberos/bin
Thebindirectoryinyourhomedirectory
Theworkingdirectory
2. Ifthereisafilenameddoitin/usr/binandanotherfilewiththesamenameinyour~/bin,whichonewillbeexecuted?(Assume
thatyouhaveexecutepermissionforbothfiles.)
3. IfyourPATHvariableisnotsettosearchtheworkingdirectory,howcanyouexecuteaprogramlocatedthere?
4. Whichcommandcanyouusetoaddthedirectory/usr/gamestotheendofthelistofdirectoriesinPATH?
4.
Assumethatyouhavemadethefollowingassignment:
$person=jenny
Givetheoutputofeachofthefollowingcommands:
1. echo$person
2. echo'$person'
3. echo"$person"
5.
Thefollowingshellscriptaddsentriestoafilenamedjournal-fileinyourhomedirectory.Thisscripthelpsyoukeeptrackofphone
conversationsandmeetings.
$catjournal
#journal:addjournalentriestothefile
#$HOME/journal-file
file=$HOME/journal-file
date>>$file
echo-n"Enternameofpersonorgroup:"
readname
echo"$name">>$file
echo>>$file
cat>>$file
echo"----------------------------------------------------">>$file
echo>>$file
1. Whatdoyouhavetodotothescripttobeabletoexecuteit?
2. Whydoesthescriptusethereadbuiltin(page487)thefirsttimeitacceptsinputfromtheterminalandthecatutilitythe
secondtime?
6.
Assumethatthe/home/jenny/grants/bibliosand/home/jenny/bibliosdirectoriesexist.GiveJenny'sworkingdirectoryaftershe
executeseachsequenceofcommandsgiven.Explainwhathappensineachcase.
1.
$pwd
/home/jenny/grants
$CDPATH=$(pwd)
$cd
$cdbiblios
2.
$pwd
/home/jenny/grants
$CDPATH=$(pwd)
$cd$HOME/biblios
7. NametwowaysyoucanidentifythePIDnumberofyourloginshell.
8.
Givethefollowingcommand:
$sleep30|cat/etc/inittab
Isthereanyoutputfromsleep?Wheredoescatgetitsinputfrom?Whathastohappenbeforetheshelldisplaysanotherprompt?
AdvancedExercises
9. Writeasequenceofcommandsorascriptthatdemonstratesthatvariableexpansionoccursbeforepathnameexpansion.
10. Writeashellscriptthatoutputsthenameoftheshellthatisexecutingit.
11.
Explainthebehaviorofthefollowingshellscript:
$catquote_demo
twoliner="Thisisline1.
Thisisline2."
echo"$twoliner"
echo$twoliner
1. Howmanyargumentsdoeseachechocommandseeinthisscript?Explain.
2. RedefinetheIFSshellvariablesothattheoutputofthesecondechoisthesameasthefirst.
12.
Addtheexitstatusofthepreviouscommandtoyourpromptsothatitbehavessimilarlytothefollowing:
$[0]lsxxx
ls:xxx:Nosuchfileordirectory
$[1]
13.
Thedirnameutilitytreatsitsargumentasapathnameandwritestostandardoutputthepathprefixthatis,everythinguptobutnot
includingthelastcomponent:
$dirnamea/b/c/d
a/b/c
Ifyougivedirnameasimplefilename(no/characters)asanargument,dirnamewritesa.tostandardoutput:
$dirnamesimple
.
Implementdirnameasabashfunction.Makesurethatitbehavessensiblywhengivensuchargumentsas/.
14.
Implementthebasenameutility,whichwritesthelastcomponentofitspathnameargumenttostandardoutput,asabashfunction.For
example,giventhepathnamea/b/c/d,basenamewritesdtostandardoutput:
$basenamea/b/c/d
d
15.
TheLinuxbasenameutilityhasanoptionalsecondargument.Ifyougivethecommandbasenamepathsuffix,basenameremoves
thesuffixandtheprefixfrompath:
$basenamesrc/shellfiles/prog.bash.bash
prog
$basenamesrc/shellfiles/prog.bash.c
prog.bash
Addthisfeaturetothefunctionyouwroteforexercise14.
Chapter9.TheTcShell
INTHISCHAPTER
ShellScripts340
EnteringandLeavingtheTCShell341
FeaturesCommontotheBourneAgainandTCShells343
RedirectingStandardError349
WordCompletion350
EditingtheCommandLine353
Variables355
ReadingUserInput361
ControlStructures368
Builtins377
TheTCShell(tcsh)performsthesamefunctionastheBourneAgainShellandothershells:Itprovides
aninterfacebetweenyouandtheLinuxoperatingsystem.TheTCShellisaninteractivecommand
interpreteraswellasahigh-levelprogramminglanguage.Althoughyouuseonlyoneshellatanygiven
time,youshouldbeabletoswitchbackandforthcomfortablybetweenshellsastheneedarises(youmay
wanttorundifferentshellsindifferentwindows).Chapters8and11applytotcshaswellastobash
sotheyprovideagoodbackgroundforthischapter.Thischapterexplainstcshfeaturesthatarenot
foundinbashandthosethatareimplementeddifferentlyfromtheirbashcounterparts.Thetcshhome
pageiswww.tcsh.org.
TheTCShellisanexpandedversionoftheCShell(csh),whichoriginatedonBerkeleyUNIX.The"T"
inTCShellcomesfromtheTENEXandTOPS-20operatingsystems,whichinspiredcommand
completionandotherfeaturesintheTCShell.Anumberoffeaturesnotfoundincsharepresentin
tcsh,includingfileandusernamecompletion,commandlineediting,andspellingcorrection.Aswith
csh,youcancustomizetcshtomakeitmoretolerantofmistakesandeasiertouse.Bysettingthe
propershellvariables,youcanhavetcshwarnyouwhenyouappeartobeaccidentallyloggingoutor
overwritingafile.ManypopularfeaturesoftheoriginalCShellarenowsharedbybashandtcsh.
Assignmentstatement
Althoughsomeofthefunctionalityoftcshispresentinbash,differencesariseinthesyntaxofsome
commands.Forexample,thetcshassignmentstatementhasthefollowingsyntax:
setvariable=value
HavingSPACEsoneithersideoftheequalsign,althoughillegalinbash,isallowedintcsh.By
conventionshellvariablesintcsharegenerallynamedwithlowercaseletters,notuppercase(youcan
useeither).Ifyoureferenceanundeclaredvariable(onethathashadnovalueassignedtoit),tcshwill
giveyouanerrormessage,whereasbashwillnot.Finallythedefaulttcshpromptisagreaterthansign
(>),butitisfrequentlysettoasingle$characterfollowedbyaSPACE.Theexamplesinthischapteruse
apromptoftcsh$toavoidconfusionwiththebashprompt.
tip:Donotusetcshasaprogramminglanguage
IfyouhaveusedUNIXandarecomfortablewiththeCorTCShell,youmaywanttouse
tcshasyourloginshell.However,youmayfindthattheTCShellisnotasgooda
programminglanguageasbash.Ifyouaregoingtolearnonlyoneshellprogramming
language,learnbash.TheBourneAgainShellisusedthroughoutLinuxtoprogrammany
systemadministrationscripts.
ShellScripts
WithtcshyoucanexecutefilescontainingTCShellcommands,justasbashcanexecutefiles
containingBourneAgainShellcommands.Theconceptsofwritingandexecutingscriptsinthetwoshells
aresimilar.However,themethodsofdeclaringandassigningvaluestovariablesandthesyntaxofcontrol
structuresaredifferent.
Youcanrunbashandtcshscriptswhileusinganyoneoftheshellsasacommandinterpreter.Various
methodsexistforselectingtheshellthatrunsascript.Referto"#!SpecifiesaShell"onpage265for
moreinformation.
Ifthefirstcharacterofashellscriptisapoundsign(#)andthefollowingcharacterisnotanexclamation
point(!),theTCShellexecutesthescriptundertcsh.Ifthefirstcharacterisanythingotherthan#,tcsh
callstheshlinktobashtoexecutethescript.
tip:echo:gettingridoftheRETURN
Thetcshechobuiltinacceptseitheranoptionoratrailing\ctogetridofthe
RETURNthatechonormallydisplaysattheendofaline.Thebashechobuiltin
acceptsonlythenoption(referto"read:AcceptsUserInput"onpage487).
tip:Shellgame
WhenyouareworkingwithaninteractiveTCShell,ifyourunascriptinwhich#isnotthe
firstcharacterofthescriptandyoucallthescriptdirectly(withoutprecedingitsnamewith
tcsh),tcshcallstheshlinktobashtorunthescript.Thefollowingscriptwaswritten
toberunundertcshbut,whencalledfromatcshcommandline,isexecutedbybash.
Thesetbuiltin(page484)worksdifferentlyunderbashandtcsh.Asaresultthe
followingexample(frompage361)issuesapromptbutdoesnotwaitforyoutorespond:
tcsh$catuser_in
echo-n"Enterinput:"
setinput_line="$<"
echo$input_line
tcsh$user_in
Enterinput:
Althoughineachcasetheexamplesarerunfromatcshcommandline,thefollowingone
callstcshexplicitlysothattcshexecutesthescriptanditrunscorrectly.
tcsh$tcshuser_in
Enterinput:hereissomeinput
hereissomeinput
EnteringandLeavingtheTCShell
chsh
Youcanexecutetcshbygivingthecommandtcsh.Ifyouarenotsurewhichshellyouareusing,usethe
psutilitytofindout.Itshowswhetheryouarerunningtcsh,bash,sh(linkedtobash),orpossibly
anothershell.Thefingercommandfollowedbyyourusernamedisplaysthenameofyourloginshell,
whichisstoredinthe/etc/passwdfile.Ifyouwanttousetcshasamatterofcourse,youcanusethe
chsh(changeshell)utilitytochangeyourloginshell:
bash$chsh
Changingshellforsam.
Password:
Newshell[/bin/bash]:/bin/tcsh
Shellchanged.
bash$
Theshellyouspecifywillbeineffectforyournextloginandallsubsequentloginsuntilyouspecifya
differentloginshell.The/etc/passwdfilestoresthenameofyourloginshell.
Youcanleavetcshinseveralways.Theapproachyouchoosedependsontwofactors:whetherthe
shellvariableignoreeofissetandwhetheryouareusingtheshellthatyouloggedinon(yourloginshell)
oranothershellthatyoucreatedafteryouloggedin.Ifyouarenotsurehowtoexitfromtcsh,press
CONTROL-DonalinebyitselfwithnoleadingSPACEs,justasyouwouldtoterminatestandardinputto
anotherprogram.Youwilleitherexitorreceiveinstructionsonhowtoexit.Ifyouhavenotsetignoreeof
(page366)andithasnotbeensetforyouinastartupfile,youcanexitfromanyshellbyusing
CONTROL-D(thesameprocedureyouusetoexitfromtheBourneAgainShell).
Whenignoreeofisset,CONTROL-Ddoesnotwork.Theignoreeofvariablecausestheshelltodisplaya
messagetellingyouhowtoexit.Youcanalwaysexitfromtcshbygivinganexitcommand.Alogout
commandallowsyoutoexitfromyourloginshellonly.
StartupFiles
WhenyouloginontheTCShell,itautomaticallyexecutesvariousstartupfiles.Thesefilesarenormally
executedintheorderdescribedinthissection,butyoucancompiletcshsothatitusesadifferentorder.
Youmusthavereadaccesstoastartupfiletoexecutethecommandsinit.
/etc/csh.cshrcand/etc/csh.login
Theshellfirstexecutesthecommandsin/etc/csh.cshrcand/etc/csh.login.Superusercansetupthese
filestoestablishsystemwidedefaultcharacteristicsfortcshusers.Theycontainsystemwide
configurationinformation,suchasthedefaultpath,thelocationtocheckformail,andsoon.
.tcshrcand.cshrc
Nexttheshelllooksfor~/.tcshrcor,ifitdoesnotexist,~/.cshrc(~/isshorthandforyourhome
directory).Youcanusethesefilestoestablishvariablesandparametersthatarelocaltoyourshell.Each
timeyoucreateanewshell,tcshreinitializesthesevariablesforthenewshell.Thefollowing.tcshrc
filesetsseveralshellvariables,establishestwoaliases(page347),andaddstwonewdirectoriesto
pathoneatthestartofthelistandoneattheend:
tcsh$cat~/.tcshrc
setnoclobber
setdunique
setignoreeof
sethistory=256
setpath=(~/bin$path/usr/games)
aliashhistory
aliasllls-l
.history
Loginshellsrebuildthehistorylistfromthecontentsof~/.history.Ifthehistfilevariableexists,tcsh
usesthefilethathistfilepointstoinplaceof.history.
.login
Loginshellsreadandexecutethecommandsin~/.login.Thisfilecontainscommandsthatyouwantto
executeonce,atthebeginningofeachsession.Youcanusesetenv(page356)todeclareenvironment
(global)variableshere.Youcanalsodeclarethetypeofterminalyouareusingandsetsometerminal
characteristicsinyour.loginfile.
tcsh$cat~/.login
setenvhistory200
setenvmail/var/spool/mail/$user
if(-z$DISPLAY)then
setenvTERMvt100
else
setenvTERMxterm
endif
sttyerase'^h'kill'^u'-lcasetab3
date'+Loginon%A%B%dat%I:%M%p'
Thepreceding.loginfileestablishesthetypeofterminalyouareusingbysettingtheTERMvariable(the
ifstatement[page368]determineswhetheryouareusingagraphicalinterfaceandthereforewhatvalue

shouldbeassignedtoTERM).Itthenrunsstty(page778)tosetterminalcharacteristicsanddate
(page630)todisplaythetimeyouloggedin.
/etc/csh.logoutand.logout
TheTCShellrunsthe/etc/csh.logoutand~/.logoutfiles,inthatorder,whenyouexitfromaloginshell.
Thefollowingsample.logoutfileusesdatetodisplaythetimeyouloggedout.Thesleepcommand
ensuresthatechohastimetodisplaythemessagebeforethesystemlogsyouout.Thedelaymaybe
usefulfordial-uplinesthattakesometimetodisplaythemessage.
tcsh$cat~/.logout
date'+Logouton%A%B%dat%I:%M%p'
sleep5
FeaturesCommontotheBourneAgainandTCShells
MostofthefeaturescommontobothbashandtcsharederivedfromtheoriginalCShell:
Commandlineexpansion(alsocalledsubstitution;page344)
History(page344)
Aliases(page347)
Jobcontrol(page348)
Filenamesubstitution(page348)
Directorystackmanipulation(page349)
Commandsubstitution(page349)
Becausethechaptersonbashdiscussthesefeaturesindetail,thissectionfocusesonthedifferences
betweenthebashandtcshimplementations.
CommandLineExpansion(Substitution)
Referto"ProcessingtheCommandLine"onpage322foranintroductiontocommandlineexpansionin
theBourneAgainShell.Thetcshmanpageusesthetermsubstitutioninsteadofexpansion,whichis
usedbybash.TheTCShellscanseachtokenforpossibleexpansioninthefollowingorder:
1. Historysubstitution(page344)
2. Aliassubstitution(page347)
3. Variablesubstitution(page356)
4. Commandsubstitution(page349)
5. Filenamesubstitution(page348)
6. Directorystacksubstitution(page349)
History
TheTCShellassignsasequentialeventnumbertoeachcommandline.Youcandisplaythiseventnumber
aspartofthetcshprompt(referto"prompt"onpage363).Examplesinthissectionshownumbered
promptswhentheyhelpillustratethebehaviorofacommand.
historyBuiltin
Asinbash,thetcshhistorybuiltindisplaystheeventsinyourhistorylist.Thelistofeventsis
orderedwiththeoldesteventsatthetop.Thelasteventinthehistorylististhehistorycommandthat
displayedthelist.Inthefollowinghistorylist,whichislimitedtotenlinesbytheargumentof10tothe
historycommand,command23modifiesthetcshprompttodisplaythehistoryeventnumber.Thetime
eachcommandwasexecutedappearstotherightoftheeventnumber.
32$history10
2323:59setprompt="!$"
2423:59ls-l
2523:59cattemp
260:00rmtemp
270:00vimmemo

280:00lprmemo
290:00vimmemo
300:00lprmemo
310:00rmmemo
320:00history
HistoryExpansion
Thesameeventandworddesignatorsworkinbothshells.Forexample,!!referstothepreviouseventin
tcsh,justasitdoesinbash.Thecommand!328executeseventnumber328and!?txt?executesthe
mostrecenteventcontainingthestringtxt.Formoreinformationreferto"UsinganExclamationPoint(!)
toReferenceEvents"onpage300.Table9-1liststhefewtcshwordmodifiersnotfoundinbash.
Table9-1.Wordmodifiers
Modifier Function
uConvertsthefirstlowercaseletterintouppercase
lConvertsthefirstuppercaseletterintolowercase
aAppliesthenextmodifiergloballywithinasingleword
Youcanusemorethanonewordmodifierinacommand.Forinstance,theamodifier,incombination
withtheuorlmodifier,enablesyoutochangethecaseofanentireword.
tcsh$echo$VERSION
VERSION:Undefinedvariable.
tcsh$echo!!:1:al
echo$version

tcsh6.12.00(Astron)2002-07-23(i386-intel-linux)options
8b,nls,...
Inadditiontousingeventdesignatorstoaccessthehistorylist,youcanusethecommandlineeditorto
access,modify,andexecutepreviouscommands(page353).
Variables
Thevariablesthatyousettocontrolhistoryintcsharedifferentfromthoseusedinbash.Whereas
bashusesHISTSIZEandHISTFILESIZEtodeterminethenumberofeventsthatarepreservedduring
andbetweensessions,tcshuseshistoryandsavehist(Table9-2)forthesepurposes.
Table9-2.Historyvariables
Variable Default Function
history 100events Maximumnumberofeventssavedduringasession
histfile ~/.history Locationofthehistoryfile
savehist notset Maximumnumberofeventssavedbetweensessions
historyandsavehist
Whenyouexitfromatcshshell,themostrecentlyexecutedcommandsaresavedinyour~/.historyfile.
Thenexttimeyoustarttheshellthisfileinitializesthehistorylist.Thevalueofthesavehistvariable
determinesthenumberoflinessavedinthe.historyfile(notnecessarilythesameasthehistory
variable).Ifsavehistisnotset,tcshdoesnotsavehistorybetweensessions.Thehistoryandsavehist
variablesmustbelocal(declaredwithset,notsetenv).Thehistoryvariableholdsthenumberof
eventsrememberedduringasessionandthesavehistvariableholdsthenumberrememberedbetween
sessions.SeeTable9-2.
Ifyousetthevalueofhistorytoohigh,itcanusetoomuchmemory.Ifitisunsetorsettozero,theshell
doesnotsaveanycommands.Toestablishahistorylistofthe500mostrecentevents,givethefollowing
commandmanuallyorplaceitinyour~/.tcshrcstartupfile:
tcsh$sethistory=500
Thefollowingcommandcausestcshtosavethe200mostrecenteventsacrossloginsessions:
tcsh$setsavehist=200
Youcancombinethesetwoassignmentsintoasinglecommand:
tcsh$sethistory=500savehist=200
Afteryousetsavehistyoucanlogoutandloginagain,andthe200mostrecenteventsfromtheprevious
loginsessionswillappearinyourhistorylist.Setsavehistinyour~/.tcshrcfileifyouwanttomaintain
youreventlistfromlogintologin.
histlit
Ifyousetthevariablehistlit(historyliteral),historydisplaysthecommandsinthehistorylistexactly
astheyweretypedinwithoutanyshellinterpretation.Thefollowingexampleshowstheeffectofthis
variable(comparethelinesnumbered32):
tcsh$cat/etc/csh.cshrc
...
tcsh$cp!!:1~
cp/etc/csh.cshrc~
tcsh$sethistlit
tcsh$history
...
319:35cat/etc/csh.cshrc
329:35cp!!:1~
339:35sethistlit
349:35history
tcsh$unsethistlit
tcsh$history
...
319:35cat/etc/csh.cshrc
329:35cp/etc/csh.cshrc~
339:35sethistlit
349:35history
359:35unsethistlit
369:36history

optional
Thereisadifferenceinhowbashandtcshexpandhistoryeventdesignators.Ifyougivethecommand!250w,bashreplacesit
withcommandnumber250withacharacterwappendedtoit.Incontrast,tcshlooksbackthroughyourhistorylistforanevent
thatbeginswiththestring250wtoexecute.Thereasonforthedifference:bashinterpretsthefirstthreecharactersof250was
thenumberofacommand,whereastcshinterpretsthosecharactersaspartofthesearchstring250w.(Ifthe250standsalone,
tcshtreatsitasacommandnumber.)
Ifyouwanttoappendwtocommandnumber250,youcaninsulatetheeventnumberfromthewbysurroundingitwithbraces:
!{250}w
Aliases
Thealias/unaliasfeatureintcshcloselyresemblesitscounterpartinbash(page312).However,
thealiasbuiltinhasaslightlydifferentsyntax:
aliasnamevalue
Thefollowingcommandcreatesanaliasforls:
tcsh$aliasls"ls-lF"
Thetcshaliasallowsyoutosubstitutecommandlinearguments,whereasbashdoesnot:
$aliasnam"echoHello,\!^ismyname"
$namSam
Hello,Samismyname
Thestring\!*withinanaliasexpandstoallcommandlinearguments:

$aliassortprint"sort\!*|lpr"
Thenextaliasdisplaysitssecondargument:
$aliasn2"echo\!:2"
SpecialAliases
Somealiasnames,calledspecialaliases,havespecialmeaningtotcsh.Ifyoudefineanaliaswithone
ofthesenames,tcshexecutesitautomaticallyasexplainedinTable9-3.Initiallyallspecialaliasesare
undefined.
Table9-3.Specialaliases
Alias Whenexecuted
beepcmd Whenevertheshellwouldnormallyringtheterminalbell.Givesyouawayto
haveothervisualoraudioeffectstakeplaceatthosetimes.
cwdcmd Wheneveryouchangetoanotherworkingdirectory.
periodic Periodically,asdeterminedbythenumberofminutesinthetperiodvariable.If
tperiodisunsetorhasthevalue0,periodichasnomeaning.
precmd Justbeforetheshelldisplaysaprompt.
shell Givestheabsolutepathnameoftheshellthatyouwanttousetorunscriptsthat
donotstartwith#!(page265).
Toseealistofcurrentaliases,givethecommandalias.Toviewthealiasforaparticularname,givethe
commandaliasfollowedbythename.
HistorySubstitutionInAliases
Youcansubstitutecommandlineargumentsbyusingthehistorymechanism,whereasingleexclamation
pointrepresentsthecommandlinecontainingthealias.Modifiersarethesameasthoseusedby
history(page300).Inthefollowingexample,theexclamationpointsarequotedsothattheshelldoes
notinterpretthemwhenbuildingthealiases:
21$aliaslastecho\!:$
22$lastthisisjustatest
test
23$aliasfn2echo\!:2:t
24$fn2/home/jenny/test/home/alex/temp/home/barbara/new
temp
Event21definesforlastanaliasthatdisplaysthelastargument.Event23definesforfn2analiasthat
displaysthesimplefilename,ortail,ofthesecondargumentonthecommandline.
JobControl
Jobcontrolissimilarinbothbash(page271)andtcsh.Youcanmovecommandsbetweenthe
foregroundandbackground,suspendjobstemporarily,andgetalistofthecurrentjobs.The%character
referencesajobwhenfollowedbyajobnumberorastringprefixthatuniquelyidentifiesthejob.You
willseeaminordifferencewhenyourunamultiple-processcommandlineinthebackgroundfromeach
shell.WhereasbashdisplaysonlythePIDnumberofthelastbackgroundprocessineachjob,tcsh
displaysthenumbersforallprocessesbelongingtoajob.Theexamplefrompage271lookslikethis
undertcsh:
tcsh$find.-print|sort|lpr&grep-lalex/tmp/*>alexfiles&
[1]188391884018841
[2]18876
FilenameSubstitution
TheTCShellexpandsthecharacters*,?,and[]inapathnamejustasbashdoes(page127).The*
matchesanystringofzeroormorecharacters,?matchesanysinglecharacter,and[]definesacharacter
class,whichisusedtomatchsinglecharactersappearingwithinapairofbrackets.
TheTCShellexpandscommandlineargumentsthatstartwithatilde(~)intofilenamesinmuchthesame
waythatbashdoes(page351),withthe~standingfortheuser'shomedirectoryorthehomedirectoryof
theuserwhosenamefollowsthetilde.Thebashspecialexpansions~+and~arenotavailablein
tcsh.
Braceexpansion(page324)isavailableintcsh.Liketildeexpansion,itisregardedasanaspectof
filenamesubstitutioneventhoughbraceexpansioncangeneratestringsthatarenotthenamesofactual
files.
Intcshanditspredecessorcsh,theprocessofusingpatternstomatchfilenamesisreferredtoas
globbingandthepatternitselfiscalledaglobbingpattern.Iftcshisunabletoidentifyoneormore
filesthatmatchaglobbingpattern,itreportsanerror(unlessthepatterncontainsabrace).Settingthe
shellvariablenoglobsuppressesfilenamesubstitution,includingbothtildeandbraceinterpretation.
ManipulatingtheDirectoryStack
Directorystackmanipulationintcshdoesnotdiffermuchfromthatinbash(page274).Thedirs
builtindisplaysthecontentsofthestack,andthepushdandpopdbuiltinspushdirectoriesontoandpop
directoriesoffofthestack.
CommandSubstitution
The$(...)formatforcommandsubstitutionisnotavailableintcsh.Initsplaceyoumustusetheoriginal
'...'format.Otherwise,theimplementationinbashandtcshisidentical.Refertopage329formore
informationoncommandsubstitution.
RedirectingStandardError
Bothbashandtcshuseagreaterthansymbol(>)toredirectstandardoutput,buttcshdoesnotuse
thebashnotation2>toredirectstandarderror.Undertcshyouuseagreaterthansymbolfollowedby
anampersand(>&)tocombineandredirectstandardoutputandstandarderror.Althoughyoucanusethis
notationunderbash,itisnotcommon.Thefollowingexamples,likethebashexamplesonpage261,
referencefilex,whichdoesnotexist,andfiley,whichcontainsasingleline.
tcsh$catx
cat:x:Nosuchfileordirectory
tcsh$caty
Thisisy.
tcsh$catxy>&hold
tcsh$cathold
cat:x:Nosuchfileordirectory
Thisisy.
Withanargumentofyintheprecedingexample,catsendsastringtostandardoutput.Anargumentofx
causescattosendanerrormessagetostandarderror.
Unlikebash,tcshdoesnotprovideasimplewaytoredirectstandarderrorseparatelyfromstandard
output.Awork-aroundfrequentlyprovidesareasonablesolution.Thefollowingexamplerunscatwith
argumentsofxandyinasubshell(theparenthesesensurethatthecommandwithinthemrunsina
subshellseepage270).Alsowithinthesubshella>redirectsstandardoutputtothefileoutfile.Output
senttostandarderrorisnottouchedbythesubshellbutratherissenttotheparentshell,wherebothitand
standardoutputaresenttoerrfile.Becausestandardoutputhasalreadybeenredirected,errfilecontains
onlyoutputsenttostandarderror.
tcsh$(catxy>outfile)>&errfile
tcsh$catoutfile
Thisisy.
tcsh$caterrfile
cat:x:Nosuchfileordirectory
Itcanbeusefultocombineandredirectoutputwhenyouwanttorunaslowcommandinthebackground
anddonotwantitsoutputclutteringuptheterminalscreen.Forexample,becausethefindutility(page
655)oftentakessometimetocomplete,itmaybeagoodideatorunitinthebackground.Thenext
commandfindsinthefilesystemhierarchyallfilesthatcontainthestringbibliointheirname.The
commandrunsinthebackgroundandsendsitsoutputtothefindoutfile.Becausethefindutilitysends
tostandarderrorareportofdirectoriesthatyoudonothavepermissiontosearch,thefindoutfile
containsarecordofanyfilesthatarefoundaswellasarecordofthedirectoriesthatcouldnotbe
searched.
tcsh$find/-name"*biblio*"-print>&findout&
Inthisexample,ifyoudidnotcombinestandarderrorwithstandardoutputandredirectedonlystandard
output,theerrormessageswouldappearonthescreenandfindoutwouldlistonlyfilesthatwerefound.
Whileacommandthathasitsoutputredirectedtoafileisrunninginthebackground,youcanlookatthe
outputbyusingtail(page783)withthefoption.Thefoptioncausestailtodisplaynewlinesas
theyarewrittentothefile:
tcsh$tail-ffindout
Toterminatethetailcommand,presstheinterruptkey(usuallyCONTROL-C).
WorkingwiththeCommandLine
Thissectioncoverswordcompletion,editingthecommandline,andcorrectingspelling.
WordCompletion
TheTCShellcompletesfilenames,commands,andvariablenamesonthecommandlinewhenyouprompt
ittodoso.Thegenerictermusedtorefertoallthesefeaturesundertcshiswordcompletion.
FilenameCompletion
TheTCShellcancompleteafilenameafteryouspecifyauniqueprefix.Filenamecompletionissimilar
tofilenamegeneration,butthegoaloffilenamecompletionistoselectasinglefile.Togethertheymakeit
practicaltouselong,descriptivefilenames.
Tousefilenamecompletionwhenyouareenteringafilenameonthecommandline,typeenoughofthe
nametoidentifythefileinthedirectoryuniquelyandpressTAB;tcshfillsinthenameandaddsa
SPACE,leavingthecursorsoyoucanenteradditionalargumentsorpressRETURN.Inthefollowing
example,theusertypesthecommandcattrig1AandpressesTAB;thesystemfillsintherestofthe

filenamethatbeginswithtrig1A:
tcsh$cattrig1A TAB cattrig1A.302488
Iftwoormorefilenamesmatchtheprefixthatyouhavetyped,tcshcannotcompletethefilename
withoutobtainingmoreinformationfromyou.Theshellattemptstomaximizethelengthoftheprefixby
addingcharacters,ifpossible,andthenbeepstosignifythatadditionalinputisneededtoresolvethe
ambiguity:
tcsh$lsh*
help.histhelp.trig01help.txt
tcsh$cath TAB cathelp.(beep)
YoucanfillinenoughcharacterstoresolvetheambiguityandthenpresstheTABkeyagain.Alternatively,
youcanpressCONTROL-Dtocausetcshtodisplayalistofmatchingfilenames:
tcsh$cathelp. CONTROL-D
help.histhelp.trig01help.txt
tcsh$cathelp.
Afterdisplayingthefilenamestcshredrawsthecommandlinesoyoucandisambiguatethefilename
(andpressTABagain)orfinishtypingthefilenamemanually.
TildeCompletion
TheTCShellparsesatilde(~)appearingasthefirstcharacterofawordandattemptstoexpandittoa
usernamewhenyouenteraTAB:
tcsh$cd~al TAB cd~alex/ RETURN
tcsh$pwd

/home/alex
Byappendingaslash(/),tcshindicatesthatthecompletedwordisadirectory.Theslashalsomakesit
easytocontinuespecifyingthepathname.
CommandandVariableCompletion
Youcanusethesamemechanismthatyouusetolistandcompletefilenameswithcommandandvariable
names.Unlessyougiveafullpathname,theshellusesthevariablepathinanattempttocompletea
commandname.Thechoiceslistedarelikelytobelocatedindifferentdirectories.
tcsh$up TAB(beep) CONTROL-D
up2dateupdatedbuptime
up2date-configupdate-mime-database
up2date-noxupdmap
tcsh$up t TAB uptime RETURN
9:59amup31days,15:11,7users,loadaverage:0.03,0.02,0.00
Ifyousettheautolistvariableasinthefollowingexample,theshelllistschoicesautomaticallywhenyou
invokecompletionbypressingTAB.YoudonothavetopressCONTROL-D.
tcsh$setautolist
tcsh$up TAB(beep)
up2dateupdatedbuptime
up2date-configupdate-mime-database
up2date-noxupdmap

tcsh$up t TAB uptime RETURN
10:01amup31days,15:14,7users,loadaverage:0.20,0.06,0.02
Ifyousetautolisttoambiguous,theshellliststhechoiceswhenyoupressTABonlyifthewordyou
enteristhelongestprefixofasetofcommands.Otherwise,pressingTABcausestheshelltoaddoneor
morecharacterstotheworduntilitisthelongestprefix;pressingTABagainthenliststhechoices:
tcsh$setautolist=ambiguous
tcsh$echo$h TAB(beep)
histfilehistoryhome
tcsh$echo$h i TAB echo$hist TAB
histfilehistory
tcsh$echo$hist o TAB echo$history RETURN
1000
Theshellmustrelyonthecontextofthewordwithintheinputlinetodeterminewhetheritisafilename,a
username,acommand,oravariablename.Thefirstwordonaninputlineisassumedtobeacommand
name;ifawordbeginswiththespecialcharacter$,itisviewedasavariablename;andsoon.Inthe
followingexample,thesecondwhichcommanddoesnotworkproperly:Thecontextofthewordup
makesitlooklikethebeginningofafilenameratherthanthebeginningofacommand.TheTCShell
supplieswhichwithanargumentofupdates(anonexecutablefile)andwhichdisplaysanerror
message:
tcsh$lsup*
updates
tcsh$whichupdatedbupsuptime

/usr/bin/updatedb
/usr/local/bin/ups
/usr/bin/uptime
tcsh$whichup TAB whichupdates
updates:Commandnotfound.
EditingtheCommandLine
bindkey
Thetcshcommandlineeditingfeatureissimilartothatavailableunderbash.Youcanuseeither
emacsmodecommands(default)orvi(m)modecommands.Changetovi(m)modecommandsbyusing
bindkeyvandtoemacsmodecommandsbyusingbindkeye.TheARROWkeysareboundtothe
obviousmotioncommandsinbothmodes,soyoucanmovebackandforth(upanddown)throughyour
historylistaswellasleftandrightonthecurrentcommandline.
Withoutanargument,thebindkeybuiltindisplaysthecurrentmappingsbetweeneditorcommandsand
thekeysequencesyoucanenteratthekeyboard:
tcsh$bindkey
Standardkeybindings
"^@"->set-mark-command
"^A"->beginning-of-line
"^B"->backward-char
"^C"->tty-sigintr
"^D"->delete-char-or-list-or-eof
...
Multi-characterbindings
"^[[A"->up-history
"^[[B"->down-history
"^[[C"->forward-char
"^[[D"->backward-char
"^[[H"->beginning-of-line
"^[[F"->end-of-line
...
Arrowkeybindings
down->down-history
up->up-history
left->backward-char
right->forward-char
home->beginning-of-line
end->end-of-line
The^indicatesaCONTROLcharacter(^B=CONTROL-B).The^[indicatesaMETAorALT
character;youpressandholdtheMETAorALTkeywhileyoupressthekeyforthenextcharacter.Ifthis
substitutiondoesnotworkorifthekeyboardyouareusingdoesnothaveaMETAorALTkey,pressand
releasetheESCAPEkeyandthenpressthekeyforthenextcharacter.For^[[FyouwouldpressMETA-[
orALT-[followedbytheFkeyorelseESCAPE[F).Thedown/up/left/rightindicateARROWkeys,
andhome/endindicatetheHOMEandENDkeysonthenumerickeypad.
Theprecedingexampleshowstheoutputfrombindkeywiththeuserinemacsmode.Changetovi(m)
mode(bindkeyv)andgiveanotherbindkeycommandtodisplaythevi(m)keybindings.Youcanpipe
theoutputofbindkeythroughlesstomakeiteasiertoreadthelist.
CorrectingSpelling

Youcanhavetcshattempttocorrectthespellingofcommandnames,filenames,andvariables(butonly
usingemacs-stylekeybindings).Spellingcorrectioncantakeplaceonlyattwotimes:beforeandafter
youpressRETURN.
beforeyoupressreturn
FortcshtocorrectawordorlinebeforeyoupressRETURN,youmustindicatethatyouwantittodo
so.Thetwofunctionsforthispurposearespell-lineandspell-word:
$bindkey|grepspell
"^[$"->spell-line
"^[S"->spell-word
"^[s"->spell-word
Theoutputfrombindkeyshowsthatspell-lineisboundtoMETA-$(ALT-$orESCAPE$)andspell-
wordisboundtoMETA-SandMETA-s(ALT-sorESCAPEsandALT-SorESCAPES).Tocorrectthe
spellingofthewordtotheleftofthecursor,enterMETA-s.EnteringMETA-$invokesthespell-line
function,whichattemptstocorrectallwordsonacommandline:
tcsh$ls
bigfile.gz
tcsh$gunzipp META-s gunzipbigfele.gz META-s gunzip
bigfile.gz
tcsh$gunzipbigfele.gz META-$ gunzipbigfile.gz
tcsh$ecno$usfr META-$ echo$user
AfterYouPressReturn
Thevariablenamedcorrectcontrolswhattcshattemptstocorrectorcompleteafteryoupress
RETURNandbeforeitpassesthecommandlinetothecommandbeingcalled.Ifyoudonotsetcorrect,
tcshwillnotcorrectanything:
tcsh$unsetcorrect
tcsh$lsmorning
morning
tcsh$ecno$usfrmorbing
usfr:Undefinedvariable.
Theshellreportstheerrorinthevariablenameandnotthecommandnamebecauseitexpandsvariables
beforeitexecutesthecommand(page344).Whenyougiveabadcommandnamewithoutanyarguments,
theshellreportsonthebadcommandname.
Setcorrecttocmdtocorrectonlycommands;alltocorrectcommands,variables,andfilenames;or
completetocompletecommands:
tcsh$setcorrect=cmd
tcsh$ecno$usfrmorbing
CORRECT>echo$usfrmorbing(y|n|e|a)?y
usfr:Undefinedvariable.
tcsh$setcorrect=all
tcsh$echo$usfrmorbing
CORRECT>echo$usermorning(y|n|e|a)?y
alexmorning

Withcorrectsettocmd,tcshcorrectsthecommandnamefromecnotoecho.Withcorrectsettoall,
tcshcorrectsboththecommandnameandthevariable.Itwouldalsocorrectafilenameifonewas
presentonthecommandline.
Automaticspellcheckingdisplaysaspecialpromptthatletsyouenterytoacceptthemodifiedcommand
line,ntorejectit,etoeditit,oratoabortthecommand.Referto"prompt3"onpage364foradiscussion
ofthespecialpromptusedinspellingcorrection.
Inthenextexample,aftersettingthecorrectvariabletheusermistypesthenameofthelscommand;
tcshthenpromptsforacorrectcommandname.Becausethecommandthattcshhasofferedasa
replacementisnotls,theuserchoosestoeditthecommandline.Theshellleavesthecursorfollowing
thecommandsotheusercancorrectthemistake:
tcsh$setcorrect=cmd
tcsh$lx-l RETURN(beep)
CORRECT>lex-l(y|n|e|a)?e
tcsh$lx-l
Ifyouassignthevaluecompletetothevariablecorrect,tcshattemptscommandnamecompletioninthe
samemannerasfilenamecompletion(page350).Inthefollowingexample,aftersettingcorrectto
completetheuserentersthecommandup.TheshellrespondswithAmbiguouscommandbecause
severalcommandsstartwiththesetwolettersbutdifferinthethirdletter.Theshellthenredisplaysthe
commandline.TheusercouldpressTABatthispointtogetalistofcommandsthatstartwithupbut
decidestoentertandpressRETURN.Theshellcompletesthecommandbecausethesethreeletters
uniquelyidentifytheuptimeutility:
tcsh$setcorrect=complete
tcsh$upRETURN
Ambiguouscommand
tcsh$up tRETURN uptime
4:45pmup5days,9:54,5users,loadaverage:1.62,0.83,0.33
Variables
Althoughtcshstoresvariablevaluesasstrings,youcanworkwiththesevariablesasnumbers.
Expressionsintcshcanusearithmetic,logical,andconditionaloperators.The@builtincanevaluate
integerarithmeticexpressions.
Thissectionusesthetermnumericvariabletodescribeastringvariablethatcontainsanumberthat
tcshusesinarithmeticorlogicalarithmeticcomputations.However,notruenumericvariablesexistin
tcsh.
Variablename
Atcshvariablenameconsistsof1to20characters,whichcanbeletters,digits,andunderscores(_).
Thefirstcharactercannotbeadigitbutcanbeanunderscore.
VariableSubstitution
Threebuiltinsdeclare,display,andassignvaluestovariables:set,@,andsetenv.Thesetand
setenvbuiltinsbothassumenonnumericstringvariables.The@builtinworksonlywithnumeric
variables.Bothsetand@declarelocalvariables.Thesetenvbuiltindeclaresavariableandplaces
itinthecallingenvironmentofallchildprocesses(makesitglobal).Usingsetenvissimilarto
assigningavaluetoavariableandthenusingexportintheBourneAgainShell.See"Localityof
Variables"onpage475foradiscussionoflocalandenvironmentvariables.
Oncethevalueormerelytheexistenceofavariablehasbeenestablished,tcshsubstitutesthevalueof
thatvariablewhenthenameofthevariable,precededbyadollarsign($),appearsonacommandline.If
youquotethedollarsignbyprecedingitwithabackslashorenclosingitwithinsinglequotationmarks,
theshelldoesnotperformthesubstitution.Whenavariableiswithindoublequotationmarks,the
substitutionoccursevenifyouquotethedollarsignbyprecedingitwithabackslash.
StringVariables
TheTCShelltreatsstringvariablessimilarlytothewaytheBourneAgainShelldoes.Themajor
differenceisintheirdeclarationandassignment:tcshusesanexplicitcommand,set(orsetenv),to
declareand/orassignavaluetoastringvariable.
tcsh$setname=fred
tcsh$echo$name
fred
tcsh$set
argv()
cwd/home/alex
home/home/alex
namefred
path(/usr/local/bin/bin/usr/bin/usr/X11R6/bin)
prompt$
shell/bin/tcsh
status0
termvt100
useralex
Thefirstlineintheexampledeclaresthevariablenameandassignsthestringfredtoit.Unlikebash,
tcshallowsbutdoesnotdemandSPACEsaroundtheequalsign.Thenextlinedisplaysthisvalue.When
yougiveasetcommandwithoutanyarguments,itdisplaysalistofalllocalshellvariablesandtheir
values(yourlistwillbelongerthantheoneintheexample).Whenyougiveasetcommandwiththe
nameofavariableandnovalue,thecommandsetsthevalueofthevariabletoanullstring.
Youcanusetheunsetbuiltintoremoveavariable:
tcsh$setname
tcsh$echo$name
tcsh$unsetname
tcsh$echo$name
name:Undefinedvariable.
Withsetenvyoumustseparatethevariablenamefromthestringbeingassignedtoitbyoneormore
SPACEsandnoequalsign.Thetcshcommandcreatesasubshell,echoshowsthatthevariableandits
valueareknowntothesubshell,andexitreturnstotheoriginalshell.Trythisexample,usingsetin
placeofsetenv:
tcsh$setenvSCRDIR/usr/local/src
tcsh$tcsh
tcsh$echo$SCRDIR
/usr/local/src
tcsh$exit
Ifyouusesetenvwithnoarguments,itdisplaysalistoftheenvironment(global)variablesvariables
thatarepassedtotheshell'schildprocesses.Byconvention,environmentvariablesarenamedusing
uppercaseletters.
Aswithset,givingsetenvavariablenamewithoutavaluesetsthevalueofthevariabletoanull
string.Althoughyoucanuseunsettoremoveenvironmentandlocalvariables,unsetenvcanremove
onlyenvironmentvariables.
ArraysofStringVariables
Anarrayisacollectionofstrings,eachofwhichisidentifiedbyitsindex(1,2,3,andsoon).Arraysin
tcshuseone-basedindexing(thefirstelementofthearrayhasthesubscript1).Beforeyoucanaccess
individualelementsofanarray,youmustdeclaretheentirearraybyassigningavaluetoeachelementof
thearray.ThelistofvaluesmustbeenclosedinparenthesesandseparatedbySPACEs:
8$setcolors=(redgreenblueorangeyellow)
9$echo$colors
redgreenblueorangeyellow
10$echo$colors[3]
blue
11$echo$colors[2-4]
greenblueorange
12$setshapes=('''''''''')
13$echo$shapes
14$setshapes[4]=square
15$echo$shapes[4]
square
Event8declaresthearrayofstringvariablesnamedcolorstohavefiveelementsandassignsvaluesto
eachofthem.Ifyoudonotknowthevaluesoftheelementsatthetimeyoudeclareanarray,youcan
declareanarraycontainingthenecessarynumberofnullelements(event12).
Youcanreferenceanentirearraybyprecedingitsnamewithadollarsign(event9).Anumberinbrackets
followingareferencetothearrayreferstoanelementofthearray(events10,14,and15).Twonumbers
inbrackets,separatedbyahyphen,refertotwoormoreadjacentelementsofthearray(event11).Refer
to"SpecialVariableForms"onpage361formoreinformationonarrays.
NumericVariables
The@builtinassignstheresultofanumericcalculationtoanumericvariable(asdescribedunder
"Variables"[page355],tcshhasnotruenumericvariables).Youcandeclaresinglenumericvariables
with@,justasyoucanusesettodeclarenonnumericvariables.However,ifyougiveitanonnumeric

argument,@displaysanerrormessage.Justassetdoes,the@commandusedwithoutanyarguments
listsallshellvariables.
Manyoftheexpressionsthatthe@builtincanevaluateandtheoperatorsitrecognizesarederivedfrom
theCprogramminglanguage.Thefollowingformatshowsadeclarationorassignmentusing@(the
SPACEafterthe@isrequired):
@variable-nameoperatorexpression
Thevariable-nameisthenameofthevariablethatyouareassigningavalueto.Theoperatorisoneof
theCassignmentoperators:=,+=,=,*=,/=,or%=.(Seepage533foranexplanationofthese
operators.)TheexpressionisanarithmeticexpressionthatcanincludemostCoperators(seethenext
section).Youcanuseparentheseswithintheexpressionforclarityortochangetheorderofevaluation.
Parenthesesmustsurroundpartsoftheexpressionthatcontainanyofthefollowingcharacters:<,>,&,or
|.
Expressions
Anexpressioniscomposedofconstants,variables,andmostanyofthebashoperators(page505).
ExpressionsthatinvolvefilesratherthannumericvariablesorstringsaredescribedinTable9-8onpage
368.
Table9-8.Valueofn
nMeaning
bFileisablockspecialfile
cFileisacharacterspecialfile
dFileisadirectoryfile
eFileexists
fFileisanordinaryordirectoryfile
gFilehastheset-group-IDbitset
kFilehasthestickybit(page903)set
lFileisasymboliclink
oFileisownedbyuser

pFileisanamedpipe(FIFO)
rTheuserhasreadaccesstothefile
sFileisnotempty(hasnonzerosize)
SFileisasocketspecialfile
tFiledescriptor(asingledigitreplacingfilename)isopenandconnectedtothescreen
uFilehastheset-user-IDbitset
wUserhaswriteaccesstothefile
xUserhasexecuteaccesstothefile
XFileiseitherabuiltinoranexecutablefoundbysearchingthedirectoriesin$path
zFileis0byteslong
Expressionsfollowtheserules:
1. Theshellevaluatesamissingornullargumentas0.
2. Allresultsaredecimalnumbers.
3. Exceptfor!=and==,theoperatorsactonnumericarguments.
4. YoumustseparateeachelementofanexpressionfromadjacentelementsbyaSPACE,unlessthe
adjacentelementis&,|,<,>,(,or).
tip:Donotuse$whenassigningavaluetoavariable
Aswithbash,variableshavingavalueassignedtothem(thoseontheleftoftheoperator)
mustnotbeprecededbyadollarsign($).Thus
tcsh$@$answer=5+5
willyield
answer:Undefinedvariable.
or,ifanswerisdefined,
@:Variablenamemustbeginwithaletter.
whereas
tcsh$@answer=5+5
assignsthevalue10tothevariableanswer.
Followingaresomeexamplesthatuse@:
216$@count=0
217$echo$count
0
218$@count=(10+4)/2
219$echo$count
7
220$@result=($count<5)
221$echo$result
0
222$@count+=5
223$echo$count
12
224$@count++
225$echo$count
13
Event216declaresthevariablecountandassignsitavalueof0.Event218showstheresultofan
arithmeticoperationbeingassignedtoavariable.Event220uses@toassigntheresultofalogical
operationinvolvingaconstantandavariabletoresult.Thevalueoftheoperationisfalse(=0)because
thevariablecountisnotlessthan5.Event222isacompressedformofthefollowingassignment
statement:
tcsh$@count=$count+5
Event224usesapostfixoperatortoincrementcountby1.
Postincrementandpostdecrementoperators
Youcanusethepostincrement(++)andpostdecrement()operatorsonlyinexpressionscontaininga
singlevariablename,asshowninthefollowingexample:
tcsh$@count=0
tcsh$@count++
tcsh$echo$count
1
tcsh$@next=$count++
@:Badlyformednumber.
UnlikeintheCprogramminglanguageandbash,expressionsintcshcannotusepreincrementand
predecrementoperators.
ArraysofNumericVariables
Youmustusethesetbuiltintodeclareanarrayofnumericvariablesbeforeyoucanuse@toassign
valuestotheelementsofthatarray.Thesetbuiltincanassignanyvaluestotheelementsofanumeric
array,includingzeros,othernumbers,andnullstrings.
Assigningavaluetoanelementofanumericarrayissimilartoassigningavaluetoasimplenumeric
variable.Theonlydifferenceisthatyoumustspecifytheelement,orindex,ofthearray.Thesyntaxis
@variable-name[index]operatorexpression
Theindexspecifiestheelementofthearraythatisbeingaddressed.Thefirstelementhasanindexof1.
Theindexcannotbeanexpressionbutmustbeeitheranumericconstantoravariable.Inthepreceding
syntaxthebracketsaroundindexarepartofthesyntaxanddonotindicatethatindexisoptional.Ifyou
specifyanindexthatistoolargeforthearrayyoudeclaredwithset,tcshdisplays@:Subscriptout
ofrange.
226$setages=(00000)
227$@ages[2]=15
228$@ages[3]=($ages[2]+4)
229$echo$ages[3]
19
230$echo$ages
0151900
231$setindex=3
232$echo$ages[$index]
19
233$echo$ages[6]
ages:Subscriptoutofrange.
Elementsofanumericarraybehaveasthoughtheyweresimplenumericvariables.Event226declaresan
arraywithfiveelements,eachhavingavalueof0.Events227and228assignvaluestoelementsofthe
array,andevent229displaysthevalueofoneoftheelements.Event230displaysalltheelementsofthe
array,232specifiesanelementbyusingavariable,and233demonstratestheout-of-rangeerrormessage.
Braces
Likewithbash,tcshallowsyoutousebracestodistinguishavariablefromsurroundingtextwithout
theuseofaseparator:
$setbb=abc
$echo$bbdef
bbdef:Undefinedvariable.
$echo${bb}def
abcdef
SpecialVariableForms
Thespecialvariablewiththefollowingsyntaxhasthevalueofthenumberofelementsinthevariable-
namearray:
$#variable-name
Youcandeterminewhethervariable-namehasbeensetbylookingatthevalueofthevariablewiththe
followingsyntax:
$?variable-name
Thisvariablehasavalueof1ifvariable-nameissetand0otherwise:
tcsh$setdays=(montueswedthursfri)
tcsh$echo$#days
5
tcsh$echo$?days
1
tcsh$unsetdays
tcsh$echo$?days
0
ReadingUserInput
Withinatcshshellscript,youcanusethesetbuiltintoreadalinefromtheterminalandassignittoa
variable.Thefollowingportionofashellscriptpromptstheuserandreadsalineofinputintothe
variableinput_line:
echo-n"Enterinput:"
setinput_line="$<"
Thevalueoftheshellvariable$<isalinefromstandardinput.Thequotationmarksaround$<keepthe
shellfromassigningonlythefirstwordofthelineofinputtothevariableinput_line.
ShellVariables
TCShellvariablesmaybesetbytheshell,inheritedbytheshellfromtheenvironment,orsetbytheuser
andusedbytheshell.Somevariablestakeonsignificantvalues(forexample,thePIDnumberofa
backgroundprocess).Othervariablesactasswitches:oniftheyaredeclaredandoffiftheyarenot.
Manyoftheshellvariablesareoftensetfromoneoftcsh'stwostartupfiles:~/.loginand~/.tcshrc
(page342).
ShellVariablesThatTakeOnValues
argv
Containsthecommandlinearguments(positionalparameters)fromthe
commandlinethatinvokedtheshell.Likealltcsharrays,thisarrayusesone-
basedindexing;argv[1]containsthefirstcommandlineargument.Youcan
abbreviatereferencesto$argv[n]as$n.Thetokenargv[*]referencesallthe
argumentstogether;youcanabbreviateitas$*.Use$0toreferencethename
ofthecallingprogram.Referto"PositionalParameters"onpage480.The
BourneAgainShelldoesnotusetheargvform,onlytheabbreviatedform.
$#argvor$# Holdsthenumberofelementsintheargvarray.Referto"SpecialVariable
Forms"onpage361.
autolist Controlscommandandvariablecompletion(page351).
autologout
Enablestcsh'sautomaticlogoutfacility,whichlogsyououtifyouleavethe
shellidlefortoolong.Thevalueofthevariableisthenumberofminutesof
inactivitythattcshwaitsbeforeloggingyouout.Thedefaultis60minutesif
youareSuperuser.Thisvariableisinitiallyunsetforotherusers.
cdpath
AffectstheoperationofcdinthesamewayastheCDPATHvariabledoesin
bash(page289).Thecdpathvariableisassignedanarrayofabsolute
pathnames(seepath,laterinthissection)andisusuallysetinthe~/.loginfile
withacommandlinesuchasthefollowing:
tcsh$setcdpath=(/home/scott/home/scott/letters)
Whenyoucallcdwithasimplefilename,itsearchestheworkingdirectoryfor
asubdirectorywiththatname.Ifoneisnotfound,cdsearchesthedirectories
listedincdpathforthesubdirectory.
correct
Settocmdforautomaticspellingcorrectionofcommandnames,toallto
correcttheentirecommandline,andtocompleteforautomaticcompletionof
commandnames.Thisvariableworksoncorrectionsthataremadeafteryou
pressRETURN.Referto"AfterYouPressRETURN"onpage354.
cwd
Theshellsetsthisvariabletothenameoftheworkingdirectory.Whenyou
accessadirectorythroughasymboliclink(page99),tcshsetscwdtothe
nameofthesymboliclink.
dirstack
Theshellkeepsthestackofdirectoriesusedwiththepushd,popd,anddirs
builtinsinthisvariable.Formoreinformationreferto"Manipulatingthe
DirectoryStack"onpage274.

fignore Holdsanarrayofsuffixesthattcshignoresduringfilenamecompletion.
gid TheshellsetsthisvariabletoyourgroupID.
histfile Holdsthefullpathnameofthefilethatsavesthehistorylistbetweenlogin
sessions(page345).Thedefaultsis~/.history.
history Specifiesthesizeofyourhistorylist.Referto"History"onpage344.
homeorHOME Holdsthepathnameoftheuser'shomedirectory.Thecdbuiltinreferstothis
variable,asdoesthefilenamesubstitutionof~(page326).
mail
Specifiesfilesanddirectoriestocheckformail.TheTCShellchecksfornew
mailevery10minutesunlessthefirstwordofmailisanumber,inwhichcase
thatnumberspecifieshowoftentheshellshouldcheckinseconds.
owd Theshellkeepsthenameofyourprevious(old)workingdirectoryinthis
variable,whichisequivalentto~inbash.
pathorPATH
Holdsalistofdirectoriesthattcshsearchesforexecutablecommands(page
284).Ifthisarrayisemptyorunset,youcanexecutecommandsonlyby
givingtheirfullpathnames.Youcansetpathwithacommandsuchasthe
following:
tcsh$setpath=(/usr/bin/bin/usr/local/bin
/usr/bin/X11~/bin.)
prompt
Holdstheprimaryprompt,similartothebashPS1variable(page286).Ifitis
notset,thepromptis>,or#forroot(Superuser).Theshellexpandsan
exclamationpointinthepromptstringtothecurrenteventnumber.The
followingisatypicallinefroma.tcshrcfilethatsetsthevalueofprompt:
setprompt='!$'
Table9-4listsanumberofspecialformattingsequencesyoucanuseinprompttoachievespecialeffects.
Table9-4.promptformattingsequences
Sequence Displaysinprompt
%/ Valueofcwd(theworkingdirectory)
%~ Sameas%/,butreplacesthepathoftheuser'shomedirectorywithatilde
%!or%hor!Currenteventnumber

%m Hostnamewithoutthedomain
%M Fullhostname,includingthedomain
%n User'susername
%t Timeofdaythroughthecurrentminute
%p Timeofdaythroughthecurrentsecond
%d Dayoftheweek
%D Dayofthemonth
%W Monthasmm
%y Yearasyy
%Y Yearasyyyy
%# Apoundsign(#)iftheuserisrunningasroot(Superuser);otherwiseagreater
thansign(>)
%? Exitstatusoftheprecedingcommand
prompt2
Holdsthepromptusedinforeachandwhilecontrolstructures(pages373and375).
Thedefaultvalueis'%R?',whereRisreplacedbythewordwhileifyouareinside
awhilestructureandforeachifyouareinsideaforeachstructure.
prompt3 Holdsthepromptusedduringautomaticspellingcorrection.Thedefaultvalueis
'CORRECT>%R(y|n|e|a)?',whereRisreplacedbythecorrectedstring.
savehist
Specifiesthenumberofcommandssavedfromthehistorylistwhenyoulogout.
Theseeventsaresavedinafilenamed~/.history.Theshellusestheseeventsasthe
initialhistorylistwhenyouloginagain,causingyourhistorylisttocontinueacross
loginsessions(page345).
shell Holdsthepathnameoftheshellyouareusing.
shlvl Isincrementedeachtimeyoustartasubshellanddecrementedeachtimeyouexita
subshell.Thevalueissetto1forloginashell.
status Containstheexitstatusreturnedbythelastcommand.Similarto$?inbash(page
479).

tcsh Holdstheversionnumberoftcshthatyouarerunning.
time
Providestwofunctions:automatictimingofcommandsusingthetimebuiltinand
theformatusedbytime.Youcansetthisvariabletoeitherasinglenumericvalueor
anarrayholdinganumericvalueandastring.Thenumericvalueisusedtocontrol
automatictiming;anycommandthattakesmorethanthatnumberofCPUsecondsto
runhastimedisplaythecommandstatisticswhenitfinishesexecution.Avalueof0
resultsinstatisticsbeingdisplayedaftereverycommand.Thestringcontrolsthe
formattingofthestatisticsusingspecialformattingsequences,includingthoselisted
inTable9-5.
Table9-5.timeformattingsequences
Sequence Displays
%U Timethecommandspentrunningusercode,inCPUseconds(usermode)
%S Timethecommandspentrunningsystemcode,inCPUseconds(kernelmode)
%E Wallclocktime(totalelapsed)takenbythecommand
%P PercentageoftimetheCPUspentonthistaskduringthisperiod,computedas
(%U+%S)/%E
%W Numberoftimesthecommand'sprocesseswereswappedouttodisk
%X Averageamountofsharedcodememoryusedbythecommand,inkilobytes
%D Averageamountofdatamemoryusedbythecommand,inkilobytes
%K Totalmemoryusedbythecommand(as%X+%D),inkilobytes
%M Maximumamountofmemoryusedbythecommand,inkilobytes
%F Numberofmajorpagefaults(pagesofmemorythathadtobereadfromdisk)
%I Numberofinputoperations
%O Numberofoutputoperations
Bydefaultthetimebuiltinusesthestring

"%Uu%Ss%E%P%%X+%Dk%I+%Oio%Fpf+%Ww"
whichgeneratesoutputinthefollowingformat:
tcsh$time
0.200u0.340s17:32:33.270.0%0+0k0+0io1165pf+0w
Youcantimecommandswhenyouareconcernedaboutsystemperformance.Ifyourcommands
consistentlyshowmanypagefaultsandswaps,yoursystemisprobablymemorystarvedandyoushould
consideraddingmorememorytothesystem.Youcanusetheinformationthattimereportstocompare
theperformanceofvarioussystemconfigurationsandprogramalgorithms.
tperiod Controlshowoften,inminutes,theshellexecutesthespecialperiodicalias(page
347).
user Theshellsetsthisvariabletoyourusername.
version Theshellsetsthisvariabletocontaindetailedinformationabouttheversionoftcsh
youareusing.
watch
Settoanarrayofuserandterminalpairstowatchforloginsandlogouts.Theword
anymeansanyuseroranyterminal,so(anyany)monitorsallloginsandlogoutson
allterminals,and(scottttyS1anyconsole$userany)watchesforscottonttyS1,
anyuserwhoaccessesthesystemconsole,andanyloginsandlogoutsthatuseyour
account(presumablytocatchintruders).Bydefaultloginsandlogoutsarechecked
onceevery10minutes,butyoucanchangethisvaluebybeginningthearraywitha
numericvaluegivingthenumberofminutesbetweenchecks.Ifyousetwatchto(1
anyconsole),loginsandlogoutsbyanyuserontheconsolewillbecheckedoncea
minute.Reportsaredisplayedjustbeforeanewshellpromptisissued.Also,thelog
builtinforcesanimmediatecheckwheneveritisexecuted.Seewhoforinformation
abouthowyoucancontroltheformatofthewatchmessages.
who Controlstheformatoftheinformationdisplayedinwatchmessages(Table9-6).
Table9-6.whoformattingsequence
Sequence Displays

%n Username
%a Actiontakenbyuser
%l Terminalonwhichactiontookplace
%M Fullhostnameofremotehost(orlocalifnone)fromwhichactiontookplace
$m Hostnamewithoutdomainname
Thedefaultstringusedforwatchmessageswhenwhoisunsetis"%nhas%a%lfrom%m",which
generatesthefollowingline:
jennyhasloggedontty2fromlocal
$Asinbash,thisvariablecontainsthePIDnumberofthecurrentshell;useitas$$.
ShellVariablesThatActasSwitches
Thefollowingshellvariablesactasswitches;theirvaluesarenotsignificant.Ifthevariablehasbeen
declared,theshelltakesthespecifiedaction.Ifnot,theactionisnottakenorisnegated.Youcansetthese
variablesinyour~/.tcshrcstartupfile,inashellscript,orfromthecommandline.
autocorrect Causestheshelltoattemptspellingcorrectionautomatically,justbeforeeach
attemptatcompletion.
dunique
Normallypushdblindlypushesthenewworkingdirectoryontothedirectory
stack,meaningthatyoucanendupwithmanyduplicateentriesonthisstack.Set
duniquetocausetheshelltolookforanddeleteanyentriesthatduplicatetheone
itisabouttopush.
echo Causestheshelltodisplayeachcommandbeforeitexecutesthatcommand.Set
echobycallingtcshwiththexoptionorbyusingset.
Enablesfilenamecompletion(page350)whenrunningtcshascsh(andcshis

filec linkedtotcsh).
histlit Displaysthecommandsinthehistorylistexactlyasentered,withoutinterpretation
bytheshell(page346).
ignoreeof
PreventsyoufromusingCONTROL-Dtoexitfromashellsoyoucannot
accidentallylogout.Whenthisvariableisdeclared,youmustuseexitorlogoutto
leaveashell.
listjobs Causestheshelltolistalljobswheneverajobissuspended.
listlinks CausesthelsFbuiltintoshowthetypeoffileeachsymboliclinkpointstoinstead
ofmarkingthesymboliclinkwithan@symbol.
loginsh Setbytheshellifthecurrentshellisrunningasaloginshell.
nobeep Disablesallbeepingbytheshell.
noclobber
Preventsyoufromaccidentallyoverwritingafilewhenyouredirectoutputand
preventsyoufromcreatingafilewhenyouattempttoappendoutputtoa
nonexistentfile(Table9-7).Tooverridenoclobber,addanexclamationpointto
thesymbolyouuseforredirectingorappendingoutput(forexample,>!and>>!).
Formoreinformationseepage119.
Table9-7.Hownoclobberworks
Command
line noclobbernotdeclared noclobberdeclared
x>fileout
Redirectsstandardoutputfrom
processxtofileout.
Overwritesfileoutifitexists.
Redirectsstandardoutputfromprocessxto
fileout.Theshelldisplaysanerrormessageif
fileoutexistsanddoesnotoverwritethefile.
x>>fileout
Redirectsstandardoutputfrom
processxtofileout.Appends
newoutputtotheendof
fileoutifitexists.Creates
fileoutifitdoesnotexist.
Redirectsstandardoutputfromprocessxto
fileout.Appendsnewoutputtotheendoffileout
ifitexists.Theshelldisplaysanerrormessageif
fileoutdoesnotexistanddoesnotcreatethefile.
noglob Preventstheshellfromexpandingambiguousfilenames.Allowsyoutouse*,?,
~,and[]onthecommandlineorinashellscriptwithoutquotingthem.
Causestheshelltopassanambiguousfilereferencethatdoesnotmatcha
filenametothecommandthatisbeingcalled.Theshelldoesnotexpandthefile
reference.Whenyoudonotsetnonomatch,tcshgeneratesaNomatcherror
nonomatch
messageanddoesnotexecutethecommand.
tcsh$catquestions?
cat:Nomatch
tcsh$setnonomatch
tcsh$catquestions?
cat:questions?:Nosuchfileordirectory
notify
Whenset,tcshsendsamessagetothescreenimmediatelywhenevera
backgroundjobcompletes.Ordinarilytcshnotifiesyouaboutjobcompletionjust
beforedisplayingthenextprompt.Referto"JobControl"onpage271.
pushdtohome Causesacalltopushdwithoutanyargumentstochangedirectoriestoyour
homedirectory(equivalenttopushd).
pushdsilent Causespushdandpopdnottodisplaythedirectorystack.
rmstar Causestheshelltorequestconfirmationwhenyougiveanrm*command.
verbose Causestheshelltodisplayeachcommandafterahistoryexpansion(page344).
Setverbosebycallingtcshwiththevoptionorbyusingset.
visiblebell Causesaudiblebeepstobereplacedbyflashingthescreen.
ControlStructures
TheTCShellusesmanyofthesamecontrolstructuresastheBourneAgainShell.Ineachcasethesyntax
isdifferent,buttheeffectsarethesame.Thissectionsummarizesthedifferencesbetweenthecontrol
structuresinthetwoshells.Formoreinformationreferto"ControlStructures"onpage436.
if
Thesyntaxoftheifcontrolstructureis
if(expression)simple-command
Theifcontrolstructureworksonlywithsimplecommands,notwithpipesorlistsofcommands.Youcan
usetheif...thencontrolstructure(page372)toexecutemorecomplexcommands.
tcsh$catif_1
#!/bin/tcsh
#Routinetoshowtheuseofasimpleifcontrolstructure.
#
if($#argv==0)echo"if_1:therearenoarguments"
Theif_1scriptcheckswhetheritwascalledwithoutanyarguments.Iftheexpressionenclosedin
parenthesesevaluatestotruethatis,ifzeroargumentswereonthecommandlinetheifstructuredisplaysa
message.
Inadditiontologicalexpressionssuchastheonetheif_1scriptuses,youcanuseexpressionsthatreturn
avaluebasedonthestatusofafile.Thesyntaxforthistypeofexpressionis
nfilename
wherenisfromthelistinTable9-8.
Iftheresultofthetestistrue,theexpressionhasavalueof1;ifitisfalse,theexpressionhasavalueof
0.Ifthespecifiedfiledoesnotexistorisnotaccessible,tcshevaluatestheexpressionas0.The
followingexamplecheckswhetherthefilespecifiedonthecommandlineisanordinaryordirectoryfile
(andnotadeviceorotherspecialfile):
tcsh$catif_2
#!/bin/tcsh
if-f$1echo"OrdinaryorDirectoryfile"
Youcancombineoperatorswhereitmakessense.Forexample,oxfilenameistrueifyouownandhave
executepermissionforthefile.Thisexpressionisequivalenttoofilename&&xfilename.
Someoperatorsreturnusefulinformationaboutafileotherthanreportingtrueorfalse.Theyusethesame

nfilenameformat,wherenisoneofthevaluesshowninTable9-9.
Table9-9.Valueofn
nMeaning
AThelasttimethefilewasaccessed.[*]
A: Thelasttimethefilewasaccesseddisplayedinahuman-readableformat.
MThelasttimethefilewasmodified.[*]
M: Thelasttimethefilewasmodifieddisplayedinahuman-readableformat.
CThelasttimethefile'sinodewasmodified.[*]
C: Thelasttimethefile'sinodewasmodifieddisplayedinahuman-readableformat.
DDevicenumberforthefile.Thisnumberuniquelyidentifiesthedevice(diskpartition,
forexample)onwhichthefileresides.
IInodenumberforthefile.Theinodenumberuniquelyidentifiesafileonaparticular
device.
FAstringoftheformdevice:inode.Thisstringuniquelyidentifiesafileanywhereonthe
system.
NNumberofhardlinkstothefile.
PThefile'spermissions,showninoctal,withoutaleading0.
UNumericuserIDofthefile'sowner.
U: Usernameofthefile'sowner.
GNumericgroupIDofthefile'sgroup.
G: Nameofthefile'sgroup.
ZNumberofbytesinthefile.
[*]Timemeasuredinsecondsfromtheepoch(usuallythestartofJanuary1,1970).
Youcanuseonlyoneoftheseoperatorsinagiventest,anditmustappearasthelastoperatorina
multiple-operatorsequence.Because0canbeavalidresponsefromsomeoftheseoperators(for
instance,thenumberofbytesinafilemightbe0),mostreturn1onfailureinsteadofthe0thatthelogical
operatorsreturnonfailure.TheoneexceptionisF,whichreturnsacolonifitcannotdeterminethedevice
andinodeforthefile.
Whenyouwanttouseoneoftheseoperatorsoutsideofacontrolstructureexpression,youcanusethe
filetestbuiltintoevaluateafiletestandreporttheresult:
tcsh$filetest-zif_1
0
tcsh$filetest-Fif_1
2051:12694
tcsh$filetest-Zif_1
131
goto
Thegotostatementhasthefollowingsyntax:
gotolabel
Agotobuiltintransferscontroltothestatementbeginningwithlabel:.Thefollowingscriptfragment
demonstratestheuseofgoto:
tcsh$catgoto_1
#!/bin/tcsh
#
#testfor2arguments
#
if($#argv==2)gotogoodargs
echo"Usage:goto_1arg1arg2"
exit1
goodargs:
...
Thegoto_1scriptdisplaysausagemessage(page440)whenitiscalledwithmoreorfewerthantwo
arguments.
InterruptHandling
Theonintrstatementtransferscontrolwhenyouinterruptashellscript.Theformatofanonintrstatement
is
onintrlabel
Whenyoupresstheinterruptkeyduringexecutionofashellscript,theshelltransferscontroltothe
statementbeginningwithlabel:.Thisstatementallowsyoutoterminateascriptgracefullywhenitis
interrupted.Youcanuseittoensurethatwhenyouinterruptashellscript,thescriptremovestemporary
filesbeforereturningcontroltotheparentshell.
Thefollowingscriptdemonstratesonintr.Itloopscontinuouslyuntilyoupresstheinterruptkey,atwhich
timeitdisplaysamessageandreturnscontroltotheshell:
tcsh$catonintr_1
#!/bin/tcsh
#demonstrationofonintr
onintrclose
while(1)
echo"Programisrunning."
sleep2
end
close:
echo"Endofprogram."
Ifascriptcreatestemporaryfiles,youcanuseonintrtoremovethem.
close:
rm-f/tmp/$$*
Theambiguousfilereference/tmp/$$*matchesallfilesin/tmpthatbeginwiththePIDnumberofthe
currentshell.Refertopage478foradescriptionofthistechniquefornamingtemporaryfiles.
if...then...else
Theif...then...elsecontrolstructurehasthreeforms.Thefirstform,anextensionofthesimpleifstructure,
executesmorecomplexcommandsoraseriesofcommandsifexpressionistrue.Thisformisstilla
one-waybranch.
if(expression)then
commands
endif
Thesecondformisatwo-waybranch.Ifexpressionistrue,thefirstsetofcommandsisexecuted.Ifitis
false,thesetofcommandsfollowingelseisexecuted.
if(expression)then
commands
else
commands
endif
Thethirdformissimilartotheif...then...elifstructure(page442).Itperformstestsuntilitfindsan
expressionthatistrueandthenexecutesthecorrespondingcommands.
if(expression)then
commands
elseif(expression)then
commands
...
else
commands
endif
Thefollowingprogramassignsavalueof0,1,2,or3tothevariableclassbasedonthevalueofthefirst
commandlineargument.Theprogramdeclaresthevariableclassatthebeginningforclarity;youdonot
needtodeclareitbeforeitsfirstuse.Alsoforclarity,thescriptassignsthevalueofthefirstcommand
lineargumenttonumber.
tcsh$catif_else_1
#!/bin/tcsh
#routinetocategorizethefirst
#commandlineargument
setclass
setnumber=$argv[1]
#
if($number<0)then
@class=0
elseif(0<=$number&&$number<100)then
@class=1
elseif(100<=$number&&$number<200)then
@class=2
else
@class=3
endif
#
echo"Thenumber$numberisinclass${class}."
Thefirstifstatementtestswhethernumberislessthan0.Ifitis,thescriptassigns0toclassandtransfers
controltothestatementfollowingendif.Ifitisnot,thesecondiftestswhetherthenumberisbetween0
and100.The&&istheBooleanANDoperator,yieldingavalueoftrueiftheexpressiononeachsideis
true.Ifthenumberisbetween0and100,1isassignedtoclassandcontrolistransferredtothestatement
followingendif.Asimilartestdetermineswhetherthenumberisbetween100and200.Ifitisnot,the
finalelseassigns3toclass.Theendifclosestheifcontrolstructure.Thefinalstatementusesbraces({}
)toisolatethevariableclassfromthefollowingperiod.Thebracesisolatetheperiodforclarity;the
shelldoesnotconsiderapunctuationmarktobepartofavariablename.Thebraceswouldberequiredif
youwantedothercharacterstofollowimmediatelyafterthevariable.
foreach
Theforeachstructureparallelsthebashfor...instructure(page449).Thesyntaxis
foreachloop-index(argument-list)
commands
end
Thisstructureloopsthroughcommands.Thefirsttimethroughtheloop,thestructureassignsthevalueof
thefirstargumentinargument-listtoloop-index.Whencontrolreachestheendstatement,theshell
assignsthevalueofthenextargumentfromargument-listtoloop-indexandexecutesthecommands
again.Theshellrepeatsthisprocedureuntilitexhaustsargument-list.
Thefollowingtcshscriptusesaforeachstructuretoloopthroughthefilesintheworkingdirectory
containingaspecifiedstringofcharactersintheirfilenameandtochangethestring.Forexample,youcan
useittochangethestringmemoinfilenamestoletter.Thefilenamesmemo.1,dailymemo,and
memorieswouldchangetoletter.1,dailyletter,andletterries.
Thisscriptrequirestwoarguments:thestringtobechanged(theoldstring)andthenewstring.The
argument-listoftheforeachstructureusesanambiguousfilereferencetoloopthroughallfilenamesthat
containthefirstargument.Foreachfilenamethatmatchestheambiguousfilereference,themvutility
changesthefilename.Theechoandsedcommandsappearwithinbackticks(')thatindicatecommand
substitution:Executingthecommandswithinthebackticksreplacesthebackticksandeverythingbetween
them.Referto"CommandSubstitution"onpage329formoreinformation.Thesedutility(page563)
substitutesthefirstargumentforthesecondargumentinthefilename.The$1and$2areabbreviated
formsof$argv[1]and$argv[2].
tcsh$catren
#!/bin/tcsh
#Usage:renarg1arg2
#changesthestringarg1inthenamesoffiles
#intheworkingdirectoryintothestringarg2
if($#argv!=2)gotousage
foreachi(*$1*)
mv$i'echo$i|sed-ns/$1/$2/p'
end
exit0
usage:
echo"Usage:renarg1arg2"
exit1

optional
Thenextscriptusesaforeachlooptoassignthecommandlineargumentstotheelementsofanarraynamedbuffer:
tcsh$catforeach_1
#!/bin/tcsh
#routinetozero-fillargvto20arguments
#
setbuffer=(00000000000000000000)
setcount=1
#
if($#argv>20)gototoomany
#
foreachargument($argv[*])
setbuffer[$count]=$argument
@count++
end
#REPLACEcommandONTHENEXTLINEWITH
#THEPROGRAMYOUWANTTOCALL.
execcommand$buffer[*]
#
toomany:
echo"Toomanyargumentsgiven."
echo"Usage:foreach_1[upto20arguments]"
exit1
Theforeach_1scriptcallsanotherprogramnamedcommandwithacommandlineguaranteedtocontain20arguments.If
foreach_1iscalledwithfewerthan20arguments,itfillsthecommandlinewithzerostocompletethe20argumentsfor
command.Providingmorethan20argumentscausesittodisplayausagemessageandexitwithanerrorstatusof1.
Theforeachstructureloopsthroughthecommandsonetimeforeachcommandlineargument.Eachtimethroughtheloop,
foreachassignsthevalueofthenextargumentfromthecommandlinetothevariableargument.Thenthescriptassignseachof
thesevaluestoanelementofthearraybuffer.Thevariablecountmaintainstheindexforthebufferarray.Apostfixoperator
incrementsthecountvariableusing@(@count++).Theexecbuiltin(bashandtcsh;page491)callscommandsothatanew
processisnotinitiated.(Oncecommandiscalled,theprocessrunningthisroutineisnolongerneededsoanewprocessisnot
required.)
while
Thesyntaxofthewhilestructureis
while(expression)
commands
end
Thisstructurecontinuestoloopthroughcommandswhileexpressionistrue.Ifexpressionisfalsethe
firsttimeitisevaluated,thestructureneverexecutescommands.
tcsh$catwhile_1
#!/bin/tcsh
#Demonstrationofawhilecontrolstructure.
#Thisroutinesumsthenumbersbetween1andn,
#withnbeingthefirstargumentonthecommand#line.
#
setlimit=$argv[1]
setindex=1
setsum=0
#
while($index<=$limit)
@sum+=$index
@index++
end
#
echo"Thesumis$sum"
Thisprogramcomputesthesumofallintegersuptoandincludingn,wherenisthefirstargumentonthe
commandline.The+=operatorassignsthevalueofsum+indextosum.
breakandcontinue
Youcaninterruptaforeachorwhilestructurewithabreakorcontinuestatement.Thesestatements
executetheremainingcommandsonthelinebeforetheytransfercontrol.Thebreakstatementtransfers
controltothestatementaftertheendstatement,terminatingexecutionoftheloop.Thecontinuestatement
transferscontroltotheendstatement,whichcontinuesexecutionoftheloop.
switch
Theswitchstructureisanalogoustothebashcasestructure(page459):
switch(test-string)
casepattern:
commands
breaksw
casepattern:
commands
breaksw
...
default:
commands
breaksw
endsw
Thebreakswstatementtransferscontroltothestatementfollowingtheendswstatement.Ifyouomita
breaksw,controlfallsthroughtothenextcommand.Youcanuseanyofthespecialcharacterslistedin
Table11-2onpage462withinpatternexceptthepipesymbol(|).
tcsh$catswitch_1
#!/bin/tcsh
#Demonstrationofaswitchcontrolstructure.
#Thisroutineteststhefirstcommandlineargument
#foryesornoinanycombinationofuppercaseand
#lowercaseletters.
#
#
#testthatargv[1]exists
if($#argv!=1)then
echo"Usage:switch_1[yes|no]"
exit1
else
#argv[1]exists,setupswitchbasedonitsvalue
switch($argv[1])
#caseofYES
case[yY][eE][sS]:
echo"Argumentoneisyes."
breaksw
#
#caseofNO
case[nN][oO]:
echo"Argumentoneisno."
breaksw

#
#defaultcase
default:
echo"Argumentoneisneitheryesnorno."
breaksw
endsw
endif
Builtins
Builtinsarecommandsthatarepartof(builtinto)theshell.Whenyougiveasimplefilenameasa
command,theshellfirstcheckswhetheritisthenameofabuiltin.Ifitis,theshellexecutesitaspartof
thecallingprocess;theshelldoesnotforkanewprocesstoexecutethebuiltin.Theshelldoesnotneedto
searchthedirectorystructureforbuiltinprogramsbecausetheyareimmediatelyavailabletotheshell.
Ifthesimplefilenameyougiveasacommandisnotabuiltin,theshellsearchesthedirectorystructurefor
theprogramyouwant,usingthePATHvariableasaguide.Whenitfindstheprogramtheshellforksa
newprocesstoexecutetheprogram.
AlthoughtheyarenotlistedinTable9-10,thecontrolstructurekeywords(if,foreach,endsw,andsoon)
arebuiltins.Thetabledescribesmanyofthetcshbuiltins,someofwhicharealsobuiltintoothershells.
Table9-10.tcshbuiltins
Builtin Function
%job Asynonymforthefgbuiltin.Thejobisthejobnumberofthejobyouwant
tobringtotheforeground(page272).
%job&Asynonymforthebgbuiltin.Thejobisthenumberofthejobyouwantto
putinthebackground(page273).
@Similartothesetbuiltinbutevaluatesnumericexpressions.Referto
"NumericVariables"onpage358.
alias Createsanddisplaysaliases;bashusesadifferentsyntaxthantcsh.Refer
to"Aliases"onpage347.

alloc Displaysareportoftheamountoffreeandusedmemory.
bg Movesasuspendedjobintothebackground(page273).
bindkey Controlsthemappingofkeystothetcshcommandlineeditorcommands.
bindkey Withoutanyarguments,bindkeylistsallkeybindings(page353).
bindkeylListsallavailableeditorcommandsalongwithashortdescriptionofeach.
bindkeyePutsthecommandlineeditorinemacsmode(page353).
bindkeyvPutsthecommandlineeditorinvi(m)mode(page353).
bindkeykey
command Attachestheeditorcommandcommandtothekeykey.
bindkeybkey
command
Similartothepreviousformbutallowsyoutospecifycontrolkeysbyusing
theformCx(wherexisthecharacteryoutypewhileyoupressthe
CONTROLkey),specifymetakeysequencesasMx(onmostkeyboards
usedwithLinux,theALTkeyisthemetakey),andspecifyfunctionkeysas
F-x.
bindkeyckey
command
Bindsthekeykeytothecommandcommand.Herethecommandisnotan
editorcommandbuteitherashellbuiltinoranexecutableprogram.
bindkeyskey
string Wheneveryoutypekey,stringissubstituted.
builtins Displaysalistofallbuiltins.
cdorchdir Changesworkingdirectories(page82).
dirs Displaysthedirectorystack(page274).
echo
Displaysitsarguments.YoucanpreventechofromdisplayingaRETURNat
theendofalinebyusingthenoption(see"ReadingUserInput"onpage
361)orbyusingatrailing\c(see"read:AcceptsUserInput:AcceptsUser
Input"onpage487).Theechobuiltinissimilartotheechoutility(page
647).
eval
Scansandevaluatesthecommandline.Whenyouputevalinfrontofa
command,thecommandisscannedtwicebytheshellbeforeitisexecuted.
Thisfeatureisusefulwithacommandthatisgeneratedbycommandor
variablesubstitution.Becauseoftheorderinwhichtheshellprocessesa
commandline,itissometimesnecessarytorepeatthescantoachievethe
desiredresult(page318).
exec
Overlaystheprogramcurrentlybeingexecutedwithanotherprograminthe
sameshell.Theoriginalprogramislost.Referto"exec:Executesa
Command:ExecutesaCommand"onpage491formoreinformation;also
refertosource(page380).

exit ExitsfromaTCShell.Whenyoufollowitwithanumericargument,tcsh
returnsthatnumberastheexitstatus(page479).
fg Movesajobintotheforeground(page271).
filetest
Takesoneofthefileinquiryoperatorsfollowedbyoneormorefilenames
andappliestheoperatortoeachfilename(page370).Returnstheresultsasa
space-separatedlist.
glob Likeecho,butdoesnotdisplaySPACEsbetweenitsargumentsanddoes
notfollowitsdisplaywithaNEWLINE.
hashstat
Reportsontheefficiencyoftcsh'shashmechanism.Thehashmechanism
speedstheprocessofsearchingthroughthedirectoriesinyoursearchpath.
Seealsorehash(page380)andunhash(page381).
history Displaysalistofrecentcommands(page344).
jobs Displaysalistofjobs(suspendedcommandsandthoserunninginthe
background).
kill Terminatesajoborprocess(page497).
limit
Limitsthecomputerresourcesthatthecurrentprocessandanyprocessesit
createscanuse.YoucanputlimitsonthenumberofsecondsofCPUtime
theprocesscanuse,thesizeoffilesthattheprocesscancreate,andso
forth.
log Immediatelyproducesthereportthatthewatchshellvariable(page365)
wouldnormallyproduceevery10minutes.
login Logsinauser.Canbefollowedbyausername.
logout Endsasessionifyouareusingyouroriginal(login)shell.
lsFSimilartolsFbutfaster.(ThisbuiltinisthecharacterslsFwithoutany
SPACEs.)
nice
Lowerstheprocessingpriorityofacommandorashell.Itisusefulifyou
wanttorunacommandthatmakeslargedemandsonthesystemandyoudo
notneedtheoutputrightaway.IfyouareSuperuser,youcanuseniceto
raisethepriorityofacommand.Refertopage734formoreinformationon
thenicebuiltinandtheniceutility,whichisavailablefrombash.
nohup
Allowsyoutologoutwithoutterminatingprocessesrunninginthe
background.Somesystemsaresetuptodothisautomatically.Refertopage
736forinformationonthenohupbuiltinandthenohuputility,whichis
availablefrombash.
notify Causestheshelltonotifyyouimmediatelywhenthestatusofoneofyour
jobschanges(page271).

onintr
Controlswhatactionaninterruptcauseswithinascript(page371).See
"trap:CatchesaSignal"onpage493forinformationontheequivalent
commandinbash.
popd Removesadirectoryfromthedirectorystack(page274).
printenv Displaysallenvironmentvariablenamesandvalues.
pushd Changestheworkingdirectoryandplacesthenewdirectoryatthetopofthe
directorystack(page274).
rehash
Re-createstheinternaltablesusedbythehashmechanism.Wheneveranew
instanceoftcshisinvoked,thehashmechanismcreatesasortedlistofall
availablecommandsbasedonthevalueofpath.Afteryouaddacommand
toadirectoryinpath,userehashtore-createthesortedlistofcommands.
Ifyoudonot,tcshmaynotbeabletofindthenewcommand.Alsoreferto
hashstat(page379)andunhash(page381).
repeat
Takestwoargumentsacountandsimplecommand(nopipesorlistsof
commands)andrepeatsthecommandthenumberoftimesspecifiedbythe
count.
sched
Executesacommandataspecifiedtime.Forexample,thefollowing
commandcausestheshelltoprintthemessageDentalappointment.at10
AM:
tcsh$sched10:00echo"Dentalappointment."
Withoutanyarguments,schedprintsthelistofscheduledcommands.
Whenthetimetoexecuteascheduledcommandarrives,tcshexecutesthe
commandjustbeforeitdisplaysaprompt.
set Declares,initializes,anddisplayslocalvariables(page355).
setenv Declares,initializes,anddisplaysenvironmentvariables(page355).
shift
Analogoustothebashshiftbuiltin(page483).Withoutanargument,
shiftpromotestheindexesoftheargvarray.Youcanuseitwithan
argumentofanarraynametoperformthesameoperationonthatarray.
source
Executestheshellscriptgivenasitsargument:sourcedoesnotfork
anotherprocess.Itissimilartothebash.(dot)builtin(page259).The
sourcebuiltinexpectsaTCShellscriptsonoleading#!isrequiredinthe
script.Thecurrentshellexecutessourcesothatthescriptcancontain
commands,suchasset,thataffectthecurrentshell.Afteryoumake
changestoyour.tcshrcor.loginfile,youcanusesourcetoexecuteit
fromtheshellandtherebyputthechangesintoeffectwithoutloggingoff
andon.Youcannestsourcebuiltins.
stop Stopsajoborprocessthatisrunninginthebackground.Thestopbuiltin
acceptsmultiplearguments.
suspend Stopsthecurrentshellandputsitinthebackground.Itissimilartothe
suspendkey,whichstopsjobsrunningintheforeground.

time Executesthecommandthatyougiveitasanargument.Itdisplaysa
summaryoftime-relatedinformationabouttheexecutedcommand,
accordingtothetimeshellvariable(page364).Withoutanargument,time
displaysthetimesforthecurrentshellanditschildren.
umask Identifiesorchangestheaccesspermissionsthatareassignedtofilesyou
create(page810).
unalias Removesanalias(page347).
unhash Turnsoffthehashmechanism.Seealsohashstat(page379)andrehash
(page380).
unlimit Removeslimits(page379)onthecurrentprocess.
unset Removesavariabledeclaration(page355).
unsetenv Removesanenvironmentvariabledeclaration(page355).
wait
Causestheshelltowaitforallchildprocessestoterminate.Whenyougivea
waitcommandinresponsetoashellprompt,tcshdoesnotdisplaya
promptuntilallbackgroundprocesseshavefinishedexecution.Ifyou
interruptitwiththeinterruptkey,waitdisplaysalistofoutstanding
processesbeforetcshdisplaysaprompt.
where
Whengiventhenameofacommandasanargument,locatesalloccurrences
ofthecommandand,foreach,tellsyouwhetheritisanalias,abuiltin,oran
executableprograminyourpath.
which
Similartowherebutreportsononlythecommandthatwouldbeexecuted,
notalloccurrences.ThisbuiltinismuchfasterthantheLinuxwhichutility
andknowsaboutaliasesandbuiltins.
ChapterSummary
LiketheBourneAgainShell,theTCShellisbothacommandinterpreterandaprogramminglanguage.
TheTCShell,whichisbasedontheCShellthatwasdevelopedattheUniversityofCaliforniaat
Berkeley,includespopularfeaturessuchashistory,alias,andjobcontrol.
Youmayprefertousetcshasacommandinterpreter,especiallyifyouarefamiliarwiththeCShell.
Youcanusechshtochangeyourloginshelltotcsh.However,runningtcshasyourinteractiveshell
doesnotcausetcshtorunshellscripts;theywillcontinuetoberunbybashunlessyouexplicitly
specifyanothershellonthefirstlineofthescriptorspecifythescriptnameasanargumenttotcsh.
Specifyingtheshellonthefirstlineofashellscriptensuresthebehavioryouexpect.
Ifyouarefamiliarwithbash,youwillnoticesomedifferencesbetweenthetwoshells.Forinstance,the
syntaxyouusetoassignavaluetoavariablediffersandtcshallowsSPACEsaroundtheequalsign.
Bothnumericandnonnumericvariablesarecreatedandgivenvaluesusingthesetbuiltin.The@builtin
canevaluatenumericexpressionsforassignmenttonumericvariables.
setenv
Becausethereisnoexportbuiltinintcsh,youmustusethesetenvbuiltintocreateanenvironment
(global)variable.Youcanalsoassignavaluetothevariablewiththesetenvcommand.Thecommand
unsetremovesbothlocalandenvironmentvariables,whereasthecommandunsetenvremovesonly
environmentvariables.
Aliases
Thesyntaxofthetcshaliasbuiltinisslightlydifferentfromthatofaliasinbash.Unlikebash,
thetcshaliasespermityoutosubstitutecommandlineargumentsusingthehistorymechanismsyntax.
Mostothertcshfeatures,suchashistory,wordcompletion,andcommandlineediting,closelyresemble
theirbashcounterparts.Thesyntaxofthetcshcontrolstructuresisslightlydifferentbutprovides
functionalityequivalenttothatfoundinbash.
Globbing
Thetermglobbing,acarryoverfromtheoriginalBourneShell,referstothematchingofstringscontaining
specialcharacters(suchas*and?)tofilenames.Iftcshisunabletogeneratealistoffilenames
matchingaglobbingpattern,itdisplaysanerrormessage.Thisbehaviorcontrastswiththatofbash,
whichsimplyleavesthepatternalone.
Standardinputandstandardoutputcanberedirectedintcsh,butthereisnostraightforwardwayto
redirectthemindependently.Doingsorequiresthecreationofasubshellthatredirectsstandardoutputto
afilewhilemakingstandarderroravailabletotheparentprocess.
Exercises
Assumethatyouareworkingwiththefollowinghistorylist:
37mailalex
38cd/home/jenny/correspondence/business/cheese_co
39lessletter.0321
40vimletter.0321
1.
41cpletter.0321letter.0325
42grephansenletter.0325
43vimletter.0325
44lprletter*
45cd../milk_co
46pwd
47vimwilson.0321wilson.0329
Usingthehistorymechanism,givecommandsto
1. SendmailtoAlex.
2. Usevimtoeditafilenamedwilson.0329.
3. Sendwilson.0329totheprinter.
4. Sendbothwilson.0321andwilson.0329totheprinter.
2. Howcanyoudisplaythealiasescurrentlyineffect?Writeanaliasnamedhomedotsthatliststhenames(only)ofallinvisiblefilesin
yourhomedirectory.
3. Howcanyoupreventacommandfromsendingoutputtotheterminalwhenyoustartitinthebackground?Whatcanyoudoifyoustart
acommandintheforegroundandlaterdecidethatyouwantittoruninthebackground?
4. Whatstatementcanyouputinyour~/.tcshrcfiletopreventaccidentallyoverwritingafilewhenyouredirectoutput?Howcanyou
overridethisfeature?
5.
Assumethattheworkingdirectorycontainsthefollowingfiles:
adams.ltr.03
adams.brief
adams.ltr.07
abelson.09
abelson.brief
anthony.073
anthony.brief
azevedo.99
WhathappensifyoupressTABaftertypingthefollowingcommands?
1. lessadams.l
2. cata
3. lsant
4. fileaz
WhathappensifyoupressCONTROL-Daftertypingthefollowingcommands?
5. lsab
6. lessa
6. Writeanaliasnamedbackupthattakesafilenameasanargumentandcreatesacopyofthatfilewiththesamenameandafilename
extensionof.bak.
7. Writeanaliasnamedqmake(quietmake)thatrunsmakewithbothstandardoutputandstandarderrorredirectedtothefilenamed
make.log.Thecommandqmakeshouldacceptthesameoptionsandargumentsasmake.
8. Howcanyoumaketcshalwaysdisplaythepathnameoftheworkingdirectoryaspartofitsprompt?
AdvancedExercises
9. WhatlinesdoyouneedtochangeintheBourneAgainShellscriptcommand_menu(page462)toturnitintoaTCShellscript?Make
thechangesandverifythatthenewscriptworks.
10.
Usersoftenfindrm(andevenrmi)toounforgivingbecauseitremovesfilesirrevocably.Createanaliasnameddeletethatmovesfiles
specifiedbyitsargument(s)intothe~/.trashdirectory.Createasecondaliasnamedundeletethatmovesafilefromthe~/.trash
directoryintotheworkingdirectory.Putthefollowinglineinyour~/.logoutfiletoremoveanyfilesthatyoudeletedduringthelogin
session:
/bin/rm-f$HOME/.trash/*>&/dev/null
Explainwhatcouldbedifferentifthefollowinglinewereputinyour~/.logoutfileinstead:
rm$HOME/.trash/*
11. Modifytheforeach_1script(page374)sothatittakesthecommandtoexecasanargument.
12. Rewritetheprogramwhile_1(page375)sothatitrunsfaster.Usethetimebuiltintoverifytheimprovementinexecutiontime.
13.
Writeyourownversionoffindnamedmyfindthatwritesoutputtothefilefindoutbutwithouttheclutteroferrormessages,suchas
thosegeneratedwhenyoudonothavepermissiontosearchadirectory.Themyfindcommandshouldacceptthesameoptionsand
argumentsasfind.Canyouthinkofasituationinwhichmyfinddoesnotworkasdesired?
14. Whentheforeach_1script(page374)issuppliedwith20orfewerarguments,whyarethecommandsfollowingtoomany:not
executed?(Whyistherenoexitcommand?)
Chapter10.ProgrammingTools
INTHISCHAPTER
ProgramminginC388
UsingSharedLibraries396
make:KeepsaSetofProgramsCurrent399
DebuggingCPrograms407
Threads417
SystemCalls417
SourceCodeManagement420
CVS:ConcurrentVersionsSystem420
Withitsrichsetoflanguagesanddevelopmenttools,theLinuxoperatingsystemprovidesanoutstanding
environmentforprogramming.Cisoneofthemostpopularsystemprogramminglanguagestousein
conjunctionwithLinux,inpartbecausetheoperatingsystemitselfiswrittenmostlyinC.UsingC,
programmerscaneasilyaccesssystemservicesusingfunctionlibrariesandsystemcalls.Inaddition,a
varietyofhelpfultoolscanfacilitatethedevelopmentandmaintenanceofprograms.
ThischapterexplainshowtocompileandlinkCprograms.ItintroducestheGNUgdbdebuggerand
toolsthatprovidefeedbackaboutmemory,disk,andCPUresources.Italsocoverssomeofthemost
usefulsoftwaredevelopmenttools:themakeutilityandCVS.Themakeutilityhelpsyoukeeptrackof
whichprogrammoduleshavebeenupdatedandhelpstoensurethatyouusethelatestversionsofall
programmoduleswhenyoucompileaprogram.CVS(ConcurrentVersionsSystem)isasourcecode
managementsystemthattrackstheversionsoffilesinvolvedinaproject.
ProgrammingInC
AmajorreasonthattheLinuxsystemprovidesanexcellentCprogrammingenvironmentisthatC
programscaneasilyaccesstheservicesoftheoperatingsystem.Thesystemcallstheroutinesthatmake
operatingsystemservicesavailabletoprogrammerscanbecalledfromCprograms.Thesesystemcalls
providesuchservicesascreatingfiles,readingfromandwritingtofiles,collectinginformationabout
files,andsendingsignalstoprocesses.WhenyouwriteaCprogram,youcanusesystemcallsinthesame
wayyouuseordinaryCprogrammodules,orfunctions,thatyouhavewritten.Formoreinformationrefer
to"SystemCalls"onpage417.
SeverallibrariesoffunctionshavebeendevelopedtosupportprogramminginC.Thelibrariesare
collectionsofrelatedfunctionsthatyoucanusejustasyouuseyourownfunctionsandthesystemcalls.
Manyofthelibraryfunctionsaccessbasicoperatingsystemservicesthroughthesystemcalls,providing
theservicesinwaysthataremoresuitedtotypicalprogrammingtasks.Otherlibraryfunctions,suchasthe
mathlibraryfunctions,servespecialpurposes.
ThischapterdescribestheprocessesofwritingandcompilingCprograms.However,itwillnotteach
youtoprograminC.
CheckingYourCompiler
TheCcompilerincommonuseonLinuxisGNUgcc(www.gnu.org/software/gcc/gcc.html),which
comesaspartofmostdistributions.Givethefollowingcommandtoseeifyouhaveaccesstothegcc
compiler:
$gcc--version
bash:gcc:commandnotfound
Ifyougetaresponseotherthanversioninformation,eitherthecompilerisnotinstalledoryourPATH
variabledoesnotcontainthenecessarypathname(usuallygccisinstalledin/usr/bin).Ifyougetversion
informationfromthegcccommand,theGNUCcompilerisinstalled.
Nextmakesurethatthecompilerisfunctioning.Asasimpletest,createafilenamedMakefilewiththe
followinglines.ThelinethatstartswithgccmustbeindentedbyusingaTAB,notSPACEs.
$catMakefile
morning:morning.c
TABgcc-omorningmorning.c
Nowcreateasourcefilenamedmorning.cwiththefollowinglines:
$catmorning.c
#include<stdio.h>
intmain(intargc,char**argv){
printf("GoodMorning\n");
return0;
}
Compilethefilewiththecommandmakemorning.Whenitcompilessuccessfully,runtheprogramby
givingthecommandmorningor./morning.Whenyougetoutputfromthisprogram,youknowthatyou
haveaworkingCcompiler:
$makemorning
gcc-omorningmorning.c
$morning
GoodMorning
ACProgrammingExample

Youmustuseaneditor,suchasemacsorvim,tocreateorchangeaCprogram.ThenameoftheC
programfilemustendin.c.Enteringthesourcecodeforaprogramissimilartotypingamemoorshell
script.Althoughemacsandvim"know"thatyouareeditingaCprogram,manyeditorsdonotknow
whetheryourfileisaCprogram,ashellscript,oranordinarytextdocument.Youareresponsiblefor
makingthecontentsofthefilesyntacticallysuitablefortheCcompilertoprocess.
Figure10-1illustratesthestructureofasimpleCprogramnamedtabs.c.Thefirsttwolinesofthe
programarecommentsthatdescribewhattheprogramdoes.Thestring/*identifiesthebeginningofthe
comment,andthestring*/identifiestheendofthecomment;theCcompilerignoresallthecharacters
betweenthem.Becauseacommentcanspantwoormorelines,the*/attheendofthefirstlineandthe/*
atthebeginningofthesecondlinearenotnecessarybutareincludedforclarity.Asthecommentexplains,
theprogramreadsstandardinput,convertsTABcharactersintotheappropriatenumberofspaces,and
writesthetransformedinputtostandardoutput.LikemanyLinuxutilities,thisprogramisafilter.
Figure10-1.AsimpleCprogram:tabs.c(Thelinenumbersarenotpartofthesource
code.)
[Viewfullsizeimage]
Followingthecommentsatthetopoftabs.carepreprocessordirectives,whichareinstructionsfortheC
preprocessor.DuringtheinitialphaseofcompilationtheCpreprocessorexpandsthesedirectives,making
theprogramreadyforthelaterstagesofthecompilationprocess.Preprocessordirectivesbeginwiththe
poundsign(#)andmayoptionallybeprecededbySPACEandTABcharacters.
Symbolicconstants
Youcanusethe#definepreprocessordirectivetodefinesymbolicconstantsandmacros.Symbolic
constantsarenamesthatyoucanuseinaprograminplaceofconstantvalues.Forexample,tabs.cusesa
#definepreprocessordirectivetoassociatethesymbolicconstantTABSIZEwiththeconstant8.
TABSIZEisusedintheprograminplaceoftheconstant8asthedistancebetweenTABstops.By
conventionthenamesofsymbolicconstantsconsistofalluppercaseletters.
Bydefiningsymbolicnamesforconstantvaluesyoucanmakeaprogrameasiertoreadandeasierto
modify.Ifyoulaterdecidetochangeaconstant,youneedtochangeonlythepreprocessordirectiverather
thanthevalueeverywhereitoccursintheprogram.Ifyoureplacethe#definedirectiveforTABSIZEin
Figure10-1withthefollowingdirective,theprogramwillplaceTABstopseveryfourcolumnsrather
thaneveryeight:
#defineTABSIZE4
Asymbolicconstant,whichisatypeofmacro,mapsasymbolicnametoreplacementtext.Macrosare
handywhenthereplacementtextisneededatmultiplepointsthroughoutthesourcecodeorwhenthe
definitionofthemacroissubjecttochange.Theprocessofsubstitutingthereplacementtextforthe
symbolicnameiscalledmacroexpansion.
Macros
Youcanalsouse#definedirectivestodefinemacroswitharguments.Useofsuchamacroresemblesa
functioncall.UnlikeCfunctions,however,macrosarereplacedwithCcodepriortocompilationinto
objectfiles.
TheNEXTTABmacrocomputesthedistancetothenextTABstop,giventhecurrentcolumnposition
curcol:
#defineNEXTTAB(curcol)(TABSIZE-((curcol)%TABSIZE))
ThisdefinitionusesthemacroTABSIZE,whosedefinitionmustappearpriortoNEXTTABinthesource
code.ThemacroNEXTTABcouldbeusedintabs.ctoassignavaluetoretvalinthefunctionfindstop:
retval=NEXTTAB(*col);
Headers(includefiles)
Whenmodulesofaprogramuseseveralmacrodefinitions,thedefinitionsaretypicallycollectedtogether
inasinglefilecalledaheaderfileoranincludefile.AlthoughtheCcompilerdoesnotplaceconstraints
onthenamesofheaderfiles,byconventiontheyendin.h.Thenameoftheheaderfileislistedinan
#includepreprocessordirectiveineachprogramsourcefilethatusesanyofthemacros.Theprogramin
Figure10-1usesgetcharandputchar,whicharemacrosdefinedinstdio.h.Thestdio.hheaderfile
definesavarietyofgeneral-purposemacrosandisusedbymanyClibraryfunctions.
Theanglebrackets(<and>)thatsurroundstdio.hintabs.cinstructtheCpreprocessortolookforthe
headerfileinastandardlistofdirectories(suchas/usr/include).Toincludeaheaderfilefromanother
directory,encloseitspathnamebetweendoublequotationmarks.Youcanspecifyanabsolutepathname
withinthedoublequotationmarksoryoucangivearelativepathname.Ifyougivearelativepathname,
searchingbeginswiththeworkingdirectoryandthenmovestothesamedirectoriesthataresearched
whentheheaderfileissurroundedbyanglebrackets.Byconventionheaderfilesthatyousupplyare
surroundedbydoublequotationmarks.
YoucanalsospecifydirectoriestobesearchedforheaderfilesbyusingtheIoptiontotheCcompiler.
Assumethatyouwanttocompiletheprogramderiv.c,whichcontainsthefollowingpreprocessor
directive:
#include"eqns.h"
Iftheheaderfileeqns.hislocatedinthesubdirectorymyincludes,youcancompilederiv.cwiththeI
optiontotelltheCpreprocessortolookforthefileeqns.hthere:
$gcc-I./myincludesderiv.c
WhentheCpreprocessorencountersthe#includedirectiveinthederiv.cfile,itwilllookforeqns.hin
themyincludessubdirectoryoftheworkingdirectory.
tip:Userelativepathnamesforincludefiles
Usingabsolutepathnamesforincludefilesdoesnotworkifthelocationoftheheaderfile
withinthefilesystemchanges.Usingrelativepathnamesforheaderfilesworksaslongas
thelocationoftheheaderfilerelativetotheworkingdirectoryremainsthesame.Relative
pathnamesalsoworkwiththeIoptiononthegcccommandlineandallowheaderfilesto
bemoved.
Functionprototype
Precedingthedefinitionofthefunctionmainisafunctionprototype.Thisdeclarationtellsthecompiler
whattypeafunctionreturns,howmanyargumentsafunctionexpects,andwhatthetypesofthose
argumentsare.Intabs.ctheprototypeforthefunctionfindstopinformsthecompilerthatfindstopreturns
typeintandthatitexpectsasingleargumentoftypepointertoint:
intfindstop(int*);
Oncethecompilerhasseenthisdeclaration,itcandetectandflaginconsistenciesinthedefinitionandthe
usesofthefunction.Asanexample,supposethatthereferencetofindstopintabs.cwasreplacedwiththe
followingstatement:
inc=findstop();
Theprototypeforfindstopwouldcausethecompilertodetectamissingargumentandissueanerror
message.Youcouldtheneasilyfixtheproblem.Whenafunctionispresentinaseparatesourcefileoris
definedafteritisreferencedinasourcefile(asfindstopisintheexample),thefunctionprototypehelps
thecompilercheckthatthefunctionisbeingcalledproperly.Withouttheprototype,thecompilerwould
notissueanerrormessageandtheproblemmightmanifestitselfasunexpectedbehaviorduringexecution.
Atthislatepoint,findingthebugmightbedifficultandtime-consuming.
Functions
AlthoughyoucancallmostCfunctionsanythingyouwant,eachprogrammusthaveexactlyonefunction
namedmain.Thefunctionmainisthecontrolmodule:Aprogrambeginsexecutionwiththefunction
main,whichtypicallycallsotherfunctions,whichinturnmaycallstillotherfunctions,andsoforth.By
puttingdifferentoperationsintoseparatefunctions,youcanmakeaprogrameasiertoreadandmaintain.
Forexample,theprograminFigure10-1usesthefunctionfindstoptocomputethedistancetothenext
TABstop.Althoughthefewstatementsoffindstopcouldeasilyhavebeenincludedinthemainfunction,
isolatingtheminaseparatefunctiondrawsattentiontoakeycomputation.
Functionscanmakebothdevelopmentandmaintenanceoftheprogrammoreefficient.Byputtinga
frequentlyusedcodesegmentintoafunction,youavoidenteringthesamecodeintotheprogramoverand
overagain.Whenyoulaterwanttomakechangestothecode,youneedchangeitonlyonce.
Ifaprogramislongandincludesseveralfunctions,youmaywanttosplititintotwoormorefiles.
Regardlessofitssize,youmaywanttoplacelogicallydistinctpartsofaprograminseparatefiles.AC
programcanbesplitintoanynumberofdifferentfiles;however,eachfunctionmustbewhollycontained
withinasinglefile.
tip:Useaheaderfileformultiplesourcefiles
Whenyouarecreatingaprogramthattakesadvantageofmultiplesourcefiles,put#define
preprocessordirectivesintoaheaderfileanduseanincludestatementwiththenameofthe
headerfileinanysourcefilethatusesthedirectives.
CompilingandLinkingaCProgram
Tocompiletabs.candcreateanexecutablefilenameda.out,givethefollowingcommand:
$gcctabs.c
ThegccutilitycallstheCpreprocessor,theCcompiler,theassembler,andthelinker.Figure10-2shows
thesefourcomponentsofthecompilationprocess.TheCpreprocessorexpandsmacrodefinitionsand
includesheaderfiles.Thecompilationphasecreatesassemblylanguagecodecorrespondingtothe
instructionsinthesourcefile.Thentheassemblercreatesmachine-readableobjectcode.Oneobjectfile
iscreatedforeachsourcefile.Eachobjectfilehasthesamenameasthesourcefile,exceptthatthe.c
extensionisreplacedwitha.o.Theprecedingexamplecreatesasingleobjectfilenamedtabs.o.After
successfullycompletingallphasesofthecompilationprocessforaprogram,theCcompilercreatesthe
executablefileandthenremovesany.ofiles.

Figure10-2.Thecompilationprocess
Duringthefinalphaseofthecompilationprocess,thelinkersearchesspecifiedlibrariesforfunctionsthe
programusesandcombinesobjectmodulesforthosefunctionswiththeprogram'sobjectmodules.By
defaulttheCcompilerlinksthestandardClibrarylibc.so(usuallyfoundin/lib),whichcontainsfunctions
thathandleinputandoutputandprovidesmanyothergeneral-purposecapabilities.Ifyouwantthelinker
tosearchotherlibraries,youmustusethel(lowercase"l")optiontospecifythelibrariesonthecommand
line.UnlikemostoptionstoLinuxsystemutilities,theloptiondoesnotcomebeforeallfilenamesonthe
commandlinebutusuallyappearsafterthefilenamesofallmodulesthatitappliesto.Inthenextexample,
theCcompilersearchesthemathlibrarylibm.so(usuallyfoundin/lib):
$gcccalc.c-lm
Theloptionusesabbreviationsforlibrarynames,appendingtheletterfollowingltolibandaddinga.so
or.aextension.Themintheexamplestandsforlibm.so.
Usingthesamenamingmechanism,youcanhaveagraphicslibrarynamedlibgraphics.a,whichcanbe
linkedwiththefollowingcommand:
$gccpgm.c-lgraphics
Whenyouusethisconventiontonamelibraries,gccknowstosearchforthemin/usr/liband/lib.You
canhavegccalsosearchotherdirectoriesbyusingtheLoption:

$gccpgm.c-L.-L/usr/X11R6/lib-lgraphics
Theprecedingcommandcausesgcctosearchforthelibraryfilelibgraphics.aintheworkingdirectory
andin/usr/X11R6/libbeforesearching/usr/liband/lib.
Asthelaststepofthecompilationprocess,thelinkercreatesanexecutablefilenameda.outunlessyou
specifyadifferentfilenamewiththeooption.Objectfilesaredeletedaftertheexecutableiscreated.
ELFformat
Youmayoccasionallyencounterreferencestothea.outformat,anoldUNIXbinaryformat.Linuxusesthe
ExecutableandLinkingFormat(ELF)forbinaries;recentversionsofgccproducethisformatnotthe
a.outformat,inspiteofthefilename.Usethefileutility(page653)todeterminetheformatofthe
executablethatgccgenerates:
$filea.out
a.out:ELF32-bitLSBexecutable,Intel80386,version1(SYSV),for
GNU/Linux2.2.5,
dynamicallylinked(usessharedlibs),notstripped
Inthenextexample,theO3optioncausesgcctousetheCcompileroptimizer.Theoptimizermakes
objectcodemoreefficientsothattheexecutableprogramrunsmorequickly.Optimizationhasmany
facets,includinglocatingfrequentlyusedvariablesandtakingadvantageofprocessor-specificfeatures.
ThenumberaftertheOindicatesthelevelofoptimization,whereahighernumberspecifiesmore
optimization.Seethegccinfopageforspecifics.Thefollowingexamplealsoshowsthatthe.ofiles
arenotpresentaftera.outiscreated:
$ls
acctspay.cacctsrec.cledger.c
$gcc-O3ledger.cacctspay.cacctsrec.c
$ls
a.outacctspay.cacctsrec.cledger.c
Youcanusetheexecutablea.outinthesamewayyouuseshellscriptsandotherprograms:bytypingits
nameonthecommandline.TheprograminFigure10-1onpage390expectstoreadfromstandardinput,
soonceyouhavecreatedtheexecutablea.outyoucanuseacommandsuchasthefollowingtorunit:
$./a.out<mymemo
Ifyouwanttosavethea.outfile,youshouldchangethenametoamoredescriptiveone.Otherwise,you
mightaccidentallyoverwriteitduringalatercompilation:
$mva.outaccounting
Tosaveyourselfthetroubleofrenamingana.outfile,youcanspecifythenameoftheexecutablefile
whenyouusegcc.TheooptioncausestheCcompilertogivetheexecutablethenameyouspecify
ratherthana.out.Inthenextexample,theexecutableisnamedaccounting:
$gcc-oaccountingledger.cacctspay.cacctsrec.c
Ifaccountingdoesnotrequirearguments,youcanrunitwiththefollowingcommand:
$accounting
Youcansuppressthelinkingphaseofcompilationbyusingthecoptionwiththegcccommand.Thec
optiondoesnottreatunresolvedexternalreferencesaserrors;thiscapabilityenablesyoutocompileand
debugthesyntaxofthemodulesofaprogramasyoucreatethem.Onceyouhavecompiledanddebugged
allthemodules,youcanrungccagainwiththeobjectfilesasargumentstoproduceanexecutable
program.Inthenextexample,gccproducesthreeobjectfilesbutnoexecutable:
$gcc-cledger.cacctspay.cacctsrec.c
$ls
acctspay.cacctspay.oacctsrec.cacctsrec.oledger.cledger.o
Ifyouthenrungccagainandnametheobjectfilesonthecommandline,gccwillproducethe
executable.Becauseitrecognizesthefilenameextension.o,theCcompilerknowsthatthefilesneedonly
tobelinked.Youcanalsoincludeboth.cand.ofilesonasinglecommandline:
$gcc-oaccountingledger.oacctspay.cacctsrec.o
TheCcompilerrecognizesthatthe.cfileneedstobepreprocessedandcompiled,whereasthe.ofilesdo
not.TheCcompileralsoacceptsassemblylanguagefilesendingin.sandassemblesandlinksthem.This
featuremakesiteasytomodifyandrecompileaprogram.
Youcanuseseparatefilestodivideaprojectintofunctionalgroups.Forinstance,youmightputgraphics
routinesinonefile,stringfunctionsinanother,anddatabasecallsinathird.Multiplefilescanenable
severalengineerstoworkonthesameprojectconcurrentlyandcanspeedupcompilation.Ifallfunctions
areinonefileandyoumakeachange,thecompilermustrecompileallfunctionsinthefile.Thusthe
entireprogramwillberecompiled,whichmaytakeconsiderabletimeevenifyoumadeonlyasmall
change.Whenyouuseseparatefiles,onlythefilethatyouchangemustberecompiled.Forlargeprograms
withmanysourcefiles(forexample,theCcompileroremacs),thetimelostbyrecompilingonehuge
fileforeverysmallchangewouldbeenormous.Formoreinformation,referto"make:KeepsaSetof
ProgramsCurrent"onpage399.
tip:Whatnottonameaprogram
Donotnameaprogramtestoranyothernameofabuiltinorotherexecutableonthelocal
system.Ifyoudo,youwilllikelyexecutethebuiltinorotherprograminsteadofthe
programyouintendtorun.Usewhich(page61)todeterminewhichprogramyouwillrun
whenyougiveacommand.
UsingSharedLibraries
Mostmodernoperatingsystemsusesharedlibraries,alsocalleddynamiclibraries.Theselibrariesare
notlinkedintoaprogramatcompiletimebutratherareloadedwhentheprogramstarts(orlaterinsome
cases).Thenamesoffileshousingsharedlibrarieshavefilenameextensionsof.so(sharedobject)for
examplelibc.so.Usuallylibaaa.soisasymboliclinktolibaaa.so.x,wherexisasmallnumber
representingtheversionofthelibrary.Manyoftheselibrariesarekeptin/usr/lib:AtypicalLinux
installationhasmorethan300sharedlibrariesin/usr/libandmorethan30in/usr/X11R6/lib.
Applicationscanhavetheirownsharedlibraries.Forexample,thegcccompilermightkeepitslibraries
in/usr/lib/gcc-lib/i386-redhat-linux/3.4.0.
Archivedlibraries
Incontrasttosharedlibrariesaretheolder,staticallylinkedlibraries(witha.afilenameextension),also
calledarchivedlibraries.Archivedlibrariesareaddedtotheexecutablefileduringthelast(link)phase
ofcompilation.Thisadditioncanmakeaprogramrunslightlyfasterthefirsttimeitisrun,albeitatthe
expenseofprogrammaintainabilityandsize.Takentogether,thecombinedsizeofseveralexecutablesthat
useasharedlibraryandthesizeofthesharedlibraryaresmallerthanthecombinedsizeofthesame
executableswithstaticlibraries.Whenarunningprogramhasalreadyloadedadynamiclibrary,asecond
programthatrequiresthesamedynamiclibrarystartsslightlyfaster.
Reducingmemoryusageandincreasingmaintainabilityaretheprimaryreasonsforusingsharedobject
libraries;theyhavelargelyreplacedstaticallylinkedlibrariesasthelibrarytypeofchoice.Consider
whathappenswhenyoudiscoveranerrorinalibrary.Withastaticlibrary,youneedtorelinkevery
programthatusesthelibraryoncethelibraryhasbeenfixedandrecompiled.Withadynamiclibrary,you
needtofixandrecompileonlythelibraryitself.
Sharedobjectlibrariesalsomakedynamicloadingofprogramlibrariesontheflypossible(forexample,
perl,python,andtclextensionsandmodules).TheApache(HTTP)Webserverspecifiesmodules
inthehttpd.conffileandloadsthemasneeded.
ldd
Theldd(listdynamicdependencies)utilitytellsyouwhichsharedlibrariesaprogramneeds.The
followingexampleshowsthatcpuseslibacl,theAccessControlListslibrary;libc,theClibrary;libattr,
theExtendedAttributeslibrary;andld-linux,theruntimelinker:
$ldd/bin/cp
libacl.so.1=>/lib/libacl.so.1(0x40026000)
libc.so.6=>/lib/i686/libc.so.6(0x42000000)
libattr.so.1=>/lib/libattr.so.1(0x4002d000)
/lib/ld-linux.so.2=>/lib/ld-linux.so.2(0x40000000)
Runninglddon/usr/bin/gnome-session(aprogramthatstartsagraphicalGNOMEsession)lists59
librariesfrom/usr/lib,/usr/X11R6/lib,and/lib.
Theprogramthatdoesthedynamicruntimelinking,ld-linux.so,alwayslooksin/usr/libfor
libraries.Theotherdirectoriesthatldsearchesvarydependingonhowldissetup.Youcanadd
directoriesforldtolookinbyspecifyingasearchpathatcompile(actuallylink)time,usingtheroption
followedbyacolon-separatedlistofdirectories(donotputaSPACEafterr).Useonlyabsolute
pathnamesinthesearchpath.Althoughyouusethisoptiononthegcccommandline,itispassedtothe
linker(ld).Thegnome-sessiondesktopmanagerwaslikelylinkedwithacommandsuchasthe
following:
gccflagsognome-sessionobjectsr/lib:/usr/X11R6/liblibraries
Thiscommandlineallowsld.so(andldd)tosearch/liband/usr/X11R6/libinadditiontothe
standard/usr/libforthelibrariesneededbytheexecutable.
Thecompilerneedstoseethesharedlibrariesatlinktimetomakesurethattheneededfunctionsand
proceduresarepresentaspromisedbytheheader(.h)files.UsetheLoptiontotellthecompile-time
linkertolookinthedirectorymylibforsharedorstaticlibraries:Lmylib.Unlikethesearchpath,Lcan
userelativepathnamessuchasL../libhandywhenaprogrambuildsitsownsharedlibrary.Thelibrary
canbeinonelocationatbuildtime(L)butinanotherlocationatruntimeafteritisinstalled(rpath).The
SPACEafterLisoptionalandisusuallyomitted;rmustnotbefollowedbyaSPACE.Youcanrepeatthe
Landtheroptionsmultipletimesonthelinkline.
FixingBrokenBinaries
Thecommandlinesearchpathisafairlynewidea.Thesearchpathwastraditionallycreatedbyusingthe
LD_LIBRARY_PATHand,morerecently,theLD_RUN_PATHenvironmentvariables.Thesevariables
havethesameformatasPATH(page284).
ThedirectoriesinLD_LIBRARY_PATHarenormallysearchedbeforetheusuallibrarylocations.
NewerLinuxreleasesextendthefunctionofLD_LIBRARY_PATHtospecifydirectoriestobesearched
eitherbeforeorafterthenormallocations.Seetheldmanpagefordetails.TheLD_RUN_PATH
variablebehavessimilarlytoLD_LIBRARY_PATH.Ifyouuser,however,LD_LIBRARY_PATH
supersedesanythinginLD_RUN_PATH.
TheuseofLD_LIBRARY_PATHbringsupseveralproblems.Becauseonlyoneenvironmentvariable
exists,itmustbesharedamongallprograms.Iftwoprogramshavethesamenameforalibraryoruse
different,incompatibleversionsofthesamelibrary,onlythefirstwillbefound.Asaresultoneofthe
programswillnotrunorworsewillnotruncorrectly.
security:LD_LIBRARY_PATH
UndercertaincircumstancesamalicioususercancreateaTrojanhorsenamedlibc.soand
placeitinadirectorythatissearchedbefore/usr/lib(anydirectoryin
LD_LIBRARY_PATH,whichappearsbefore/usr/lib).Thefakelibcwillthenbeused
insteadofthereallibc.
Wrappers
LD_LIBRARY_PATHstillhasitsplaceinthescripts,calledwrappers,thatareusedtofixbroken
binaries.Supposethatthebrokenbinarybbusesthesharedlibrarylibbb.so,whichyouwanttoputin
/opt/bb/libandnotin/usr/lib,asthebbprogrammerrequested.Thecommandlddbbwilltellyouwhich
librariesaremissing.Notaproblem:Renamebbtobb.broken,andcreatea/bin/shwrappernamedbb.
#!/bin/sh
LD_LIBRARY_PATH=/opt/bb/lib
exportLD_LIBRARY_PATH
execbb.broken"$@"
(Using$@ratherthan$*preservesSPACEsintheparameters;seepage482.)Awrappercanalsoallow
youtoinstallprogramsinarbitrarylocations.
CreatingSharedLibraries
Buildingadynamicallyloadablesharedlibraryisnotatrivialmatter:Itinvolvesusingreentrantfunction
calls,definingalibraryentranceroutine,andperformingothertasks.Whenyouwanttocreateashared
objectlibrary,youmustataminimumcompilethesourcefileswiththefPIC(position-independentcode)
optiontogccandlinktheresultingobjectfilesintothelibxx.sofileusingthesharedxoptionstothe
linker(forexample,ldsharedxolibmylib.so*.o).Thebestresourceforinvestigatingsharedlibrary
constructionandusageisexistingcodeontheInternet.Forexample,youcanlookatthesourcefilesfor
zlib(www.gzip.org/zlib).
C++
C++fileshavespecialneeds,andlibraries(sharedornot)oftenhavetobemadebythecompilerrather
thanldorar.Sharedlibrariescandependonothersharedlibrariesandhavetheirownsearchpaths.If
yousetLD_LIBRARY_PATH,addtheiflagtothelinkphasewhencompilingtoignorethecurrent
LD_LIBRARY_PATHoryoumayhaveunexpectedresults.Ideally,youwouldnothave
LD_LIBRARY_PATHsetonagloballevelbutwoulduseitonlyinwrappersasneeded.

make:KeepsaSetofProgramsCurrent
tip:ThissectioncoverstheGNUmakeprogram
ThissectiondescribestheGNUmakeprogram.Othermaketools(BSNmake,GNUStep
make,Borlandmake,andsoon)areavailableaswellassimilartoolssuchasant(the
Apachebuildtool).MakefilescreatedforGNUmakeareoftenincompatiblewithother
maketools,whichcanbeproblematicifyouaretryingtocompilecodetargetedfor
anotherplatform.
Inalargeprogramwithmanysourceandheaderfiles,thefilestypicallydependononeanotherin
complexways.Whenyouchangeafilethatotherfilesdependon,youmustrecompilealldependentfiles.
Forexample,youmighthaveseveralsourcefiles,allofwhichuseasingleheaderfile.Whenyouchange
theheaderfile,youmustrecompileeachofthesourcefiles.Theheaderfilemightdependonotherheader
files,andsoforth.Figure10-3showsasimpleexampleofdependencyrelationships.Eacharrowinthis
figurepointsfromafiletoanotherfilethatdependsonit.
Figure10-3.Dependencygraphforthetargetform
Whenyouareworkingonalargeprogram,itcanbedifficult,time-consuming,andtedioustodetermine
whichmodulesneedtoberecompiledbecauseoftheirdependencyrelationships.Themakeutility
automatesthisprocess.
Dependencylines:targetfilesandprerequisitefiles
Atitssimplest,makelooksatdependencylinesinafilenamedMakefileormakefileintheworking
directory.Thedependencylinesindicaterelationshipsamongfiles,specifyingatargetfilethatdepends
ononeormoreprerequisitefiles.Ifyouhavemodifiedanyoftheprerequisitefilesmorerecentlythan
theirtargetfile,makeupdatesthetargetfilebasedonconstructioncommandsthatfollowthedependency
line.Themakeutilitynormallystopsifitencountersanerrorduringtheconstructionprocess.
Thefilecontainingtheupdatinginformationforthemakeutilityiscalledamakefile.(Seepage388fora
trivialexample.)Asimplemakefilehasthefollowingsyntax:
target:prerequisite-list
TABconstruction-commands
Thedependencylineconsistsofthetargetandtheprerequisite-list,separatedbyacolon.Each
construction-commandsline(youmayhavemorethanone)muststartwithaTABandmustfollowthe
dependencyline.LonglinescanbecontinuedwithaBACKSLASH(\)asthelastcharacterontheline.
Thetargetisthenameofthefilethatdependsonthefilesintheprerequisite-list.Theconstruction-
commandsareregularshellcommandsthatconstruct(usuallycompileand/orlink)thetargetfile.The
makeutilityexecutestheconstruction-commandswhenthemodificationtimeofoneormorefilesinthe
prerequisite-listismorerecentthanthatofthetargetfile.
Thefollowingexampleshowsthedependencylineandconstructioncommandsforthefilenamedformin
Figure10-3.Theformfiledependsontheprerequisitessize.oandlength.o.Anappropriategcc
commandconstructsthetarget:
form:size.olength.o
TABgcc-oformsize.olength.o
Eachoftheprerequisitesononedependencylinecanbeatargetonanotherdependencyline.For
example,bothsize.oandlength.oaretargetsonotherdependencylines.AlthoughtheexampleinFigure
10-3issimple,thenestingofdependencyspecificationscancreateacomplexhierarchythatdictates
relationshipsamongmanyfiles.
Thefollowingmakefile(namedMakefile)correspondstothecompletedependencystructureshownin
Figure10-3.Theexecutablefileformdependsontwoobjectfiles,andtheobjectfileseachdependon
theirrespectivesourcefilesandaheaderfile,form.h.Inturn,form.hdependsontwootherheaderfiles.
$catMakefile
form:size.olength.o
gcc-oformsize.olength.o
size.o:size.cform.h
gcc-csize.c
length.o:length.cform.h
gcc-clength.c
form.h:num.htable.h
catnum.htable.h>form.h
Althoughthelastlinewouldnotnormallybeseeninamakefile,itillustratesthefactthatyoucanputany
shellcommandonaconstructionline.Becausetheshellprocessesmakefiles,thecommandlineshouldbe
onethatyoucouldenterinresponsetoashellprompt.
Thefollowingcommandbuildsthedefaulttargetformifanyofitsprerequisitesaremorerecentthantheir
correspondingtargetsorifanyofthetargetsdonotexist:
$make
Thus,ifthefileformhasbeendeleted,makewillrebuildit,regardlessofthemodificationdatesofits
prerequisitefiles.Thefirsttargetinamakefileisthedefaultandisbuiltwhenyoucallmakewithoutany
arguments.
Ifyouwantmaketorebuildatargetotherthanthefirstinthemakefile,youmustprovidethattargetasan
argumenttomake.Thefollowingcommandrebuildsonlyform.hifitdoesnotexistorifitsprerequisites
aremorerecentthanthetarget:

$makeform.h
ImpliedDependencies
Youcanrelyonimplieddependenciesandconstructioncommandstofacilitatethejobofwritinga
makefile.Forinstance,ifyoudonotincludeadependencylineforanobjectfile,makeassumesthatit
dependsonacompilerorassemblersourcecodefile.Thus,ifaprerequisiteforatargetfileisxxx.oand
nodependencylineidentifiesxxx.oasatarget,makelooksattheextensiontodeterminehowtobuildthe
.ofile.Ifitfindsanappropriatesourcefile,makeprovidesadefaultconstructioncommandlinethatcalls
thepropercompilerortheassemblertocreatetheobjectfile.Table10-1listssomefilenameextensions
thatmakerecognizesandthetypeoffilethatcorrespondstoeachsuffix.
Table10-1.Filenameextensions
Filenamewithextension Typeoffile
filename.c Cprogramminglanguagesourcecode
filename.C,filename.cc,
filename.cxx,filename.c++,
filename.cpp
C++programminglanguagesourcecode
filename.f Fortranprogramminglanguagesourcecode
filename.h Headerfile
filename.l flex,lexlexicalanalyzergeneratorsourcecode
filename.o Objectmodule
filename.s Assemblercode
filename.sh Shellscript
filename.y bison,yaccparsergeneratorsourcecode
CandC++aretraditionalprogramminglanguagesthatareavailablewithmanyLinuxdistributions.The
bisonandflextoolscreatecommandlanguages.
Inthenextexampleamakefilekeepsthefilenamedcomputeup-to-date.Themakeutilityignoresany
linethatbeginswithapoundsign(#).Thusthefirstthreelinesofthefollowingmakefilearecomment
lines.Thefirstdependencylineshowsthatcomputedependsontwoobjectfiles:compute.oandcalc.o.
Thecorrespondingconstructionlinegivesthecommandmakeneedstoproducecompute.Thesecond
dependencylineshowsthatcompute.odependsnotonlyonitsCsourcefilebutalsoonthecompute.h
headerfile.Theconstructionlineforcompute.ousestheCcompileroptimizer(O3option).Thethirdset
ofdependencyandconstructionlinesisnotrequired.Intheirabsence,makeinfersthatcalc.odependson
calc.candproducesthecommandlineneededforthecompilation:
$catMakefile
#
#Makefileforcompute
#
compute:compute.ocalc.o
gcc-ocomputecompute.ocalc.o
compute.o:compute.ccompute.h
gcc-c-O3compute.c
calc.o:calc.c
gcc-ccalc.c
clean:
rm*.o*core**~
Therearenoprerequisitesforclean,thelasttarget.Thistargetiscommonlyusedtogetridofextraneous
filesthatmaybeout-of-dateornolongerneeded,suchas.ofiles.
Followingaresomesampleexecutionsofmakebasedonthepreviousmakefile.Asthelscommand
shows,compute.o,calc.o,andcomputearenotup-to-date.Consequentlythemakecommandrunsthe
constructioncommandsthatre-createthem.
$ls-ltr
total22
-rw-rw----1alexpubs311Jun2115:56makefile
-rw-rw----1alexpubs354Jun2116:02calc.o
-rwxrwx---1alexpubs6337Jun2116:04compute
-rw-rw----1alexpubs49Jun2116:04compute.h
-rw-rw----1alexpubs880Jun2116:04compute.o
-rw-rw----1alexpubs780Jun2118:20compute.c
-rw-rw----1alexpubs179Jun2118:20calc.c
$make
gcc-c-O3compute.c
gcc-ccalc.c
gcc-ocomputecompute.ocalc.o
Ifyourunmakeonceandthenrunitagainwithoutmakinganychangestotheprerequisitefiles,make
indicatesthattheprogramisup-to-dateanddoesnotexecuteanycommands:
$make
make:'compute'isuptodate.
touch
Thenextexampleusesthetouchutilitytochangethemodificationtimeofaprerequisitefile.This
simulationshowswhathappenswhenyoualterthefile.Themakeutilityexecutesonlythecommands
necessarytobringtheout-of-datetargetsup-to-date:
$touchcalc.c
$make
gcc-ccalc.c
gcc-ocomputecompute.ocalc.o
Inthenextexample,touchchangesthemodificationtimeofcompute.h.Themakeutilityre-creates
compute.obecauseitdependsoncompute.handre-createstheexecutablebecauseitdependson
compute.o:
$touchcompute.h
$make
gcc-c-O3compute.c
gcc-ocomputecompute.ocalc.o
n
Ifyouwanttoseewhatmakewoulddoifyouranit,runmakewiththen(noexecute)option.Then
optionshowsthecommandsthatmakewouldexecutebutitdoesnotexecutethem.
t
Astheseexamplesillustrate,touchisusefulwhenyouwanttofoolmakeeitherintorecompiling
programsorintonotrecompilingthem.Youcanusetouchtoupdatethemodificationtimesofallsource
filessothatmakeconsidersnothingtobeup-to-date;makewillthenrecompileeverything.
Alternatively,youcanusetouchorthetoptiontomaketotouchallrelevantfiles;makethen
considerseverythingtobeup-to-date.Usingtouchinthismannerisusefulifthemodificationtimesof
fileshavechangedyetthefilesremainup-to-date(ascanhappenwhenyoucopyasetoffilesfromone
directorytoanother).
Thefollowingexampleusesmakenseveraltimestoseewhatmakewoulddoifyougaveamake
command.Thefirstcommandshowsthatthetarget,compute,isup-to-date.Nexttouchmakesthe
modificationdatesonallthe*.cfilesmorerecentthantheirtargetsandmakenshowswhatmakewould
doifyoucalleditwithoutthenoption.Themaketcommandthenbringsallthetargetsup-to-date.The
finalmakenconfirmsthatcomputeisup-to-date.
$make-n
make:'compute'isuptodate.
$touch*.c
$make-n
gcc-c-O3compute.c
gcc-ccalc.c
gcc-ocomputecompute.ocalc.o
$make-t
touchcompute.o
touchcalc.o
touchcompute
$make-n
make:'compute'isuptodate.
j
Thej(jobs)optionperformsanumberoftasksinparallel;thenumericargumenttojspecifiesthenumber
ofjobsorprocesses.MostmaketaskshitthediskfirstandthentheCPU,resultinginCPUusage
droppingbetweencompiles.Onamultiprocessorsystem,youcanreduceCPUusagebyusingmakejn,
wherenisthenumberofCPUsplus1.Runningtasksinparallelcansignificantlyreducethebuildtime
foralargeproject.
Onceyouaresatisfiedwiththeprogramyouhavecreated,youcanusethemakefiletoremoveextraneous
files.Itishelpfultokeepintermediatefilesaroundwhileyouarewritinganddebuggingaprogramsothat
youneedtorebuildonlytheonesthatchange.Whenyouwillnotbeworkingontheprogramforawhile,
youcanreleasethediskspace.Usingacleantargetinamakefilemeansthatyoudonothavetoremember
allthelittlepiecesthatcansafelybedeleted.Thenextexamplesimplyremovesallobject(.o)files:
$makeclean
rm*.o

optional:Macros
Themakeutility'smacrofacilityenablesyoutocreateandusemacroswithinamakefile.Thesyntaxofamacrodefinitionis
ID=list
ReplaceIDwithanidentifyingname,andreplacelistwithalistoffilenames.Afterthismacrodefinition,$(ID)representslistin
themakefile.
WithamacroyoucancompileaprogramwithanyofseveralCcompilers,makingonlyaminorchangetothemakefile.Byusing
theCCmacroandreplacingalloccurrencesofgccinthemakefileonpage402with$(CC),forexample,youneedtoassigna
valueonlytoCCtousethecompilerofyourchoice:
$catMakefile
#
#Makefileforcompute
#
CC=gcc
compute:compute.ocalc.o
$(CC)-ocomputecompute.ocalc.o
compute.o:compute.ccompute.h
$(CC)-c-O3compute.c
calc.o:calc.c
$(CC)-ccalc.c
clean:
rm*.o
Thisexampleassumesthatthecompiler/loaderflagsarethesameacrosscompilers/loaders.Inamorecomplexsituation,youneed
tocreatemacrosfortheseflagsorusethedefaultvalues.Severalcommercial,high-performancecompilersareavailableforLinux.
YoucouldspecifythecompilerfromthePortlandGroup,pgcc,byreplacingtheCC=gccassignmentwithCC=pgcc.Ifyoudo
notassignavaluetotheCCmacro,itdefaultstogccunderLinux.TheCCmacroinvokestheCcompilerwithonlytheoptions
thatyouspecify.
Severalothermacrodefinitionsarecommonlyused.TheCFLAGSmacrosendsargumentstotheCcompiler,LDFLAGSsends
argumentstothelinker(ld,orgcco),andCPPFLAGSsendsargumentstotheCpreprocessorandprogramsthatuseit,
includinggcc.TheCOMPILE.cmacroexpandsto$(CC)c$(CFLAGS)$(CPPFLAGS).TheLINK.cmacroexpandsto$(CC)
$(CFLAGS)$(CPPFLAGS)$(LDFLAGS).

BydefaultmakeinvokestheCcompilerwithoutanyoptions(exceptthecoptionwhenitisappropriatetocompilebutnottolink
afile).YoucanusetheCFLAGSmacrodefinitiontocausemaketocalltheCcompilerwithspecificoptions.Replaceoptions
withtheoptionsyouwanttouse:
CFLAGS=options
Thefollowingmakefileusesmacrosaswellasimplieddependenciesandconstructions:
#makefile:report,print,printf,printh
#
CC=gcc
CFLAGS=-O3
#commentoutthetwolinesaboveanduncommentthe
#twobelowwhenyouareusingthePortlandGroup'scompiler
#CC=pgcc
#CFLAGS=-fast
FILES=in.cout.cratio.cprocess.ctally.c
OBJECTS=in.oout.oratio.oprocess.otally.o
HEADERS=names.hcompanies.hconventions.h
report:$(OBJECTS)
$(LINK.c)-oreport$(OBJECTS)
ratio.o:$(HEADERS)
process.o:$(HEADERS)
tally.o:$(HEADERS)
print:
pr$(FILES)$(HEADERS)|lpr
printf:
pr$(FILES)|lpr
printh:

pr$(HEADERS)|lpr
Followingthecommentlinesinthisexample,themakefileusestheCFLAGSmacrotocausemakealwaystousetheoptimizer
(O3option)whenitinvokestheCcompilerastheresultofanimpliedconstruction.(TheCCandCFLAGSdefinitionsforthe
pgccCcompilerperformthesamefunctionswhentheyareuncommentedandyouareworkingwithpgcc,exceptthatyouuse
fastwithpgccwhereyouuseO3withgcc.)Aconstructionlineinamakefileoverridesthecorrespondingimpliedconstruction
line,ifoneexists.Ifyouwanttoapplyamacrotoaconstructioncommand,youmustincludethemacrointhatcommand;see
OBJECTSintheconstructioncommandforthereporttarget.FollowingCFLAGS,themakefiledefinestheFILES,OBJECTS,
andHEADERSmacros.Eachofthesemacrosdefinesalistoffiles.
ThefirstdependencylineintheprecedingexampleshowsthatreportdependsonthelistoffilesthatOBJECTSdefines.The
correspondingconstructionlinelinkstheOBJECTSandcreatesanexecutablefilenamedreport.
ThenextthreedependencylinesshowthatthreeobjectfilesdependonthelistoffilesthatHEADERSdefines.Becausethereare
noconstructionlines,makelooksforasourcecodefilecorrespondingtoeachobjectfileandcompilesit.Thesethreedependency
linesensurethattheobjectfilesarerecompiledifanyheaderfileschange.
FinallytheLINK.cmacroisinvokedtolinktheexecutablefile.IfyouspecifyanyLDFLAGS,theyareusedinthisstep.
Youcancombineseveraltargetsononedependencyline,sothesethreedependencylinescouldhavebeencombinedintooneline
asfollows:
ratio.oprocess.otally.o:$(HEADERS)
Thethreefinaldependencylinesintheprecedingexamplesendsourceandheaderfilestotheprinter.Theyhavenothingtodowith
compilingthereportfile.Noneofthesetargets(print,printf,andprinth)dependsonanything.Whenyoucalloneofthese
targetsfromthecommandline,makeexecutestheconstructionlinefollowingit.Thefollowingcommandprintsallthesource
filesthatFILESdefines:
$makeprintf
Youcanoverridemacrosinamakefilebyspecifyingthemonthecommandline.Thefollowingcommandaddsdebuggingsymbols
toallobjectfiles:
$makeCFLAGS=-g...

DebuggingCPrograms
TheCcompilerisliberalaboutthekindsofconstructsitallowsinprograms.InkeepingwiththeUNIX
philosophythat"nonewsisgoodnews"andthattheuserknowswhatisbest,gcc,likemanyotherLinux
utilities,acceptsalmostanythingthatislogicallypossibleaccordingtothedefinitionofthelanguage.
Althoughthisapproachgivestheprogrammeragreatdealofflexibilityandcontrol,itcanmake
debuggingdifficult.
Figure10-4onpage409showsbadtabs.c,aflawedversionofthetabs.cprogramdiscussedearlier.It
containssomeerrorsanddoesnotrunproperly.Thissectionusesthisprogramtoillustratesome
debuggingtechniques.
Figure10-4.Thebadtabs.cprogram(Thelinenumbersarenotpartofthesourcecode;
thearrowspointtoerrorsintheprogram.)
[Viewfullsizeimage]
Inthefollowingexample,badtabs.ciscompiledandthenrunwithinputfromthetesttabsfile.Inspection
oftheoutputshowsthattheTABcharacterhasnotbeenreplacedwiththepropernumberofSPACEs:
$gcc-obadtabsbadtabs.c
$cattesttabs
abcTABxyz
$badtabs<testtabs
abcxyz
OnewaytodebugaCprogramistoinsertprintstatementsatcriticalpointsthroughoutthesourcecode.
Tolearnmoreaboutthebehaviorofbadtabs.cwhenitruns,youcanreplacethecontentsoftheswitch
statementwith
case'\t':/*cisatab*/
fprintf(stderr,"beforecalltofindstop,posnis%d\n",posn);
inc=findstop(&posn);
fprintf(stderr,"aftercalltofindstop,posnis%d\n",posn);
for(;inc>0;inc--)
putchar('');
break;
case'\n':/*cisanewline*/
fprintf(stderr,"gotanewline\n");
putchar(c);
posn=0;
break;
default:/*cisanythingelse*/
fprintf(stderr,"gotanothercharacter\n");
putchar(c);
posn++;
break;
Thefprintfstatementsinthiscodesendtheirmessagestostandarderror.Thus,ifyouredirectstandard
outputofthisprogram,itwillnotbeinterspersedwiththeoutputsenttostandarderror.Thenextexample
demonstratestheoperationofthisprogramontheinputfiletesttabs:
$gcc-obadtabsbadtabs.c
$badtabs<testtabs>testspaces
gotanothercharacter
gotanothercharacter
gotanothercharacter
beforecalltofindstop,posnis3
aftercalltofindstop,posnis3
gotanothercharacter
gotanothercharacter
gotanothercharacter
gotanewline
$cattestspaces
abcTABxyz

Thefprintfstatementsprovideadditionalinformationabouttheexecutionoftabs.c.Thevalueofthe
variableposnisnotincrementedinfindstop,asitshouldbe.Thiscluemightbeenoughtoleadyoutothe
bugintheprogram.Ifnot,youmightattemptto"corner"theoffendingcodebyinsertingprintstatementsin
findstop.
Forsimpleprogramsorwhenyouhaveanideaofwhatiswrongwithaprogram,addingprintstatements
thattracetheexecutionofthecodecanoftenhelpyousolvetheproblemquickly.Abetterstrategymaybe
totakeadvantageofthetoolsthatLinuxprovidestohelpyoudebugprograms.
gcc:CompilerWarningOptions
Thegcccompilerincludesmanyofthefeaturesoflint,theclassicCprogramverifier,andthensome.
(ThelintutilityisnotavailableunderLinux;usesplint[secureprogramminglint;
www.splint.org]instead.)ThegcccompilercanidentifymanyCprogramconstructsthatposepotential
problems,evenforprogramsthatconformtothesyntaxrulesofthelanguage.Forinstance,youcan
requestthatthecompilerreportwhetheravariableisdeclaredbutnotused,acommentisnotproperly
terminated,orafunctionreturnsatypenotpermittedinolderversionsofC.Optionsthatenablethis
strictercompilerbehaviorallbeginwiththeuppercaseletterW(Warning).
AmongtheWoptionsisaclassofwarningsthattypicallyresultfromprogrammercarelessnessor
inexperience(seeTable10-2).Theconstructsthatgeneratethesewarningsaregenerallyeasytofixand
easytoavoid.
Table10-2.gccWoptions
Option Reportsanerrorwhen
Wimplicit Afunctionorparameterisnotexplicitlydeclared
Wreturn-type Afunctionthatisnotvoiddoesnotreturnavalueorthetypeofafunction
defaultstoint
Wunused Avariableisdeclaredbutnotused
Wcomment Thecharacters/*,whichnormallybeginacomment,occurwithina
comment
Wformat Certaininput/outputstatementscontainformatspecificationsthatdonot
matchthearguments
TheWalloptiondisplayswarningsaboutalltheerrorslistedinTable10-2,alongwithother,similar
errors.
Theprogrambadtabs.cissyntacticallycorrect:Itcompileswithoutgeneratinganerror.However,ifyou
compileit(ccausesgcctocompilebutnottolink)withtheWalloption,gccdisplaysseveral
problems.(Warningmessagesdonotstoptheprogramfromcompiling,whereaserrormessagesdo.)
$gcc-c-Wallbadtabs.c
badtabs.c:47:warning:'/*'withincomment
badtabs.c:11:warning:return-typedefaultsto'int'
badtabs.c:Infunction'main':
badtabs.c:34:warning:controlreachesendofnon-voidfunction
badtabs.c:Infunction'findstop':
badtabs.c:40:warning:unusedvariable'colindex'
badtabs.c:49:warning:controlreachesendofnon-voidfunction
Thefirstwarningmessagereferencesline47.Inspectionofthecodeforbadtabs.caroundthatline
revealsacommentthatisnotproperlyterminated.Thecompilerseesthestring/*inthefollowinglineas
thebeginningofacomment:
/*incrementargument(currentcolumnposition)tonexttabstop*/
However,becausethecharacters*and/attheendofthelineareseparatedbyaSPACE,theydonot
signifytheendofthecommenttothecompiler.Insteadthecompilerinterpretsallthestatementsincluding
thestatementthatincrementstheargumentthroughthestring*/attheveryendofthefindstopfunctionas
partofthecomment.
CompilingwiththeWalloptioncanbeveryhelpfulwhenyouaredebuggingaprogram.Afteryouremove
theSPACEbetweenthecharacters*and/,badtabsproducesthecorrectoutput.
Thenextfewparagraphsdiscusstheremainingwarningmessages.Althoughmostdonotcauseproblems
intheexecutionofbadtabs,youcangenerallyimproveaprogrambyrewritingthosepartsofthecodethat
producesuchwarnings.
Becausethedefinitionofthefunctionmaindoesnotincludeanexplicittype,thecompilerassumestype
int,thedefault.Thisresultsinthewarningmessagereferencingline11inbadtabs.c,thetopofthe
functionmain.Anadditionalwarningisgivenwhenthecompilerencounterstheendofthefunctionmain
(line34)withoutseeingavaluereturned.
Ifaprogramrunssuccessfully,byconventionitshouldreturnazerovalue;ifnovalueisreturned,theexit
codeisundefined.AlthoughmanyCprogramsdonotreturnavalue,thisoversightcancauseproblems
whentheprogramisexecuted.Whenyouaddthefollowingstatementattheendofthefunctionmainin
badtabs.c,thewarningreferencingline34disappears:
return0;
Line40ofbadtabs.ccontainsthedefinitionforthelocalvariablecolindexinthefunctionfindstop.The
warningmessagereferencingthatlineoccursbecausethecolindexvariableisneverused.Removingits
declarationeliminatesthewarningmessage.
Thefinalwarningmessage,referencingline49,resultsfromtheimproperlyterminatedcomment
discussedearlier.Thecompilerissuesthewarningmessagebecauseitneverseesareturnstatementin
findstop.(Thecompilerignorescommentedtext.)Becausethefunctionfindstopreturnstypeint,the
compilerexpectsareturnstatementbeforereachingtheendofthefunction.Thewarningdisappears
whenthecommentisproperlyterminated.
ManyotherWoptionsareavailablewiththegcccompiler.TheonesnotcoveredintheWallclassoften
dealwithportabilitydifferences;modifyingthecodecausingthesewarningsmaynotbeappropriate.The
warningsusuallyresultfromprogramsthatarewrittenindifferentCdialectsaswellasfromconstructs
thatmaynotworkwellwithother(especiallyolder)Ccompilers.Thepedantic-errorsoptionturns
warningsintoerrors,causingabuildtofailifitcontainsitemsthatwouldgeneratewarnings.Tolearn
moreabouttheseandotherwarningoptions,refertothegccinfopage.
SymbolicDebugger
Manydebuggersareavailabletotackleproblemsthatevadethesimplerdebuggingmethodssuchasprint
statementsandcompilerwarningoptions.Thesedebuggersincludegdb,kdbg,xxgdbmxgdb,ddd,
andups,whichareavailablefromtheWeb(refertoAppendixB).Allarehigh-levelsymbolicdebuggers
thatenableyoutoanalyzetheexecutionofaprogramintermsofClanguagestatements.Thedebuggers
alsoprovidealower-levelviewforanalyzingtheexecutionofaprogramintermsofthemachine
instructions.Exceptforgdb,eachofthesedebuggersprovidesaGUI.
Adebuggerenablesyoutomonitorandcontroltheexecutionofaprogram.Youcanstepthrougha
programlinebylinewhileyouexaminethestateoftheexecutionenvironment.
Coredumps
Adebuggeralsoallowsyoutoexaminecorefiles.(Corefilesarenamedcore.)Whenaseriouserror
occursduringtheexecutionofaprogram,theoperatingsystemcancreateacorefilecontaining
informationaboutthestateoftheprogramandthesystemwhentheerroroccurred.Thisfilecomprisesa
dumpofthecomputer'smemory(itwaspreviouslycalledcorememoryhencethetermcoredump)that
wasbeingusedbytheprogram.Toconservediskspace,yoursystemmaynotsavecorefiles
automatically.Youcanusetheulimitbuiltintoenablecorefilestobesaved.Ifyouarerunningbash,
thefollowingcommandallowscorefilesofunlimitedsizetobesavedtodisk:
$ulimit-cunlimited
Theoperatingsystemadvisesyouwhenitdumpscore.Youcanuseasymbolicdebuggertoread
informationfromthecorefiletoidentifythelineintheprogramwheretheerroroccurred,tocheckthe
valuesofvariablesatthatpoint,andsoforth.Becausecorefilestendtobelargeandtakeupdiskspace,
besuretoremovethesefileswhenyounolongerneedthem.
gdb:SymbolicDebugger
ThefollowingexamplesdemonstratetheuseoftheGNUgdbdebugger.Othersymbolicdebuggersoffera
differentinterfacebutoperateinasimilarmanner.Tomakefulluseofasymbolicdebuggerwitha
program,youmustcompiletheprogramwiththegoption,whichcausesgcctogenerateadditional
informationthatthedebuggeruses.Thisinformationincludesasymboltablealistofvariablenamesused
intheprogramandtheirassociatedvalues.Withoutthesymboltableinformation,thedebuggercannot
displaythevaluesandtypesofvariables.Ifaprogramiscompiledwithoutthegoption,gdbcannot
identifysourcecodelinesbynumber,asmanygdbcommandsrequire.
tip:Alwaysuseg
Itcanbehelpfulalwaystousethegoptionevenwhenyouarereleasingsoftware.
Includingdebuggingsymbolsmakesabinaryabitbigger.Debuggingsymbolsdonotmake
aprogramrunmoreslowly,buttheydomakeitmucheasiertofindproblemsidentifiedby
users.
tip:Avoidusingoptimizationflagswiththedebugger
LimittheoptimizationflagstoOorO2whenyoucompileaprogramfordebugging.
Becausedebuggingandoptimizinginherentlyhavedifferentgoals,itmaybebesttoavoid
combiningthetwooperations.
ThefollowingexampleusesthegoptionwhencreatingtheexecutablefiletabsfromtheCprogram
tabs.c,discussedatthebeginningofthischapter:
$gcc-gtabs.c-otabs
tip:Optimizationshouldwork
Turningoptimizationoffcompletelycansometimeseliminateerrors.Eliminatingerrorsin
thiswayshouldnotbeseenasapermanentsolution,however.Whenoptimizationisnot
enabled,thecompilermayautomaticallyinitializevariablesandperformcertainother
checksforyou,resultinginmorestablecode.Correctcodeshouldworkcorrectlywhen
compiledwithatleastOandalmostcertainlyO2.TheO3settingoftenincludes
experimentaloptimizationssoitmaynotgeneratecorrectcodeinallcases.
Inputfortabsiscontainedinthefiletesttabs,whichconsistsofasingleline:
$cattesttabs
xyzTABabc
Youcannotspecifytheinputfiletotabswhenyoufirstcallthedebugger.Specifytheinputfileonceyou
havecalledthedebuggerandstartedexecutionwiththeruncommand.
Torunthedebuggeronthesampleexecutable,givethenameoftheexecutablefileonthecommandline
whenyourungdb.Youwillseesomeintroductorystatementsaboutgdb,followedbythegdbprompt
[(gdb)].Atthispointthedebuggerisreadytoacceptcommands.Thelistcommanddisplaysthefirstten
linesofsourcecode.Asubsequentlistcommanddisplaysthenexttenlinesofsourcecode.
$gdbtabs
GNUgdb4.18
...
(gdb)list
4#include<stdio.h>
5#defineTABSIZE8
6
7/*prototypeforfunctionfindstop*/
8intfindstop(int*);
9
10intmain()
11{
12intc;/*characterreadfromstdin*/
13intposn=0;/*columnpositionofcharacter*/
(gdb)list
14intinc;/*columnincrementtotabstop*/
15
16while((c=getchar())!=EOF)
17switch(c)
18{
19case'\t':/*cisatab*/
20inc=findstop(&posn);
21for(;inc>0;inc--)
22putchar('');
23break;
(gdb)
Oneofthemostimportantfeaturesofadebuggerisitsabilitytorunaprograminacontrolled
environment.Youcanstoptheprogramfromrunningwheneveryouwant.Whileitisstopped,youcan
checkthestateofanargumentorvariable.Forexample,youcangivethebreakcommandasourcecode
linenumber,anactualmemoryaddress,orafunctionnameasanargument.Thefollowingcommandtells
gdbtostoptheprocesswheneverthefunctionfindstopiscalled:
(gdb)breakfindstop
Breakpoint1at0x804849f:filetabs.c,line41.
(gdb)
Thedebuggeracknowledgestherequestbydisplayingthebreakpointnumber,thehexadecimalmemory
addressofthebreakpoint,andthecorrespondingsourcecodelinenumber(41).Thedebuggernumbers
breakpointsinascendingorderasyoucreatethem,startingwith1.
Aftersettingabreakpointyoucanissuearuncommandtostartexecutionoftabsunderthecontrolofthe
debugger.Theruncommandsyntaxallowsyoutouseanglebracketstoredirectinputandoutput(justas
theshellsdo).Inthefollowingexample,thetesttabsfileisspecifiedasinput.Whentheprocessstops(at
thebreakpoint),youcanusetheprintcommandtocheckthevalueof*col.Thebacktrace(orbt)
commanddisplaysthefunctionstack.Theexampleshowsthatthecurrentlyactivefunctionhasbeen
assignedthenumber0.Thefunctionthatcalledfindstop(main)hasbeenassignedthenumber1:
(gdb)run<testtabs
Startingprogram:/home/mark/book/10/tabs<testtabs
Breakpoint1,findstop(col=0xbffffc70)attabs.c:41
41retval=(TABSIZE-(*col%TABSIZE));
(gdb)print*col
$1=3
(gdb)backtrace
#0findstop(col=0xbffffc70)attabs.c:41
#10x804843ainmain()attabs.c:20
(gdb)
Youcanexamineanythinginthecurrentscopevariablesandargumentsintheactivefunctionaswellas
globals.Inthenextexample,therequesttoexaminethevalueofthevariableposnatbreakpoint1results
inanerror.Theerrorisgeneratedbecausethevariableposnisdefinedlocallyinthefunctionmain,notin
thefunctionfindstop:
(gdb)printposn
Nosymbol"posn"incurrentcontext.
Theupcommandchangestheactivefunctiontothecallerofthecurrentlyactivefunction.Becausemain
callsthefunctionfindstop,thefunctionmainbecomestheactivefunctionwhentheupcommandisgiven.
(Thedowncommanddoestheinverse.)Theupcommandmaybegivenanintegerargumentspecifyingthe
numberoflevelsinthefunctionstacktobacktrack,withup1havingthesamemeaningasup.(Youcan
usethebacktracecommandtodeterminetheargumenttousewithup.)
(gdb)up
10x804843ainmain()attabs.c:20
20inc=findstop(&posn);
(gdb)printposn
$2=3
(gdb)print*col
Nosymbol"col"incurrentcontext.
(gdb)
Thecont(continue)commandcausestheprocesstocontinuerunningfromwhereitleftoff.Thetesttabs
filecontainsonlyoneline;theprocessfinishesexecutingandtheresultsappearonthescreen.The
debuggerreportstheexitcodeoftheprogram.Acontcommandgivenafteraprogramhasfinished
executingremindsyouthatexecutionoftheprogramiscomplete.Thedebuggingsessionisthenended
withaquitcommand.
(gdb)cont
Continuing.
abcxyz
Programexitednormally.
(gdb)cont
Theprogramisnotbeingrun.
(gdb)quit
$
Thegdbdebuggersupportsmanycommandsthataredesignedtomakedebuggingeasier.Typehelpatthe
(gdb)prompttogetalistofthecommandclassesavailableundergdb:
(gdb)help
Listofclassesofcommands:
aliases--Aliasesofothercommands
breakpoints--Makingprogramstopatcertainpoints
data--Examiningdata
files--Specifyingandexaminingfiles
internals--Maintenancecommands
obscure--Obscurefeatures
running--Runningtheprogram
stack--Examiningthestack
status--Statusinquiries
support--Supportfacilities
tracepoints--Tracingofprogramexecutionwithoutstoppingthe
program
user-defined--User-definedcommands
Type"help"followedbyaclassnameforalistofcommandsinthat
class.
Type"help"followedbycommandnameforfulldocumentation.
Commandnameabbreviationsareallowedifunambiguous.
(gdb)
Asexplainedintheinstructionsfollowingthelist,enteringhelpfollowedbythenameofacommandclass
orcommandnamewilldisplaymoreinformation.Thefollowingliststhecommandsintheclassdata:
(gdb)helpdata
Examiningdata.
Listofcommands:
call--Callafunctionintheprogram
deletedisplay--Cancelsomeexpressionstobedisplayedwhen
programstops
disabledisplay--Disablesomeexpressionstobedisplayedwhen
programstops
disassemble--Disassembleaspecifiedsectionofmemory
display--PrintvalueofexpressionEXPeachtimetheprogramstops
enabledisplay--Enablesomeexpressionstobedisplayedwhen
programstops
inspect--Sameas"print"command
output--Like"print"butdon'tputinvaluehistoryanddon'tprint
newline
print--PrintvalueofexpressionEXP
printf--Printf"printfformatstring"
ptype--PrintdefinitionoftypeTYPE
set--EvaluateexpressionEXPandassignresulttovariableVAR
setvariable--EvaluateexpressionEXPandassignresulttovariable
VAR
undisplay--Cancelsomeexpressionstobedisplayedwhenprogram
stops
whatis--PrintdatatypeofexpressionEXP
x--Examinememory:x/FMTADDRESS
Type"help"followedbycommandnameforfulldocumentation.
Commandnameabbreviationsareallowedifunambiguous.
(gdb)
Thefollowingrequestsinformationonthecommandwhatis,whichtakesavariablenameorother
expressionasanargument:
(gdb)helpwhatis
PrintdatatypeofexpressionEXP.
GraphicalSymbolicDebuggers
Severalgraphicalinterfacestogdbexist.Thexxgdbgraphicalversionofgdbprovidesanumberof
windows,includingaSourceListingwindow,aCommandwindowthatcontainsasetofcommonlyused
commands,andaDisplaywindowforviewingthevaluesofvariables.Theleftmousebuttonselects
commandsfromtheCommandwindow.YoucanclickthedesiredlineintheSourceListingwindowtoset
abreakpoint,andyoucanselectvariablesbyclickingthemintheSourceListingwindow.Selectinga
variableandclickingprintintheCommandwindowwilldisplaythevalueofthevariableintheDisplay
window.Youcanviewlinesofsourcecodebyscrolling(andresizing)theSourceListingwindow.
TheGNUddddebugger(www.gnu.org/software/ddd)alsoprovidesaGUItogdb.Unlikexxgdb,ddd
cangraphicallydisplaycomplexCstructuresandthelinksbetweenthem.Thisdisplaymakesiteasierto
seeerrorsinthesestructures.Otherwise,thedddinterfaceisverysimilartothatofxxgdb.
Unlikexxgdb,ups(ups.sourceforge.net)wasdesignedfromthegrounduptoworkasagraphical
debugger;thegraphicalinterfacewasnotaddedafterthedebuggerwascomplete.Theresultinginterface
issimpleyetpowerful.Forexample,upsautomaticallydisplaysthevalueofavariablewhenyouclickit
andprovidesabuilt-inCinterpreterthatallowsyoutoattachCcodetotheprogramyouaredebugging.
Becausethisattachedcodehasaccesstothevariablesandvaluesintheprogram,youcanuseitto
performsophisticatedchecks,suchasfollowinganddisplayingthelinksinacomplexdatastructure
(page870).
Threads
Athreadisasinglesequentialflowofcontrolwithinaprocess.Threadsarethebasisformultithreaded
programs,whichallowasingleprogramtocontrolconcurrentlyrunningthreads,eachperforminga
differenttask.Multithreadedprogramsgenerallyusereentrantcode(codethatmultiplethreadscanuse
simultaneously)andaremostvaluablewhenrunonmultiple-CPUmachines.UnderLinux,multithreaded
servers,suchasNFS,canprovideacleanerinterfaceandmaybeeasiertowritethanmultipleserver
processes.Whenappliedjudiciously,multithreadingcanalsoserveasalower-overheadreplacementfor
thetraditionalfork-execidiomforspawningprocesses.SeetheFAQattldp.org/FAQ/Threads-FAQ.
tip:Multiplethreadsarenotalwaysbetter
Ifyouwriteamultithreadedprogramwithnocleargoalordivisionofeffortforasingle-
CPUsystem(forexample,aparallel-serverprocess),theresultingprogramwilllikelyrun
moreslowlythananonthreadedprogramonthesamesystem.

SystemCalls
ThreefundamentalresponsibilitiesoftheLinuxkernelaretocontrolprocesses,managethefilesystem,
andoperateperipheraldevices.Asaprogrammeryouhaveaccesstothesekerneloperationsthrough
systemcallsandlibraryfunctions.Thissectiondiscussessystemcallsatagenerallevel;adetailed
treatmentisbeyondthescopeofthisbook.
Asthenameimplies,asystemcallinstructsthesystem(kernel)toperformsomeworkdirectlyonyour
behalf.Therequestisamessagethattellsthekernelwhatworkneedstobedoneandincludesthe
necessaryarguments.Forexample,asystemcalltoopenafileincludesthenameofthefile.Alibrary
routineisindirect;itissuessystemcallsforyou.Theadvantagesofalibraryroutinearethatitmay
insulateyoufromthelow-leveldetailsofkerneloperationsandthatithasbeenwrittencarefullytomake
surethatitperformsefficiently.
Forexample,itisstraightforwardtousethestandardI/Olibraryfunctionfprintf()tosendtextto
standardoutputorstandarderror.Withoutthisfunction,youwouldneedtoissueseveralsystemcallsto
achievethesameresult.Thecallstothelibraryroutinesputchar()andgetchar()inFigure10-1onpage
390ultimatelyusethewrite()andread()systemcallstoperformtheI/Ooperations.
strace:TRacesSystemCalls
Thestraceutilityisadebuggingtoolthatdisplaysatraceofallsystemcallsmadebyaprocessor
program.Becauseyoudonotneedtorecompiletheprogramthatyouwanttotrace,youcanusestrace
onbinariesthatyoudonothavesourcefor.
Systemcallsareeventsthattakeplaceattheinterface(boundary)betweenusercodeandkernelcode.
Examiningthisboundarycanhelpyouisolatebugs,trackdownraceconditions,andperformsanity
checking.TheLinuxkerneldoesnotfullycooperatewithstrace.Seethestracehomepage
(www.liacs.nl/~wichert/strace)forkernelpatchesthatimprovekernelcooperationwithstrace.
ControllingProcesses
Whenyouenteracommandlineatashellprompt,theshellprocesscallstheforksystemcalltocreatea
copyofitself(spawnachild)andthenusesanexecsystemcalltooverlaythatcopyinmemorywitha
differentprogram(thecommandyouaskedittorun).Table10-3listssystemcallsthataffectprocesses.
Table10-3.Systemcalls:processescontrol
Systemcall Function
fork() Createsacopyofaprocess

exec() Overlaysaprograminmemorywithanother
getpid() ReturnsthePIDnumberofthecallingprocess
wait() Causestheparentprocesstowaitforthechildtofinishrunningbeforeit
resumesexecution
exit() Causesaprocesstoexit
nice() Changesthepriorityofaprocess
kill() Sendsasignaltoaprocess
AccessingTheFilesystem
Manyoperationstakeplacewhenaprogramreadsfromorwritestoafile.Theprogramneedstoknow
wherethefileislocated;thefilenamemustbeconvertedtoaninodenumberonthecorrectfilesystem.
Youraccesspermissionsmustbecheckednotonlyforthefileitselfbutalsoforallinterveningdirectories
inthepathtothefile.Thefileisnotstoredinonecontinuouspieceonthedisksoalldiskblocksthat
containpiecesofthefilemustbelocated.Theappropriatekerneldevicedrivermustbecalledtocontrol
theoperationofthedisk.Oncethefilehasbeenfound,theprogrammayneedtofindaparticularlocation
withinthefileratherthanworkingwithitsequentiallyfrombeginningtoend.Table10-4listssomeofthe
mostcommonsystemcallsforfilesystemoperations.
Table10-4.Systemcalls:filesystem
Systemcall Function
stat() Getsstatusinformationfromaninode,suchastheinodenumber,thedevice
onwhichitislocated,ownerandgroupinformation,andthesizeofthefile
lseek() Movestoapositioninthefile
creat() Createsanewfile
open() Opensanexistingfile
read() Readsafile
write() Writesafile
close() Closesafile

unlink() Unlinksafile(deletesanamereferencetotheinode)
chmod() Changesfileaccesspermissions
chown() Changesfileownership
AccesstoperipheraldevicesonaLinuxsystemishandledthroughthefilesysteminterface.Each
peripheraldeviceisrepresentedbyoneormorespecialfiles,usuallylocatedunder/dev.Whenyouread
orwritetooneofthesespecialfiles,thekernelpassesyourrequeststotheappropriatekerneldevice
driver.Asaresultyoucanusethestandardsystemcallsandlibraryroutinestointeractwiththese
devices;youdonotneedtolearnanewsetofspecializedfunctions.Thisabilityisoneofthemost
powerfulfeaturesofaLinuxsystembecauseitallowsuserstousethesamebasicutilitiesonawide
rangeofdevices.
TheavailabilityofstandardsystemcallsandlibraryroutinesisthekeytotheportabilityofLinuxtools.
Forexample,asanapplicationsprogrammer,youcanrelyonthereadandwritesystemcallsworkingthe
samewayondifferentversionsoftheLinuxsystemandondifferenttypesofcomputers.Thesystems
programmerwhowritesadevicedriverorportsthekerneltorunonanewcomputer,however,must
understandthedetailsattheirlowestlevel.
SourceCodeManagement
Whenyouworkonaprojectinvolvingmanyfilesthatevolveoverlongperiodsoftime,itcanbedifficult
tokeeptrackofthedifferentversionsofthefiles,particularlyifseveralpeopleareupdatingthefiles.
Thisproblemfrequentlyoccursinlargesoftwaredevelopmentprojects.Sourcecodeanddocumentation
fileschangefrequentlyasyoufixbugs,enhanceprograms,andreleasenewversionsofthesoftware.The
taskbecomesevenmorecomplexwhenmorethanoneversionofeachfileisactive.Frequentlycustomers
areusingoneversionofafilewhileanewerversionisbeingmodified.Youcaneasilylosetrackofthe
versionsandaccidentallyundochangesorduplicateearlierwork.
Tohelpavoidthesekindsofproblems,LinuxincludesCVS(ConcurrentVersionsSystem;
www.cvshome.org)formanagingandtrackingchangestofiles.AlthoughCVScanbeusedonanyfile,it
ismostoftenusedtomanagesourcecodeandsoftwaredocumentation.CVSisbasedonRCS(GNU's
RevisionControlSystem)andisdesignedtocontroltheconcurrentaccessandmodificationofsource
filesbymultipleusers.
AgraphicalfrontendtoCVSnamedTkCVS(page429)simplifiestheuseofCVS,especiallyifyoudo
notuseitfrequentlyenoughtomemorizeitsmanycommandsandoptions.
CVScontrolswhoisallowedtoupdatefiles.Foreachupdate,CVSrecordswhomadethechangesand
whythechangesweremade.BecauseCVSstoresthemostrecentversionofafileandtheinformation
neededtore-createallpreviousversions,itispossibletoregenerateanyversionofafile.
Asetofversionsforseveralfilesmaybegroupedtogethertoformarelease.Anentirereleasecanbere-
createdfromthechangeinformationstoredwitheachfile.Savingthechangesforafileratherthansaving
acompletecopyofthefilegenerallyconservesalotofdiskspace,wellinexcessofthespacerequiredto
storeeachupdateintheCVSfilesthemselves.
ThissectionprovidesanoverviewofCVSandTkCVS.SeetheCVS-RCS-HOW-TODocumentforLinux
formoreinformation.
CVS:ConcurrentVersionsSystem
CVStreatscollectionsoffilesassingleunits,makingiteasytoworkonlargeprojectsandpermitting
multipleuserstoworkonthesamefile.CVSalsoprovidesvaluableself-documentingfeaturesforits
utilities.
Built-InCVSHelp
CVSusesasingleutility,cvs,forallitsfunctions.Todisplaytheinstructionsforgettinghelp,usethe
helpoption:
$cvs--help
Usage:cvs[cvs-options]command[command-options-and-arguments]
wherecvs-optionsare-q,-n,etc.
(specify--help-optionsforalistofoptions)
wherecommandisadd,admin,etc.
(specify--help-commandsforalistofcommands
or--help-synonymsforalistofcommandsynonyms)
wherecommand-options-and-argumentsdependonthespecificcommand
(specify-Hfollowedbyacommandnameforcommand-specifichelp)
Specify--helptoreceivethismessage
TheConcurrentVersionsSystem(CVS)isatoolforversioncontrol.
ForCVSupdatesandadditionalinformation,see
theCVShomepageathttp://www.cvshome.org/orPascalMolli's
CVS
siteathttp://www.loria.fr/~molli/cvs-index.html
Togethelpwithacvscommand,usethehelpoptionfollowedbythenameoftheutility.Thefollowing
exampleshowshelpforthelogcommand:
$cvs--helplog
Usage:cvslog[-lRhtNb][-r[revisions]][-ddates][-sstates]
[-w[logins]][files...]
-lLocaldirectoryonly,norecursion.
-ROnlyprintnameofRCSfile.
-hOnlyprintheader.
-tOnlyprintheaderanddescriptivetext.
-NDonotlisttags.
-bOnlylistrevisionsonthedefaultbranch.
-r[revisions]Specifyrevision(s)stolist.
rev1:rev2Betweenrev1andrev2,includingrev1and
rev2.
rev1::rev2Betweenrev1andrev2,excludingrev1and
rev2.
rev:revandfollowingrevisionsonthesame
branch.
rev::Afterrevonthesamebranch.
:revrevandpreviousrevisionsonthesamebranch.
::revBeforerevonthesamebranch.
revJustrev.
branchAllrevisionsonthebranch.
branch.Thelastrevisiononthebranch.
-ddatesSpecifydates(D1<D2forrange,Dforlatest
before).
-sstatesOnlylistrevisionswithspecifiedstates.
-w[logins]Onlylistrevisionscheckedinbyspecified
logins.
(Specifythe--helpglobaloptionforalistofotherhelpoptions)
Optionsforindividualcvscommands(commandoptions)gototherightoftheindividualcommand
names.Optionstothecvsutilityitself,suchasthehelpoptiontothelogcommand,gototheleftofall
individualcommandnames(thatis,theyfollowthewordcvsonthecommandline).Thetwotypesof
optionssometimesusethesameletteryetmayhaveanentirelydifferentmeaning.
HowCVSStoresRevisionFiles
WithCVS,revisionfilesarekeptinacommonareacalledasourcerepository.Thisareaisidentifiedby
thevalueoftheenvironmentvariableCVSROOT,whichholdstheabsolutepathnameoftherepository.
ThesystemadministratorcantellyouwhatvalueofCVSROOTtouse,oryoucancreateyourown
privaterepositoryandhaveCVSROOTpointtoit.
Thesourcerepositoryisorganizedasahierarchicalcollectionoffilesanddirectories.CVSdoesnot
limityoutocheckingoutonefileatatime;youcancheckoutanentiresubdirectorycontainingmany
filestypicallyallthefilesforaparticularproject.AsubdirectoryofCVSROOTthatcanbecheckedout
asasingleunitiscalledamodule.Severalpeoplecancheckoutandsimultaneouslymodifythefiles
withinasinglemodule.
CVSuserstypicallystoreallthemodulestheyarecurrentlyworkingoninaspecialdirectory.Ifyouwant
tofollowthispractice,youmustusecdtomakethatspecialdirectorytheworkingdirectorybeforeyou
checkoutamodule.Whenyoucheckoutamodule,CVSreplicatesthemodule'streestructureinthe
workingdirectory.MultipledeveloperscancheckoutandeditCVSfilessimultaneouslybecausethe
originalsareretainedinthesourcerepository;thefilesintherepositoryundergorelativelyinfrequent
modificationinacontrolledmanner.
BasicCvsCommands
Althoughmanycvscommandsareavailable,ahandfulofcommandsallowsasoftwaredevelopertouse
CVSandtocontributechangestoamodule.Adiscussionofsomeusefulcommandsfollows.All
examplesassumethattheappropriatemoduleshavebeeninstalledintheCVSsourcerepository."Adding
aModuletotheRepository"(page426)explainshowtoinstallamodule.
Ofthecommandsdiscussedinthissection,cvscommitistheonlyonethatchangesthesourcerepository.
Theothercommandsaffectonlythefilesintheworkingdirectory.
Tosimplifyexamplesinthefollowingsections,thepathnameoftheworkingdirectoryisgivenbythe
variableCVSWORK;allmodulescanbeassumedtobesubdirectoriesofCVSWORK.Althoughthis
variablehasnospecialmeaningtoCVS,youmayfindithelpfultodefinesuchavariableforyourown
work.
CheckingOutFilesfromtheSourceRepository
TocheckoutamodulefromtheCVSsourcerepository,usethecvscheckoutcommand.Thefollowing
examplechecksouttheProject2module,whichconsistsoffoursourcefiles.Firstusecdtochange
workingdirectoriestothedirectoryyouwantthemodulecopiedinto(CVSWORKinthiscase).The
cvsutilityalwayscopiesintotheworkingdirectory.
$cd$CVSWORK
$ls
Project1
$cvscheckoutProject2
cvscheckout:UpdatingProject2
UProject2/adata.h
UProject2/compute.c
UProject2/randomfile.h
UProject2/shuffle.c
$ls
Project1Project2
$lsProject2
CVSadata.hcompute.crandomfile.hshuffle.c
Thenameofthemodule,Project2,isgivenasanargumenttocvscheckout.BecausetheProject2
directorydoesnotalreadyexist,cvscreatesitintheworkingdirectoryandplacescopiesofallsource
filesfortheProject2moduleintoit:Thenameofthemoduleandthenameofthedirectoryholdingthe
modulearethesame.Thecheckoutcommandpreservesthetreestructureofthecvsmodule,creating
subdirectoriesasneeded.
Thesecondlscommandaftercheckoutreveals,inadditiontothefoursourcefilesforProject2,a
directorynamedCVS.TheCVSsystemusesthisdirectoryforadministrativepurposes;youdonot
normallyaccessit.
Onceyouhaveyourowncopiesofthesourcefiles,youcaneditthemasyouseefit.Youcanchangefiles
withinthemoduleevenifotherdevelopersaremodifyingthesamefilesatthesametime.
MakingYourChangesAvailabletoOthers
Tocheckinyourchangessothatothershaveaccesstothem,youneedtorunthecvscommitcommand.
Whenyougivethiscommand,cvspromptsyoutoprovideabrieflogmessagedescribingthechanges,
unlessyouusethemoption.Withthisoption,cvsusesthestringfollowingtheoptionasthelogmessage.
Thefileorfilesthatyouwanttocommitfollowtheoptionallogmessageonthecommandline:
$cvscommit-m"functionshuffleinserted"compute.c
cvscommit:Up-to-datecheckfailedfor'compute.c'
cvs[commitaborted]:correctaboveerrorsfirst!
Herethecvsutilityreportsanerrorbecausetheversionofcompute.cthatyoumodifiedisnotup-to-
date.Anewerversionofcompute.chasbeencommittedbysomeoneelsesinceyoulastcheckeditoutof
thesourcerepository.Afterinformingyouoftheproblem,cvsexitswithoutstoringyourchangesinthe
sourcerepository.
Tomakeyourversionofcompute.ccurrent,youneedtoruntheupdatecommand.Asubsequent
commitwillthensucceed,andyourchangeswillapplytothelatestrevisioninthesourcerepository.
UpdatingYourCopieswithChangesbyOthers
Astheprecedingexampleshows,CVSdoesnotnotifyyouwhenanotherdeveloperchecksinanew
revisionofafileafteryouhavecheckedoutyourworkingcopy.Youlearnthisfactonlywhenyouattempt
tocommityourchangestothesourcerepository.Toincorporateup-to-daterevisionsofaCVSsource
file,usethecvsupdatecommand:
$cvsupdatecompute.c
RCSfile:/usr/local/src/master/Project2/compute.c,v
retrievingrevision1.9
retrievingrevision1.10
Mergingdifferencesbetween1.9and1.10intocompute.c
Mcompute.c
Thechangesmadetotheworkingcopyofcompute.cremainintactbecausetheupdatecommandmerges
thelatestrevisioninthesourcerepositorywiththeversionspecifiedontheupdatecommandline.The
resultofthemergeisnotalwaysperfect,however.Thecvsupdatecommandinformsyouifitdetects
overlappingchanges.
AddingNewFilestotheRepository
Youcanusethecvsaddcommandtoschedulenewfilestobeaddedtothesourcerepositoryaspartofthe
moduleyouareworkingon.Onceyouhavemovedtothedirectorycontainingthefiles,givethecvsadd
command,listingthefilesyouwanttoaddasarguments:
$cd$CVSWORK/Project2
$ls
CVScompute.cshuffle.ctabout2.c
adata.hrandomfile.htabout1.c
$cvsaddtabout[1-2].c
cvsadd:schedulingfile'tabout1.c'foraddition
cvsadd:schedulingfile'tabout2.c'foraddition
cvsadd:use'cvscommit'toaddthesefilespermanently
Theaddcommandmarksthefilestabout1.candtabout2.cforentryintotherepository.Thesefileswill
notbeavailableforothersuntilyougiveacommitcommand.Thisstagingallowsyoutoprepareseveral
filesbeforeothersincorporatethechangesintotheirworkingcopieswiththecvsupdatecommand.
RemovingFilesfromtheRepository
Thecvsremovecommandrecordsthefactthatyouwishtoremoveafilefromthesourcerepository.Like
theaddcommand,itdoesnotaffectthesourcerepository.Todeleteafilefromtherepository,youmust
firstdeleteyourworkingcopyofthefile,asthefollowingexampleshows:
$cvsremoveshuffle.c
cvsremove:file'shuffle.c'stillinworkingdirectory
cvsremove:1fileexists;use'rm'toremoveitfirst
$rmshuffle.c
$cvsremoveshuffle.c
cvsremove:scheduling'shuffle.c'forremoval
cvsremove:use'cvscommit'toremovethisfilepermanently
Afterusingrmtodeletetheworkingcopyofshuffle.c,invokeacvsremovecommand.Again,youmust
givethecommitcommandbeforethefileisactuallyremovedfromthesourcerepository.
OtherCVSCommands
Althoughthecommandsgivenearlieraresufficientformostworkonamodule,youmayfindsomeother
commandstobeusefulaswell.
TaggingaRelease
Youcanapplyacommonlabel,ortag,tothefilesinamoduleastheycurrentlyexist.Onceyouhave
taggedfilesofamodule,youcanre-createtheminexactlythesameformeveniftheyhavebeenmodified,
added,ordeletedsincethattime.Thisabilityenablesyoutofreezeareleaseyetallowsdevelopmentto
continueonthenextrelease:
$cvsrtagRelease_1Project1
cvsrtag:TaggingProject1
HeretheProject1modulehasbeentaggedwiththelabelRelease_1.Youcanusethistagwiththecvs
exportcommandtoextractthefilesastheywerefrozenatthistime.
ExtractingaRelease
Thecvsexportcommandletsyouextractfilesastheywerefrozenandtagged:
$cvsexport-rRelease_1-dR1Project1
cvsexport:UpdatingR1
UR1/scm.txt
ThiscommandworkslikethecvscheckoutcommandbutdoesnotcreatetheCVSsupportfiles.Youmust
giveeithertheroptiontoidentifytherelease(asshownabove)oradatewiththeDoption.ThedR1
optioninstructscvstoplacethefilesforthemoduleintothedirectoryR1insteadofusingthemodule
nameasthedirectory.
RemovingWorkingFiles
Whenyouarefinishedmakingchangestothefilesyouhavecheckedoutoftherepository,youmaydecide
toremoveyourcopyofthemodulefromyourworkingdirectory.Onesimplemethodistomoveintothe
workingdirectoryandrecursivelyremovethemodule.Forexample,ifyouwanttoremoveyourworking
copyofProject2,youcouldusethefollowingcommands:
$cd$CVSWORK
$rm-rfProject2
Therepositorywillnotbeaffectedbyremovingthesefiles.However,ifyouhadmadechangestothefiles
buthadnotyetcommittedthosechanges,theywouldbelostifyouusedthisapproach.Thecvsrelease
commandishelpfulinthissituation:
$cd$CVSWORK
$cvsrelease-dProject2
Thereleasecommandalsoremovestheworkingfilesbutfirstcheckseachonetoseewhetherithasbeen
markedforadditionintotherepositorybuthasnotyetbeencommitted.Ifthatisthecase,therelease
commandwarnsyouandasksyoutoverifyyourintentiontodeletethefile.Youcanfixtheproblematthis
pointifyoulikeandredothereleasecommand.Thereleasecommandalsowarnsyouiftherepository
holdsanewerversionofthefilethantheoneinyourworkingdirectory.Thusyouhavetheopportunityto
updateandcommityourfilebeforedeletingit.(Withoutthedoption,yourworkingfileswillnotbe
deleted,butthesamesequenceofwarningmessageswillbegiven.)
AddingaModuletotheRepository
ThediscussionofCVStothispointassumesthatamoduleisalreadypresentintheCVSsource
repository.Ifyouwanttoinstalladirectoryhierarchyasanewmoduleintherepositoryorupdatean
existingmodulewithanewreleasethatwasdevelopedelsewhere,gotothedirectorythatholdsthefiles
fortheprojectandrunthecvsimportcommand.ThefollowingexampleinstallsthefilesforProject1in
thesourcerepository:
$cvsimport-m"Myfirstproject"Project1ventagreltag
Themoptionallowsyoutoenterabriefdescriptionofthemoduleonthecommandline.Followingthe
descriptionisthedirectoryorthepathnameofthedirectoryunderCVSROOTthatyouwanttoholdthe
module.Thelasttwofieldsaresymbolicnamesforthevendorbranchandtherelease.Althoughtheyare
notsignificanthere,theycanbeusefulwhenreleasesofsoftwarearesuppliedbyoutsidesources.
YoucannowusethecvscheckoutcommandtocheckouttheProject1module:
$cvscheckoutProject1
CVSAdministration
BeforeyouinstallaCVSrepository,thinkabouthowyouwouldliketoadministerit.Manyinstallations
haveasinglerepositorywhereseparateprojectsarekeptasseparatemodules.Youmaychoosetohave
morethanonerepository.TheCVSsystemsupportsasinglerepositorythatissharedacrossseveral
computersystemsusingNFS.
Insidearepositoryisamodule,namedCVSROOTthatcontainsadministrativefiles(hereCVSROOTis
thenameofamoduleandisdifferentfromtheCVSROOTdirectory).Althoughthefilesinthismodule
arenotrequiredtouseCVS,theycansimplifyaccesstotherepository.
DonotchangeanyfilesintheCVSROOTmodulebyeditingthemdirectly.Instead,checkoutthefileyou
wanttochange,editthechecked-outcopy,andthencheckitbackin,justasyouwouldwithfilesinany
othermoduleintherepository.Forexample,tocheckoutthemodulesfilefromtheCVSROOTmodule,
usethecommand
$cvscheckoutCVSROOT/modules
ThiscommandcreatesthedirectoryCVSROOTinyourworkingdirectoryandplacesachecked-out
copyofmodulesinthatdirectory.Aftercheckingitout,youcaneditthemodulesfileintheCVSROOT
directory:
$cdCVSROOT
$vimmodules
Afteryoueditthemodulesfile,checkitbackintotherepository:
$cd..
$cvscheckinCVSROOT/modules
OfalltheadministrativefilesintheCVSROOTmodule,themodulesfileisthemostimportant.Youcan
usethisfiletoattachsymbolicnamestomodulesintherepository,allowaccesstosubdirectoriesofa
moduleasiftheywerethemselvesmodules,andspecifyactionstotakewhencheckingspecificfilesinor
out.
Mostrepositoriesstartwithamodulesfilethatallowsyoutocheckoutthemodulesfilewiththe
followingcommand,insteadoftheoneshownearlier:
$cvscheckoutmodules
WiththeprecedingcommandCVScreatesasubdirectorynamedmoduleswithintheworkingdirectory,
insteadofonenamedCVSROOT.Themodulesfileisthencheckedoutintothisdirectory.
Thefollowingisanexampleofamodulesfile(thelinesthatstartwith#arecommentlinesand,along
withblanklines,areignoredbyCVS):
#TheCVSmodulesfile
#
#Threedifferentlineformatsarevalid:
#key-aaliases...
#key[options]directory
#key[options]directoryfiles...
#
#Where"options"arecomposedof:
#-iprogRun"prog"on"cvscommit"fromtop-levelofmodule.
#-oprogRun"prog"on"cvscheckout"ofmodule.
#-tprogRun"prog"on"cvsrtag"ofmodule.
#-uprogRun"prog"on"cvsupdate"ofmodule.
#-ddirPlacemoduleindirectory"dir"insteadofmodule
name.
#-lTop-leveldirectoryonly--donotrecurse.
#
#And"directory"isapathtoadirectoryrelativeto$CVSROOT.
#
#The"-a"optionspecifiesanalias.Analiasisinterpretedasif
#everythingontherightofthe"-a"hadbeentypedonthecommand
line.
#
#
#Youcanencodeamodulewithinamodulebyusingthespecial'&'
#charactertointerposeanothermoduleintothecurrentmodule.
This
#canbeusefulforcreatingamodulethatconsistsofmany
directories
#spreadoutovertheentiresourcerepository.
#Convenientaliases
world-a.
#CVSROOTsupport;runmkmoduleswheneveranythingchanges.
CVSROOT-imkmodulesCVSROOT
modules-imkmodulesCVSROOTmodules
loginfo-imkmodulesCVSROOTloginfo
commitinfo-imkmodulesCVSROOTcommitinfo
rcsinfo-imkmodulesCVSROOTrcsinfo
editinfo-imkmodulesCVSROOTeditinfo
#Addothermoduleshere...
testgentestgen
testdata1testdata1
testdata2testdata2
testdata3testdata3
testdata4testdata4
testcodetestgen/_code
cvscvs
Thelinesafterthecommentandblanklinesdefinesymbolicnamesformanymodules.Forexample,the
followinglinedefinesworldtobeanaliasfortherootoftheCVSrepository:
world-a.
YoucanusesuchnamesinCVScommandsasthenamesofmodules.Forexample,thefollowing
commandchecksouttheentirerepository(probablynotagoodidea):
$cvscheckoutworld
Inthesamplemodulesfile,theadministrativefileshavebeengivendefinitionsthatattachbothasymbolic
nametothefileandanaction(imkmodules)totakewheneachfileischeckedintotherepository.Thei
mkmodulesactioncausesCVStorunthemkmodulesprogramwhenthefileischeckedin.Thisprogram
ensuresthatacopyofthechecked-infileexistsinalocationwhereCVScanlocateit.
FollowingtheactionisthenameofthesubdirectoryinCVSROOTwhereanyfilesassociatedwiththe
symbolicnamearelocated.Anyremainingargumentsonthelinearethenamesofspecificfileswithinthat
directory.
ThefollowinglineidentifiesCVSROOTasthenameforthemoduleinthedirectory
$CVSROOT/CVSROOTthatis,foralltheadministrativefilesforCVS:
CVSROOT-imkmodulesCVSROOT
SimilarlythefollowinglineassociatesthemodulesmodulewiththemodulesfilewithintheCVSROOT
directory:
modules-imkmodulesCVSROOTmodules
Theprecedinglineallowsthefollowingcommandtofindandcheckoutthemodulesfile:
$cvscheckoutmodules
Thelastsetoflinesinthesamplemodulesfileassociatessymbolicmodulenameswithdirectoriesand
filesintherepository.
UsingTkCVS
ThecvsutilityisusefulenoughthatanXWindowSysteminterface,TkCVS
(www.twobarleycorns.net/tkcvs.html),hasbeenwrittenforitusingtheTkextensiontotheTcl
programminglanguage(tcl.sourceforge.net).Itprovidesaconvenientpoint-and-clickinterfacetoCVS
(Figure10-5).AfteryouhavedownloadedandinstalledTkCVS,startitbyusingcdtochangetothe
directoryyouwanttoworkinandenteringthefollowingcommand:
$tkcvs&
Figure10-5.TheTkCVSutility

Alloperationsareavailablethroughthepull-downmenusatthetopofthewindow.Alongthebottomare
buttonsforaccessingthemostcommonactions.Adescriptionoftheactionboundtoabuttonappears
whenyoupositionthemousepointerontopofabutton.
Inthemiddleofthewindowisabrowselist.Moveintoasubdirectorybydouble-clickingtheleftmouse
buttonwhilethemousepointerisonthedirectorynameinthelist.Editafilebydouble-clickingthe
filename.Toselectmorethanonefile,holddowntheleftmousebuttonanddragthemousepointeracross
severalnames.Clickingtherightmousebuttonwillmarkallselectedfiles.Someoftheoperations(such
asviewingtherevisionlogmessages)willworkonallmarkedfiles.
TheHelppull-downmenuintheupper-rightcornerisanexcellentwaytolearnhowTkCVSworks.For
example,whenyouselecttheHelpmenuitemCVSmodulesfile...,anexplanationofthelinesthatyou
canaddtotheCVSmodulesfiletosupportTkCVSbetterappearsinawindow.Ifyouchoosenottoadd
theselinestothemodulesfile,someTkCVScommands,suchasbrowsingtherepository,maynotdisplay
allavailablemodules.
ChapterSummary
TheoperatingsysteminterfacetoCprogramsandavarietyofsoftwaredevelopmenttoolsmaketheLinux
systemwellsuitedtoprogramminginC.TheClibrariesprovidegeneral-purposeCfunctionsthatmake
operatingsystemservicesandotherfunctionalityavailabletoCprogrammers.ThestandardClibrarylibc
isalwaysaccessibletoCprograms,andyoucanspecifyotherlibrariesbyusingtheloptiontothegcc
compiler.
YoucanwriteaCprogramusingatexteditor,suchasvimoremacs.Cprogramsalwayshavea
functionnamedmainandoftenincludeseveralotherfunctions.Preprocessordirectivesdefinesymbolic
constantsandmacrosandinstructthepreprocessortoincludeheaderfiles.
gcc
Whenyouusegcc,itcallstheCpreprocessorfollowedbytheCcompilerandtheassembler.The
compilercreatesassemblylanguagecode,whichtheassemblerusestocreateobjectmodules.Thelinker
combinestheseobjectmodulesintoanexecutablefile.YoucanusetheWalloptiontogcctodetectrisky
constructsonesthatarelegalbutsuggestthepossibilityoflaterproblems.Otheroptionstogcccanhelp
locateareasofyourcodethatmightnotbeportable.
gdb
AlthoughusingprintfstatementsandtheWalloptioncanhelpintrackingprogrambugs,itisagood
practicetocompileCprogramsroutinelywiththegoption.Thisoptioncausesinformationthatcanbe
interpretedbygdb,asymbolicdebugger,tobegeneratedaspartoftheexecutablefile.Whenyouruna
programunderthecontrolofgdb,youcanspecifypointswhereyouwantgdbtopausetheprogram,
inquireaboutthevaluesofvariables,displaytheprogramstack,anduseawiderangeofcommandsto
learnaboutmanyotheraspectsoftheprogram'sbehavior.
make
ThemakeutilityusesafilenamedMakefile(ormakefile)thatdocumentstherelationshipsamongfiles.
Itdetermineswhichmodulesofaprogramareout-of-dateandcompilesfilestokeepallmodulesup-to-
date.Thedependencyline,whichspecifiestheexactdependencyrelationshipbetweentargetand
prerequisitefiles,isthekeytotheoperationofamakefile.Followingthedependencylineare
constructioncommandsthatcanbringthetargetup-to-date.Implieddependencies,construction
commands,andthemakemacrofacilityareavailabletosimplifythewritingofcomplexmakefiles.
TheLinuxsystemincludesutilitiesthatassistinkeepingtrackofgroupsoffilesthatundergomultiple
revisions,oftenatthehandsofmultipledevelopers.Thesesourcecodemanagementsystemsinclude
CVS,theConcurrentVersionsSystem.CVSisbuiltontopofRCSbutprovidesamuchmoreextensiveset
ofoperationsformanagingdirectoriesoffilesthatmaybeaccessedandmodifiedbymanyusers.Itisa
goodchoiceforlarge-scaleprojectsandformaintainingsoftwarereleasesthataresenttoandfromother
sites.
Exercises
1. WhatfunctiondoeseveryCprogramhave?Whyshouldyousplitlargeprogramsintoseveralfunctions?
2. Whatcommandcouldyouusetocompileprog.candfunc.cintoanexecutablenamedcprog?
3.
ShowtwowaystoinstructtheCpreprocessortoincludetheheaderfile/usr/include/math.hinyourCprogram.Assumingthatthe
declar.hheaderfileislocatedinthesubdirectorynamedheadersofyourhomedirectory,describetwowaystoinstructtheC
preprocessortoincludethisheaderfileinyourCprogram.
4. Howarethenamesofsystemlibrariesabbreviatedonthegcccommandline?Wheredoesgccsearchforlibrariesnamedinthis
manner?Describehowtospecifyyourownlibraryonthegcccommandline.
5.
Writeamakefilethatreflectsthefollowingrelationships:
1. TheCsourcefilestransactions.candreports.carecompiledtoproduceanexecutableaccts.
2. Bothtransactions.candreports.cincludeaheaderfileaccts.h.
3. Theheaderfileaccts.hiscomposedoftwootherheaderfiles:trans.handreps.h.
6. Ifyouretrieveversion4.1ofthefileanswerforeditingandthenattempttoretrievethesameversionagain,whatwillCVSdo?Whyis
CVSsetupthisway?
AdvancedExercises
7. Modifythebadtabs.cprogram(page409)sothatitexitscleanly(withaspecificreturnvalue).Compiletheprogramandrunitusing
gdboranotherdebugger.Whatvaluesdoesthedebuggerreportwhentheprogramfinishesexecuting?
8.
Forthemakefile
$catMakefile
leads:menu.ousers.oresellers.oprospects.o
gcc-oleadsmenu.ousers.oresellers.oprospects.o
menu.o:menu.hdialog.hinquiry.h
users.o:menu.hdialog.h
prospects.o:dialog.h
identify:
1. Targets.
2. Constructioncommands.
3. Prerequisites.
9.
RefertoMakefileinexercise8toanswerthefollowingquestions:
1. Ifthetargetleadsisup-to-dateandyouthenchangeusers.c,whathappenswhenyourunmakeagain?Bespecific.
2. Rewritethemakefiletoincludethefollowingmacros:
OBJECTS=menu.ousers.oresellers.oprospects.o
HFILES=menu.hdialog.h
10.
Reviewthemakeinfopagetoanswerthefollowingquestions:
1. Whatdoesthetoptiondo?
2. IfyouhavefilesnamedmakefileandMakefileintheworkingdirectory,howcanyouinstructmaketouseMakefile?
3. Givetwowaystodefineavariablesothatyoucanuseitinsideamakefile.
Refertothemakefileforcomputeonpage402.
11.
1. Supposethatafileintheworkingdirectoryisnamedclean.Whatistheeffectofgivingthefollowingcommand?Explain.
$makeclean
2. Thediscussiononpage401statesthatthefollowingcommandisnotnormallyseeninmakefiles:
catnum.htable.h>form.h
Discusstheeffectofremovingthisconstructioncommandfromthemakefilewhileretainingthedependencyline.
3. Theprecedingconstructioncommandworksonlybecausethefileform.hismadeupofnum.handtable.h.Moreoften
#includedirectivesinthetargetdefinethedependencies.Suggestamoregeneraltechniquethatupdatesform.hwhenever
num.hortable.hhasamorerecentmodificationdate.
Chapter11.ProgrammingTheBourneAgainShell
INTHISCHAPTER
ControlStructures436
FileDescriptors470
ParametersandVariables474
ArrayVariables474
LocalityofVariables475
SpecialParameters478
PositionalParameters480
BuiltinCommands487
Expressions501
ShellPrograms510
ARecursiveShellScript510
ThequizShellScript513
Chapter5introducedtheshellsandChapter8wentintodetailabouttheBourneAgainShell.Thischapter
introducesadditionalBourneAgainShellcommands,builtins,andconceptsthatcarryshellprogramming
toapointwhereitcanbeuseful.Thefirstpartofthischaptercoversprogrammingcontrolstructures,
whicharealsoknownascontrolflowconstructs.Thesestructuresallowyoutowritescriptsthatcanloop
overcommandlinearguments,makedecisionsbasedonthevalueofavariable,setupmenus,andmore.
TheBourneAgainShellusesthesameconstructsfoundinsuchhigh-levelprogramminglanguagesasC.
Thenextpartofthischapterdiscussesparametersandvariables,goingintodetailaboutarrayvariables,
localversusglobalvariables,specialparameters,andpositionalparameters.Theexplorationofbuiltin
commandscoverstype,whichdisplaysinformationaboutacommand,andread,whichallowsyouto
acceptuserinputinashellscript.Thesectionontheexecbuiltindemonstrateshowexecprovidesan
efficientwaytoexecuteacommandbyreplacingaprocessandexplainshowyoucanuseittoredirect
inputandoutputfromwithinascript.ThenextsectioncoverstheTRapbuiltin,whichprovidesawayto
detectandrespondtooperatingsystemsignals(suchasthatwhichisgeneratedwhenyoupress
CONTROL-C).Thediscussionofbuiltinsconcludeswithadiscussionofkill,whichcanaborta
process,andgetopts,whichmakesiteasytoparseoptionsforashellscript.(Table11-6onpage500
listssomeofthemorecommonlyusedbuiltins.)

Table11-6.bashbuiltins
Builtin Function
: Returns0ortrue(thenullbuiltin;page495)
.(dot) Executesashellscriptaspartofthecurrentprocess
(page259)
bg Putsasuspendedjobinthebackground(page273)
break Exitsfromaloopingcontrolstructure(page459)
cd Changestoanotherworkingdirectory(page82)
continue Startswiththenextiterationofaloopingcontrol
structure(page459)
echo Displaysitsarguments(page53)
eval Scansandevaluatesthecommandline(page318)
exec Executesashellscriptorprograminplaceofthecurrent
process(page491)
exit Exitsfromthecurrentshell(usuallythesameas
CONTROL-Dfromaninteractiveshell;page480)
export Placesthevalueofavariableinthecallingenvironment
(makesitglobal;page475)
fg Bringsajobfromthebackgroundintotheforeground
(page272)
getopts Parsesargumentstoashellscript(page497)
jobs Displayslistofbackgroundjobs(page271)
kill Sendsasignaltoaprocessorjob(page693)
pwd Displaysthenameoftheworkingdirectory(page81)
read Readsalinefromstandardinput(page487)
readonly Declaresavariabletobereadonly(page281)
set Setsshellflagsorcommandlineargumentvariables;with
noargument,listsallvariables(pages319,356,and484)

shift Promoteseachcommandlineargument(page483)
test Comparesarguments(pages437and794)
times Displaystotaltimesforthecurrentshellanditschildren
trap Trapsasignal(page493)
type Displayshoweachargumentwouldbeinterpretedasa
command(page487)
umask Returnsthevalueofthefile-creationmask(page810)
unset Removesavariableorfunction(page281)
wait Waitsforabackgroundprocesstoterminate(page381)
Nextthechapterexaminesarithmeticandlogicalexpressionsandtheoperatorsthatworkwiththem.The
finalsectionwalksthroughthedesignandimplementationoftwomajorshellscripts.
Thischaptercontainsmanyexamplesofshellprograms.Althoughtheyillustratecertainconcepts,most
useinformationfromearlierexamplesaswell.Thisoverlapnotonlyreinforcesyouroverallknowledge
ofshellprogrammingbutalsodemonstrateshowyoucancombinecommandstosolvecomplextasks.
Running,modifying,andexperimentingwiththeexamplesinthisbookisagoodwaytobecome
comfortablewiththeunderlyingconcepts.
tip:Donotnameashellscripttest
Youcanunwittinglycreateaproblemifyougiveashellscriptthenametestbecausea
Linuxutilityhasthesamename.DependingonhowthePATHvariableissetupandhow
youcalltheprogram,youmayrunyourscriptortheutility,leadingtoconfusingresults.
Thischapterillustratesconceptswithsimpleexamples,whicharefollowedbymorecomplexonesin
sectionsmarked"Optional".Themorecomplexscriptsillustratetraditionalshellprogrammingpractices
andintroducesomeLinuxutilitiesoftenusedinscripts.Youcanskipthesesectionswithoutlossof
continuitythefirsttimeyoureadthechapter.Returntothemlaterwhenyoufeelcomfortablewiththe
basicconcepts.
ControlStructures
Thecontrolflowcommandsaltertheorderofexecutionofcommandswithinashellscript.TheTCShell
usesadifferentsyntaxforthesecommands(page368)thantheBourneAgainShelldoes.Control
structuresincludetheif...then,for...in,while,until,andcasestatements.Inaddition,thebreakand
continuestatementsworkinconjunctionwiththecontrolstructurestoaltertheorderofexecutionof
commandswithinascript.
if...then
Theif...thencontrolstructurehasthefollowingsyntax:
iftest-command
then
commands
fi
Theboldwordsinthesyntaxdescriptionaretheitemsyousupplytocausethestructuretohavethe
desiredeffect.Thenonboldwordsarethekeywordstheshellusestoidentifythecontrolstructure.
testbuiltin
Figure11-1showsthattheifstatementteststhestatusreturnedbythetest-commandandtransferscontrol
basedonthisstatus.Theendoftheifstructureismarkedbyafistatement,(ifspelledbackward).The
followingscriptpromptsfortwowords,readsthem,andthenusesanifstructuretoexecutecommands
basedontheresultreturnedbythetestbuiltin(tcshusesthetestutility)whenitcomparesthetwo
words.(Seepage794forinformationonthetestutility,whichissimilartothetestbuiltin.)The
testbuiltinreturnsastatusoftrueifthetwowordsarethesameandfalseiftheyarenot.Double
quotationmarksaround$word1and$word2makesurethattestworksproperlyifyouenterastring
thatcontainsaSPACEorotherspecialcharacter:
$catif1
echo-n"word1:"
readword1
echo-n"word2:"

readword2
iftest"$word1"="$word2"
then
echo"Match"
fi
echo"Endofprogram."
$if1
word1:peach
word2:peach
Match
Endofprogram.
Figure11-1.Anif...thenflowchart
Intheprecedingexamplethetest-commandistest"$word1"="$word2".Thetestbuiltinreturnsa
truestatusifitsfirstandthirdargumentshavetherelationshipspecifiedbyitssecondargument.Ifthis
commandreturnsatruestatus(=0),theshellexecutesthecommandsbetweenthethenandfistatements.
Ifthecommandreturnsafalsestatus(not=0),theshellpassescontroltothestatementfollowingfi
withoutexecutingthestatementsbetweenthenandfi.TheeffectofthisifstatementistodisplayMatchif
thetwowordsarethesame.ThescriptalwaysdisplaysEndofprogram.
Builtins
IntheBourneAgainShell,testisabuiltinpartoftheshell.Itisalsoastand-aloneutilitykeptin
/usr/bin/test.ThischapterdiscussesanddemonstratesmanyBourneAgainShellbuiltins.Eachbash
builtinmayormaynotbeabuiltinintcsh.Youusuallyusethebuiltinversionifitisavailableandthe
utilityifitisnot.Eachversionofacommandmayvaryslightlyfromoneshelltothenextandfromthe
utilitytoanyoftheshellbuiltins.Seepage487formoreinformationonshellbuiltins.
Checkingarguments
Thenextprogramusesanifstructureatthebeginningofascripttocheckthatyouhavesuppliedatleast
oneargumentonthecommandline.Theeqtestoperatorcomparestwointegers,wherethe$#special
parameter(page480)takesonthevalueofthenumberofcommandlinearguments.Thisstructuredisplays
amessageandexitsfromthescriptwithanexitstatusof1ifyoudonotsupplyatleastoneargument:
$catchkargs
iftest$#-eq0
then
echo"Youmustsupplyatleastoneargument."
exit1
fi
echo"Programrunning."
$chkargs
Youmustsupplyatleastoneargument.
$chkargsabc
Programrunning.
Atestliketheoneshowninchkargsisakeycomponentofanyscriptthatrequiresarguments.Toprevent
theuserfromreceivingmeaninglessorconfusinginformationfromthescript,thescriptneedstocheck
whethertheuserhassuppliedtheappropriatearguments.Sometimesthescriptsimplytestswhether
argumentsexist(asinchkargs).Otherscriptstestforaspecificnumberorspecifickindsofarguments.
Youcanusetesttoaskaquestionaboutthestatusofafileargumentortherelationshipbetweentwo
filearguments.Afterverifyingthatatleastoneargumenthasbeengivenonthecommandline,the
followingscripttestswhethertheargumentisthenameofaregularfile(notadirectoryorothertypeof
file)intheworkingdirectory.Thetestbuiltinwiththefoptionandthefirstcommandlineargument
($1)checkthefile:
$catis_regfile
iftest$#-eq0
then
echo"Youmustsupplyatleastoneargument."
exit1
fi
iftest-f"$1"
then
echo"$1isaregularfileintheworkingdirectory"
else
echo"$1isNOTaregularfileintheworkingdirectory"
fi

Youcantestmanyothercharacteristicsofafilewithtestandvariousoptions.Table11-1listssomeof
theseoptions.
Table11-1.Optionstothetestbuiltin
Option Testsfiletoseeifit
d Existsandisadirectoryfile
e Exists
f Existsandisaregularfile(notadirectory)
rExistsandisreadable
sExistsandhasasizegreaterthan0bytes
wExistsandiswritable
xExistsandisexecutable
Othertestoptionsprovidewaystotestrelationshipsbetweentwofiles,suchaswhetheronefileis
newerthananother.Refertolaterexamplesinthischapterandtotestonpage794formoredetailed
information.
tip:Alwaystestthearguments
Tokeeptheexamplesinthisbookshortandfocusedonspecificconcepts,thecodeto
verifyargumentsisoftenomittedorabbreviated.Itisagoodpracticetotestargumentsin
shellprogramsthatotherpeoplewilluse.Doingsoresultsinscriptsthatareeasiertorun
anddebug.
[]isasynonymfortest
Thefollowingexampleanotherversionofchkargschecksforargumentsinawaythatismoretraditional
forLinuxshellscripts.Theexampleusesthebracket([])synonymfortest.Ratherthanusingtheword
testinscripts,youcansurroundtheargumentstotestwithbrackets.Thebracketsmustbesurrounded
bywhitespace(SPACEsorTABs).
$catchkargs2
if[$#-eq0]
then
echo"Usage:chkargs2argument..."1>&2
exit1
fi
echo"Programrunning."
exit0
$chkargs2
Usage:chkargs2arguments
$chkargs2abc
Programrunning.
Usagemessage
Theerrormessagethatchkargs2displaysiscalledausagemessageandusesthe1>&2notationto
redirectitsoutputtostandarderror(page260).Afterissuingtheusagemessage,chkargs2exitswithan
exitstatusof1,indicatingthatanerrorhasoccurred.Theexit0commandattheendofthescriptcauses
chkargs2toexitwitha0statusaftertheprogramrunswithoutanerror.TheBourneAgainShellreturnsa
0statusifyouomitthestatuscode.
Theusagemessageiscommonlyemployedtospecifythetypeandnumberofargumentsthescripttakes.
ManyLinuxutilitiesprovideusagemessagessimilartotheoneinchkargs2.Ifyoucallautilityorother
programwiththewrongnumberorkindofarguments,youwilloftenseeausagemessage.Followingis
theusagemessagethatcpdisplayswhenyoucallitwithoutanyarguments:
$cp

cp:missingfileargument
Try'cp--help'formoreinformation.
if...then...else
Theintroductionofanelsestatementturnstheifstructureintothetwo-waybranchshowninFigure11-2.
Theif...then...elsecontrolstructure(availableintcshwithaslightlydifferentsyntax)hasthefollowing
syntax:
iftest-command
then
commands
else
commands
fi
Figure11-2.Anif...then...elseflowchart
Becauseasemicolon(;)endsacommandjustasaNEWLINEdoes,youcanplacethenonthesameline
asifbyprecedingitwithasemicolon.(Becauseifandthenareseparatebuiltins,theyrequireacommand
separatorbetweenthem;asemicolonandNEWLINEworkequallywell.)Somepeoplepreferthis
notationforaestheticreasons,whileotherslikeitbecauseitsavesspace:
iftest-command;then
commands
else
commands
fi
Ifthetest-commandreturnsatruestatus,theifstructureexecutesthecommandsbetweenthethenand
elsestatementsandthendivertscontroltothestatementfollowingfi.Ifthetest-commandreturnsafalse
status,theifstructureexecutesthecommandsfollowingtheelsestatement.
Whenyourunthenextscript,namedout,withargumentsthatarefilenames,itdisplaysthefilesonthe
terminal.Ifthefirstargumentisv(calledanoptioninthiscase),outusesless(page45)todisplaythe
filesonepageatatime.Afterdeterminingthatitwascalledwithatleastoneargument,outtestsitsfirst
argumenttoseewhetheritisv.Iftheresultofthetestistrue(ifthefirstargumentisv),outusesthe
shiftbuiltintoshifttheargumentstogetridofthevanddisplaysthefilesusingless.Iftheresultof
thetestisfalse(ifthefirstargumentisnotv),thescriptusescattodisplaythefiles:
$catout
if[$#-eq0]
then
echo"Usage:out[-v]filenames..."1>&2
exit1
fi
if["$1"="-v"]
then
shift
less--"$@"
else
cat--"$@"
fi

optional
Inouttheargumenttocatandlesstellstheseutilitiesthatnomoreoptionsfollowonthecommandlineandnottoconsider
leadinghyphens()inthefollowinglistasindicatingoptions.Thusallowsyoutoviewafilewithanamethatstartswitha
hyphen.Althoughnotcommon,filenamesbeginningwithahyphendooccasionallyoccur.(Youcancreatesuchafilebyusingthe
commandcat>fname.)TheargumentworkswithallLinuxutilitiesthatusethegetoptsbuiltin(page497)toparsetheir
options;itdoesnotworkwithmoreandafewotherutilities.Thisargumentisparticularlyusefulwhenusedinconjunctionwith
rmtoremoveafilewhosenamestartswithahyphen(rmfname),includinganythatyoucreatewhileexperimentingwiththe
argument.
if...then...elif
Theif...then...elifcontrolstructure(Figure11-3;notavailableintcsh)hasthefollowingsyntax:
iftest-command
then
commands
eliftest-command
then
commands
...
else
commands
fi
Figure11-3.Anif...then...elifflowchart

Theelifstatementcombinestheelsestatementandtheifstatementandallowsyoutoconstructanested
setofif...then...elsestructures(Figure11-3).Thedifferencebetweentheelsestatementandtheelif
statementisthateachelsestatementmustbepairedwithafistatement,whereasmultiplenestedelif
statementsrequireonlyasingleclosingfistatement.
Thefollowingexampleshowsanif...then...elifcontrolstructure.Thisshellscriptcomparesthreewords
thattheuserenters.ThefirstifstatementusestheBooleanoperatorAND(a)asanargumenttotest.
Thetestbuiltinreturnsatruestatusonlyifthefirstandsecondlogicalcomparisonsaretrue(thatis,if
word1matchesword2andword2matchesword3).Iftestreturnsatruestatus,thescriptexecutesthe
commandfollowingthenextthenstatement,passescontroltothestatementfollowingfi,andterminates:
$catif3
echo-n"word1:"
readword1
echo-n"word2:"
readword2
echo-n"word3:"
readword3
if["$word1"="$word2"-a"$word2"="$word3"]
then
echo"Match:words1,2,&3"
elif["$word1"="$word2"]
then
echo"Match:words1&2"
elif["$word1"="$word3"]
then
echo"Match:words1&3"
elif["$word2"="$word3"]
then
echo"Match:words2&3"
else
echo"Nomatch"
fi
$if3
word1:apple
word2:orange
word3:pear
Nomatch
$if3
word1:apple
word2:orange
word3:apple
Match:words1&3
$if3
word1:apple
word2:apple
word3:apple
Match:words1,2,&3
Ifthethreewordsarenotthesame,thestructurepassescontroltothefirstelif,whichbeginsaseriesof
teststoseeifanypairofwordsisthesame.Asthenestingcontinues,ifanyoneoftheifstatementsis
satisfied,thestructurepassescontroltothenextthenstatementandsubsequentlytothestatement
followingfi.Eachtimeanelifstatementisnotsatisfied,thestructurepassescontroltothenextelif
statement.Thedoublequotationmarksaroundtheargumentstoechothatcontainampersands(&)
preventtheshellfrominterpretingtheampersandsasspecialcharacters.

optional:ThelnksScript
Thefollowingscript,namedlnks,demonstratestheif...thenandif...then...elifcontrolstructures.Thisscriptfindshardlinksto
itsfirstargument,afilename.Ifyouprovidethenameofadirectoryasthesecondargument,lnkssearchesforlinksinthat
directoryandallsubdirectories.Ifyoudonotspecifyadirectory,lnkssearchestheworkingdirectoryanditssubdirectories.This
scriptdoesnotlocatesymboliclinks.
$catlnks
#!/bin/bash
#Identifylinkstoafile
#Usage:lnksfile[directory]
if[$#-eq0-o$#-gt2];then
echo"Usage:lnksfile[directory]"1>&2
exit1
fi
if[-d"$1"];then
echo"Firstargumentcannotbeadirectory."1>&2
echo"Usage:lnksfile[directory]"1>&2
exit1
else
file="$1"
fi
if[$#-eq1];then
directory="."
elif[-d"$2"];then
directory="$2"
else
echo"Optionalsecondargumentmustbeadirectory."1>&2
echo"Usage:lnksfile[directory]"1>&2
exit1
fi
#Checkthatfileexistsandisaregularfile:
if[!-f"$file"];then

echo"lnks:$filenotfoundorspecialfile"1>&2
exit1
fi
#Checklinkcountonfile
set--$(ls-l"$file")
linkcnt=$2
if["$linkcnt"-eq1];then
echo"lnks:nootherhardlinksto$file"1>&2
exit0
fi
#Gettheinodeofthegivenfile
set$(ls-i"$file")
inode=$1
#Findandprintthefileswiththatinodenumber
echo"lnks:usingfindtosearchforlinks..."1>&2
find"$directory"-xdev-inum$inode-print
Alexhasafilenamedletterinhishomedirectory.Hewantstofindlinkstothisfileinhisandotherusers'homedirectoryfile
trees.Inthefollowingexample,Alexcallslnksfromhishomedirectorytoperformthesearch.Thesecondargumenttolnks,
/home,isthepathnameofthedirectoryhewantstostartthesearchin.Thelnksscriptreportsthat/home/alex/letterand
/home/jenny/draftarelinkstothesamefile:
$lnksletter/home
lnks:usingfindtosearchforlinks...
/home/alex/letter
/home/jenny/draft
Inadditiontotheif...then...elifcontrolstructure,lnksintroducesotherfeaturesthatarecommonlyusedinshellprograms.The
followingdiscussiondescribeslnkssectionbysection.
Specifytheshell
Thefirstlineofthelnksscriptuses#!(page265)tospecifytheshellthatwillexecutethescript:

#!/bin/bash
Inthischapterthe#!notationappearsonlyinmorecomplexexamples.Itensuresthatthepropershellexecutesthescript,even
whentheuserisrunningadifferentshellorthescriptiscalledfromanothershellscript.
Comments
Thesecondandthirdlinesoflnksarecomments;theshellignoresthetextthatfollowsapoundsignuptothenextNEWLINE
character.Thesecommentsinlnksbrieflyidentifywhatthefiledoesandhowtouseit:
#Identifylinkstoafile
#Usage:lnksfile[directory]
Usagemessages
Thefirstifstatementtestswhetherlnkswascalledwithzeroargumentsormorethantwoarguments:
if[$#-eq0-o$#-gt2];then
echo"Usage:lnksfile[directory]"1>&2
exit1
fi
Ifeitheroftheseconditionsistrue,lnkssendsausagemessagetostandarderrorandexitswithastatusof1.Thedouble
quotationmarksaroundtheusagemessagepreventtheshellfrominterpretingthebracketsasspecialcharacters.Thebracketsin
theusagemessageindicatethatthedirectoryargumentisoptional.
Thesecondifstatementtestswhetherthefirstcommandlineargument($1)isadirectory(thedargumenttotestreturnsatrue
valueifthefileexistsandisadirectory):
if[-d"$1"];then
echo"Firstargumentcannotbeadirectory."1>&2
echo"Usage:lnksfile[directory]"1>&2
exit1
else
file="$1"
fi
Ifthefirstargumentisadirectory,lnksdisplaysausagemessageandexits.Ifitisnotadirectory,lnkssavesthevalueof$1in
thefilevariablebecauselaterinthescriptsetresetsthecommandlinearguments.Ifthevalueof$1isnotsavedbeforetheset
commandisissued,itsvaluewillbelost.
Testthearguments

Thenextsectionoflnksisanif...then...elifstatement:
if[$#-eq1];then
directory="."
elif[-d"$2"];then
directory="$2"
else
echo"Optionalsecondargumentmustbeadirectory."1>&2
echo"Usage:lnksfile[directory]"1>&2
exit1
fi
Thefirsttest-commanddetermineswhethertheuserspecifiedasingleargumentonthecommandline.Ifthetest-command
returns0(true),theuser-createdvariablenameddirectoryisassignedthevalueoftheworkingdirectory(.).Ifthetest-command
returnsfalse,theelifstatementtestswhetherthesecondargumentisadirectory.Ifitisadirectory,thedirectoryvariableisset
equaltothesecondcommandlineargument,$2.If$2isnotadirectory,lnkssendsausagemessagetostandarderrorandexits
withastatusof1.
Thenextifstatementinlnkstestswhether$filedoesnotexist.Thistestkeepslnksfromwastingtimelookingforlinkstoa
nonexistentfile.
Thetestbuiltinwiththethreearguments!,f,and$fileevaluatestotrueifthefile$filedoesnotexist:
[!-f"$file"]
The!operatorprecedingthefargumenttotestnegatesitsresult,yieldingfalseifthefile$filedoesexistandisaregularfile.
Nextlnksusessetandlsltocheckthenumberoflinks$filehas:
#Checklinkcountonfile
set--$(ls-l"$file")
linkcnt=$2
if["$linkcnt"-eq1];then
echo"lnks:nootherhardlinksto$file"1>&2
exit0
fi
Thesetbuiltinusescommandsubstitution(page329)tosetthepositionalparameterstotheoutputoflsl.Thesecondfieldin
thisoutputisthelinkcount,sotheuser-createdvariablelinkcntissetequalto$2.Theusedwithsetpreventssetfrom
interpretingasanoptionthefirstargumentproducedbylsl(thefirstargumentistheaccesspermissionsforthefileandtypically

beginswith).Theifstatementcheckswhether$linkcntisequalto1;ifitis,lnksdisplaysamessageandexits.Althoughthis
messageisnottrulyanerrormessage,itisredirectedtostandarderror.Thewaylnkshasbeenwritten,allinformationalmessages
aresenttostandarderror.Onlythefinalproductoflnksthepathnamesoflinkstothespecifiedfileissenttostandardoutput,so
youcanredirecttheoutputasyouplease.
Ifthelinkcountisgreaterthanone,lnksgoesontoidentifytheinode(page880)for$file.Asexplainedonpage99,comparing
theinodesassociatedwithfilenamesisagoodwaytodeterminewhetherthefilenamesarelinkstothesamefile.Thelnksscript
usessettosetthepositionalparameterstotheoutputoflsi.Thefirstargumenttosetistheinodenumberforthefile,sothe
user-createdvariablenamedinodeisassignedthevalueof$1:
#Gettheinodeofthegivenfile
set$(ls-i"$file")
inode=$1
Finallylnksusesthefindutility(page655)tosearchforfileshavinginodenumbersthatmatch$inode:
#Findandprintthefileswiththatinodenumber
echo"lnks:usingfindtosearchforlinks..."1>&2
find"$directory"-xdev-inum$inode-print
Thefindutilitysearchesforfilesthatmeetthecriteriaspecifiedbyitsarguments,beginningitssearchwiththedirectory
specifiedbyitsfirstargument($directory)andsearchingallsubdirectories.Theremainingargumentsspecifythatthefilenamesof
fileshavinginodesmatching$inodeshouldbesenttostandardoutput.Becausefilesindifferentfilesystemscanhavethesame
inodenumberandnotbelinked,findmustsearchonlydirectoriesinthesamefilesystemas$directory.Thexdevargument
preventsfindfromsearchingdirectoriesonotherfilesystems.Refertopage96formoreinformationaboutfilesystemsandlinks.
Theechocommandprecedingthefindcommandinlnks,whichtellstheuserthatfindisrunning,isincludedbecausefind
frequentlytakesalongtimetorun.Becauselnksdoesnotincludeafinalexitstatement,theexitstatusoflnksisthatofthelast
commanditruns,find.
DEBUGGINGSHELLSCRIPTS
Whenyouarewritingascriptsuchaslnks,itiseasytomakemistakes.Youcanusetheshell'sxoptiontohelpdebugascript.
Thisoptioncausestheshelltodisplayeachcommandbeforeitrunsthecommand.Tracingascript'sexecutioninthiswaycan
giveyouinformationaboutwhereaproblemlies.
Youcanrunlnksasinthepreviousexampleandcausetheshelltodisplayeachcommandbeforeitisexecuted.Eithersetthex
optionforthecurrentshell(setx)sothatallscriptsdisplaycommandsastheyarerunorusethexoptiontoaffectonlytheshell
thatisrunningthescriptcalledbythecommandline.
$bash-xlnksletter/home
+'['2-eq0-o2-gt2']'
+'['-dletter']'
+file=letter
+'['2-eq1']'
+'['-d/home']'
+directory=/home

+'[''!'-fletter']'
...
PS4
EachcommandthatthescriptexecutesisprecededbythevalueofthePS4variableaplussign(+)bydefault,soyoucan
distinguishdebuggingoutputfromscript-producedoutput.YoumustexportPS4ifyousetitintheshellthatcallsthescript.The
nextcommandsetsPS4to>>>>followedbyaSPACEandexportsit:
$exportPS4='>>>>'
Youcanalsosetthexoptionoftheshellrunningthescriptbyputtingthefollowingsetcommandatthetopofthescript:
set-x
Putsetxanywhereinthescriptyouwanttoturndebuggingon.Turnthedebuggingoptionoffwithaplussign.
set+x
Thesetoxtraceandset+oxtracecommandsdothesamethingsassetxandset+x,respectively.
for...in
Thefor...incontrolstructure(tcshusesforeach)hasthefollowingsyntax:
forloop-indexinargument-list
do
commands
done
Thefor...instructure(Figure11-4)assignsthevalueofthefirstargumentintheargument-listtotheloop-
indexandexecutesthecommandsbetweenthedoanddonestatements.Thedoanddonestatementsmark
thebeginningandendoftheforloop.

Figure11-4.Afor...inflowchart
Afteritpassescontroltothedonestatement,thestructureassignsthevalueofthesecondargumentinthe
argument-listtotheloop-indexandrepeatsthecommands.Thestructurerepeatsthecommands
betweenthedoanddonestatementsonetimeforeachargumentintheargument-list.Whenthestructure
exhauststheargument-list,itpassescontroltothestatementfollowingdone.
Thefollowingfor...instructureassignsapplestotheuser-createdvariablefruitandthendisplaysthe
valueoffruit,whichisapples.Nextthestructureassignsorangestofruitandrepeatstheprocess.When
itexhauststheargumentlist,thestructuretransferscontroltothestatementfollowingdone,which
displaysamessage.
$catfruit
forfruitinapplesorangespearsbananas
do
echo"$fruit"
done
echo"Taskcomplete."
$fruit
apples
oranges
pears
bananas
Taskcomplete.
Thenextscriptliststhenamesofthedirectoryfilesintheworkingdirectorybyloopingoverallthefiles,
usingtesttodeterminewhichfilesaredirectories:
$catdirfiles
foriin*
do
if[-d"$i"]
then
echo"$i"
fi
done
Theambiguousfilereferencecharacter*matchesthenamesofallfiles(exceptinvisiblefiles)inthe
workingdirectory.Priortoexecutingtheforloop,theshellexpandsthe*andusestheresultinglistto
assignsuccessivevaluestotheindexvariablei.
for
Theforcontrolstructure(notavailableintcsh)hasthefollowingsyntax:
forloop-index
do
commands
done
Intheforstructuretheloop-indextakesonthevalueofeachofthecommandlinearguments,oneata
time.Itisthesameasthefor...instructure(Figure11-4)exceptforwhereitgetsvaluesfortheloop-
index.Theforstructureperformsasequenceofcommands,usuallyinvolvingeachargumentinturn.
Thefollowingshellscriptshowsaforstructuredisplayingeachcommandlineargument.Thefirstlineof
thescript,forarg,impliesforargin"$@",wheretheshellexpands"$@"intoalistofquoted
commandlinearguments"$1""$2""$3"andsoon.Thebalanceofthescriptcorrespondstothefor...in
structure.
$catfor_test
forarg
do
echo"$arg"
done
$for_testcandygumchocolate
candy
gum
chocolate

optional:ThewhosScript
Thefollowingscript,namedwhos,demonstratestheusefulnessoftheimplied"$@"intheforstructure.Yougivewhosoneor
moreuserorloginnamesasarguments,andwhosdisplaysinformationabouttheusers.Thewhosscriptgetstheinformationit
displaysfromthefirstandfifthfieldsinthe/etc/passwdfile.Thefirstfieldalwayscontainsausername,andthefifthfieldtypically
containstheuser'sfullname.Youcanprovidealoginnameasanargumenttowhostoidentifytheuser'snameorprovideaname
asanargumenttoidentifytheusername.Thewhosscriptissimilartothefingerutility,althoughwhosdeliverslessinformation.
$catwhos
#!/bin/bash
#adaptedfromfinger.shbyLeeSailer
#UNIX/WORLD,III:11,p.67,Fig.2
if[$#-eq0]
then
echo"Usage:whosid..."1>&2
exit1
fi
forid
do
gawk-F:'{print$1,$5}'/etc/passwd|
grep-i"$id"
done
BelowwhosidentifiestheuserwhoseusernameischasandtheuserwhosenameisMarilouSmith:
$whoschas"MarilouSmith"
chasCharlesCasey
msmithMarilouSmith
Useof"$@"
Thewhosscriptusesaforstatementtoloopthroughthecommandlinearguments.Inthisscripttheimplieduseof"$@"inthe
forloopisparticularlybeneficialbecauseitcausestheforlooptotreatanargumentthatcontainsaSPACEasasingleargument.
ThisexamplequotesMarilouSmith,whichcausestheshelltopassittothescriptasasingleargument.Thentheimplied"$@"
intheforstatementcausestheshelltoregeneratethequotedargumentMarilouSmithsothatitisagaintreatedasasingle
argument.
gawk

Foreachcommandlineargument,whossearchesthe/etc/passwdfile.Insidetheforloopthegawkutility(Chapter12)extracts
thefirst($1)andfifth($5)fieldsfromthelinesin/etc/passwd.TheF:optioncausesgawktouseacolon(:)asafieldseparator
whenitreads/etc/passwd,allowingittobreakeachlineintofields.Thegawkcommandsetsandusesthe$1and$5arguments;
theyareincludedwithinsinglequotationmarksandarenotinterpretedbytheshell.Donotconfusetheseargumentswith
positionalparameters,whichcorrespondtocommandlinearguments.Thefirstandfifthfieldsaresenttogrep(page683)viaa
pipe.Thegreputilitysearchesfor$id(whichhastakenonthevalueofacommandlineargument)initsinput.Theioption
causesgreptoignorecaseasitsearches;grepdisplayseachlineinitsinputthatcontains$id.
|attheendofaline
Aninterestingsyntacticalexceptionthatbashgivesthepipesymbol(|)appearsonthelinewiththegawkcommand:Youdonot
havetoquoteaNEWLINEthatimmediatelyfollowsapipesymbol(thatis,apipesymbolthatisthelastthingonaline)tokeepthe
NEWLINEfromexecutingacommand.Trygivingthecommandwho|andpressingRETURN.Theshell(nottcsh)displaysa
secondaryprompt.IfyouthenentersortfollowedbyanotherRETURN,youseeasortedwholist.Thepipeworkseventhougha
NEWLINEfollowsthepipesymbol.
while
Thewhilecontrolstructure(notavailableintcsh)hasthefollowingsyntax:
whiletest-command
do
commands
done
Aslongasthetest-command(Figure11-5)returnsatrueexitstatus,thewhilestructurecontinuesto
executetheseriesofcommandsdelimitedbythedoanddonestatements.Beforeeachloopthroughthe
commands,thestructureexecutesthetest-command.Whentheexitstatusofthetest-commandisfalse,
thestructurepassescontroltothestatementafterthedonestatement.
Figure11-5.Awhileflowchart
testbuiltin
Thefollowingshellscriptfirstinitializesthenumbervariabletozero.Thetestbuiltinthendetermines
whethernumberislessthan10.Thescriptusestestwiththeltargumenttoperformanumericaltest.
Fornumericalcomparisons,youmustusene(notequal),eq(equal),gt(greaterthan),ge(greaterthanor
equalto),lt(lessthan),orle(lessthanorequalto).Forstringcomparisonsuse=(equal)or!=(not
equal)whenyouareworkingwithtest.Inthisexample,testhasanexitstatusof0(true)aslongas
numberislessthan10.Aslongastestreturnstrue,thestructureexecutesthecommandsbetweenthe
doanddonestatements.Seepage794forinformationonthetestutility,whichisverysimilartothe
testbuiltin.
$catcount
#!/bin/bash
number=0
while["$number"-lt10]
do
echo-n"$number"
((number+=1))
done
echo
$count
0123456789
$
Theechocommandfollowingdodisplaysnumber.ThenpreventsechofromissuingaNEWLINE
followingitsoutput.Thenextcommandusesarithmeticevaluation[((...));page501]toincrementthe
valueofnumberby1.Thedonestatementterminatestheloopandreturnscontroltothewhilestatement
tostarttheloopoveragain.ThefinalechocausescounttosendaNEWLINEcharactertostandard
output,sothatthenextpromptoccursintheleftmostcolumnonthedisplay(ratherthanimmediately
following9).

optional:Thespell_checkScript
Theaspellutilitychecksthewordsinafileagainstadictionaryofcorrectlyspelledwords.Withtheloption,aspellrunsin
listmode:Inputcomesfromstandardinputandaspellsendseachpotentiallymisspelledwordtostandardoutput.Thefollowing
commandproducesalistofpossiblemisspellingsinthefileletter.txt:
$aspell-l<letter.txt
quikly
portible
frendly
Thenextshellscript,namedspell_check,showsanotheruseofawhilestructure.Tofindtheincorrectspellingsinafile,youcan
usespell_check,whichcallsaspelltocheckafileagainstasystemdictionarybutgoesastepfurther:Itenablesyoutospecify
alistofcorrectlyspelledwordsandremovesthesewordsfromtheoutputofaspell.Thisscriptisusefulforremovingwords
thatyouusefrequently,suchasnamesandtechnicalterms,thatarenotinastandarddictionary.Althoughyoucanduplicatethe
functionalityofspell_checkbyusingadditionalaspelldictionaries,thescriptisincludedhereforitsinstructivevalue.
Thespell_checkscriptrequirestwofilenamearguments:afilecontainingthelistofcorrectlyspelledwordsandafilethatyou
wanttocheck.Thefirstifstatementverifiesthattheuserspecifiedtwoarguments.Thenexttwoifstatementsverifythatboth
argumentsarereadablefiles.(Theexclamationpointnegatesthesenseofthefollowingoperator;theroperatorcausestestto
determinewhetherafileisreadable.Theresultisatestthatdetermineswhetherafileisnotreadable.)
$catspell_check
#!/bin/bash
#removecorrectspellingsfromaspelloutput
if[$#-ne2]
then
echo"Usage:spell_checkfile1file2"1>&2
echo"file1:listofcorrectspellings"1>&2
echo"file2:filetobechecked"1>&2
exit1
fi
if[!-r"$1"]
then
echo"spell_check:$1isnotreadable"1>&2
exit1
fi

if[!-r"$2"]
then
echo"spell_check:$2isnotreadable"1>&2
exit1
fi
aspell-l<"$2"|
whilereadline
do
if!grep"^$line$""$1">/dev/null
then
echo$line
fi
done
Thespell_checkscriptsendstheoutputfromaspell(withtheloptionsothatitproducesalistofmisspelledwordson
standardoutput)throughapipetostandardinputofawhilestructure,whichreadsonelineatatime(eachlinehasonewordon
it)fromstandardinput.Thetest-command(thatis,readline)returnsatrueexitstatusaslongasitreceivesalinefromstandard
input.
Insidethewhileloopanifstatement[1]monitorsthereturnvalueofgrep,whichdetermineswhetherthelinethatwasreadisin
theuser'slistofcorrectlyspelledwords.Thepatternthatgrepsearchesfor(thevalueof$line)isprecededandfollowedby
specialcharactersthatspecifythebeginningandendofaline(^and$,respectively).Thesespecialcharactersensurethatgrep
findsamatchonlyifthe$linevariablematchesanentirelineinthefileofcorrectlyspelledwords.(Otherwise,grepwould
matchastring,suchaspaul,intheoutputofaspellifthefileofcorrectlyspelledwordscontainedthewordpaulson.)These
specialcharacters,togetherwiththevalueofthe$linevariable,formaregularexpression(AppendixA).
Theoutputofgrepisredirectedto/dev/null(page122)becausetheoutputisnotneeded;onlytheexitcodeisimportant.Theif
statementchecksthenegatedexitstatusofgrep(theleadingexclamationpointnegatesorchangesthesenseoftheexitstatustrue
becomesfalse,andviceversa),whichis0ortrue(falsewhennegated)whenamatchinglineisfound.Iftheexitstatusisnot0
orfalse(truewhennegated),thewordwasnotinthefileofcorrectlyspelledwords.Theechobuiltinsendsalistofwordsthat
arenotinthefileofcorrectlyspelledwordstostandardoutput.
OnceitdetectstheEOF(endoffile),thereadbuiltinreturnsafalseexitstatus.Controlthenpassesoutofthewhilestructure,
andthescriptterminates.
Beforeyouusespell_check,createafileofcorrectspellingscontainingwordsthatyouusefrequentlybutthatarenotina
standarddictionary.Forexample,ifyouworkforacompanynamedBlinkenshipandKlimowski,Attorneys,youwouldput
BlinkenshipandKlimowskiintothefile.Thefollowingexampleshowshowspell_checkchecksthespellinginafilenamed
memoandremovesBlinkenshipandKlimowskifromtheoutputlistofincorrectlyspelledwords:
$aspell-l<memo
Blinkenship
Klimowski
targat

hte
$catword_list
Blinkenship
Klimowski
$spell_checkword_listmemo
targat
hte
Refertopage589formoreinformationonaspell.
[1]Thisifstatementcanalsobewrittenas
if!grep-qw"$line""$1"
Theqoptionsuppressestheoutputfromgrepsothatonlyanexitcodeisreturned.Thewoptioncausesgreptomatchonlyawhole
word.
until
Theuntil(notavailableintcsh)andwhile(availableintcshwithaslightlydifferentsyntax)
structuresareverysimilar,differingonlyinthesenseofthetestperformedatthetopoftheloop.Figure
11-6showsthatuntilcontinuestoloopuntilthetest-commandreturnsatrueexitstatus.Thewhile
structureloopswhilethetest-commandcontinuestoreturnatrueornonerrorcondition.Theuntilcontrol
structurehasthefollowingsyntax:

untiltest-command
do
commands
done
Figure11-6.Anuntilflowchart
Thefollowingscriptdemonstratesanuntilstructurethatincludesread.Whentheuserentersthecorrect
stringofcharacters,thetest-commandissatisfiedandthestructurepassescontroloutoftheloop.
$catuntil1
secretname=jenny
name=noname
echo"Trytoguessthesecretname!"
echo
until["$name"="$secretname"]
do
echo-n"Yourguess:"
readname
done
echo"Verygood."
$until1
Trytoguessthesecretname!
Yourguess:helen
Yourguess:barbara
Yourguess:rachael
Yourguess:jenny
Verygood
ThefollowinglockttyscriptissimilartothelockcommandonBerkeleyUNIXandtheLockScreen
menuselectioninGNOME.Thescriptpromptsyouforakey(password)andusesanuntilcontrol
structuretolocktheterminal.Theuntilstatementcausesthesystemtoignoreanycharacterstypedatthe
keyboarduntiltheusertypesinthekeyonalinebyitself,whichunlockstheterminal.Thelockttyscript
cankeeppeoplefromusingyourterminalwhileyouareawayfromitforshortperiodsoftime.Itsaves
youfromhavingtologoutifyouareconcernedaboutotherusersusingyourlogin.
$catlocktty
#!/bin/bash
#UNIX/WORLD,III:4
trap''12318
stty-echo
echo-n"Key:"
readkey_1
echo
echo-n"Again:"
readkey_2
echo
key_3=
if["$key_1"="$key_2"]
then
tputclear
until["$key_3"="$key_2"]
do
readkey_3
done
else
echo"locktty:keysdonotmatch"1>&2
fi
sttyecho
tip:Forgetyourpasswordforlocktty?
Ifyouforgetyourkey(password),youwillneedtologinfromanother(virtual)terminal
andkilltheprocessrunninglocktty.

trapbuiltin
Thetrapbuiltin(page493;notavailableintcsh)atthebeginningofthelockttyscriptstopsauser
frombeingabletoterminatethescriptbysendingitasignal(forexample,bypressingtheinterruptkey).
Trappingsignal18meansthatnoonecanuseCONTROL-Z(jobcontrol,astopfromatty)todefeatthe
lock.(SeeTable11-5onpage494foralistofsignals.)Thesttyechocommand(page778)causesthe
terminalnottodisplaycharacterstypedatthekeyboard,therebypreventingthekeythattheuserenters
fromappearingonthescreen.Afterturningoffkeyboardecho,thescriptpromptstheuserforakey,reads
itintotheuser-createdvariablekey_1,promptstheusertoenterthesamekeyagain,andsavesitin
key_2.Thestatementkey_3=createsavariablewithaNULLvalue.Ifkey_1andkey_2match,locktty
clearsthescreen(withthetputcommand)andstartsanuntilloop.Theuntilloopkeepsattemptingto
readfromtheterminalandassigningtheinputtothekey_3variable.Oncetheusertypesinastringthat
matchesoneoftheoriginalkeys(key_2),theuntilloopterminatesandkeyboardechoisturnedonagain.
Table11-5.Signals
Type Name Number Generatingcondition
Notarealsignal EXIT 0
Exitbecauseofexitcommandor
reachingtheendoftheprogram
(notanactualsignalbutusefulin
trap)
Hangup SIGHUPorHUP 1 Disconnecttheline
Terminalinterrupt SIGINTorINT 2 Presstheinterruptkey(usually
CONTROL-C)
Quit SIGQUITorQUIT 3
Pressthequitkey(usually
CONTROL-SHIFT-|or
CONTROL-SHIFT-\)
Kill SIGKILLorKILL 9
Thekillcommandwiththe9
option(cannotbetrapped;use
onlyasalastresort)
Softwaretermination SIGTERMor
TERM 15 Defaultofthekillcommand
Stop SIGTSTPorTSTP 20 Pressthesuspendkey(usually
CONTROL-Z)
Debug DEBUG
Executescommandsspecifiedin
theTRapstatementaftereach
command(notanactualsignalbut
usefulintrap)
Error ERR
Executescommandsspecifiedin
theTRapstatementaftereach
commandthatreturnsanonzero
exitstatus(notanactualsignalbut

usefulinTRap)
breakANDcontinue
Youcaninterruptafor,while,oruntilloopbyusingabreakorcontinuestatement.Thebreakstatement
transferscontroltothestatementafterthedonestatement,whichterminatesexecutionoftheloop.The
continuecommandtransferscontroltothedonestatement,whichcontinuesexecutionoftheloop.
Thefollowingscriptdemonstratestheuseofthesetwostatements.Thefor...instructureloopsthroughthe
values110.Thefirstifstatementexecutesitscommandswhenthevalueoftheindexislessthanorequal
to3($indexle3).Thesecondifstatementexecutesitscommandswhenthevalueoftheindexisgreater
thanorequalto8($indexge8).Inbetweenthetwoifs,echodisplaysthevalueoftheindex.Forall
valuesuptoandincluding3,thefirstifstatementdisplayscontinueandexecutesacontinuestatement
thatskipsecho$indexandthesecondifstatementandcontinueswiththenextforstatement.Forthevalue
of8,thesecondifstatementdisplaysbreakandexecutesabreakstatementthatexitsfromtheforloop:
$catbrk
forindexin12345678910
do
if[$index-le3];then
echo"continue"
continue
fi
#
echo$index
#
if[$index-ge8];then
echo"break"
break
fi
done
$brk
continue
continue
continue
4
5
6
7
8
break
case
Thecasestructure(Figure11-7,page461)isamultiple-branchdecisionmechanism.Thepathtaken
throughthestructuredependsonamatchorlackofamatchbetweenthetest-stringandoneofthe
patterns.Thecasecontrolstructure(tcshusesswitch)hasthefollowingsyntax:
casetest-stringin
pattern-1)
commands-1
;;
pattern-2)
commands-2

;;
pattern-3)
commands-3
;;
...
esac
Figure11-7.Acaseflowchart
Thefollowingcasestructureexaminesthecharacterthattheuserentersasthetest-string.Thisvalueis
heldinthevariableletter.Ifthetest-stringhasavalueofA,thestructureexecutesthecommand
followingthepatternA.Therightparenthesisispartofthecasecontrolstructure,notpartofthepattern.
Ifthetest-stringhasavalueofBorC,thestructureexecutesthecommandfollowingthematching
pattern.Theasterisk(*)indicatesanystringofcharactersandservesasacatchallincasethereisno
match.Ifnopatternmatchesthetest-stringandifthereisnocatchall(*)pattern,controlpassestothe
commandfollowingtheesacstatement,withoutthecasestructuretakinganyaction.
$catcase1
echo-n"EnterA,B,orC:"
readletter
case"$letter"in
A)
echo"YouenteredA"
;;
B)
echo"YouenteredB"
;;
C)
echo"YouenteredC"
;;
*)
echo"YoudidnotenterA,B,orC"
;;
esac
$case1
EnterA,B,orC:B
YouenteredB

Thenextexecutionofcase1showstheuserenteringalowercaseb.Becausethetest-stringbdoesnot
matchtheuppercaseBpattern(oranyotherpatterninthecasestatement),theprogramexecutesthe
commandsfollowingthecatchallpatternanddisplaysamessage:
$case1
EnterA,B,orC:b
YoudidnotenterA,B,orC
Thepatterninthecasestructureisanalogoustoanambiguousfilereference.Itcanincludeanyofthe
specialcharactersandstringsshowninTable11-2.
Table11-2.Patterns
Pattern Function
*Matchesanystringofcharacters.Useforthedefaultcase.
?Matchesanysinglecharacter.
[...]
Definesacharacterclass.Anycharactersenclosedwithinbracketsaretried,
oneatatime,inanattempttomatchasinglecharacter.Ahyphenbetween
twocharactersspecifiesarangeofcharacters.
|Separatesalternativechoicesthatsatisfyaparticularbranchofthecase
structure.
Thenextscriptacceptsbothuppercaseandlowercaseletters:
$catcase2
echo-n"EnterA,B,orC:"
readletter
case"$letter"in
a|A)
echo"YouenteredA"
;;
b|B)
echo"YouenteredB"
;;
c|C)
echo"YouenteredC"
;;
*)
echo"YoudidnotenterA,B,orC"
;;
esac
$case2
EnterA,B,orC:b
YouenteredB

optional
Thefollowingexampleshowshowyoucanusethecasestructuretocreateasimplemenu.Thecommand_menuscriptuses
echotopresentmenuitemsandprompttheuserforaselection.(Theselectcontrolstructure[page466]makesitmucheasierto
codeamenu.)Thecasestructurethenexecutestheappropriateutilitydependingontheuser'sselection.
$catcommand_menu
#!/bin/bash
#menuinterfacetosimplecommands
echo-e"\nCOMMANDMENU\n"
echo"a.Currentdateandtime"
echo"b.Userscurrentlyloggedin"
echo"c.Nameoftheworkingdirectory"
echo-e"d.Contentsoftheworkingdirectory\n"
echo-n"Entera,b,c,ord:"
readanswer
echo
case"$answer"in
a)
date
;;
b)
who
;;
c)
pwd
;;
d)
ls
;;
*)
echo"Thereisnoselection:$answer"
;;

esac
$command_menu
COMMANDMENU
a.Currentdateandtime
b.Userscurrentlyloggedin
c.Nameoftheworkingdirectory
d.Contentsoftheworkingdirectory
Entera,b,c,ord:a
WedJan512:31:12PST2005
echoe
Theeoptioncausesechotointerpret\nasaNEWLINEcharacter.Ifyoudonotincludethisoption,echodoesnotoutputthe
extrablanklinesthatmakethemenueasytoreadbutinsteadoutputsthe(literal)two-charactersequence\n.Theeoptioncauses
echotointerpretseveralotherbackslash-quotedcharacters(Table11-3).Remembertoquote(i.e.,placedoublequotationmarks
aroundthestring)thebackslash-quotedcharactersothattheshelldoesnotinterpretitbutpassesthebackslashandthecharacter
toecho.Seexpg_echo(page322)forawaytoavoidusingtheeoption.
Table11-3.Specialcharactersinecho(mustusee)
Quotedcharacter echodisplays
\a Alert(bell)
\b BACKSPACE
\c SuppresstrailingNEWLINE
\f FORMFEED
\n NEWLINE
\r RETURN
\t HorizontalTAB
\v VerticalTAB

\\ Backslash
\nnn ThecharacterwiththeASCIIoctalcodennn;ifnnnisnotvalid,
echodisplaysthestringliterally
Youcanalsousethecasecontrolstructuretotakevariousactionsinascript,dependingonhowmanyargumentsthescriptis
calledwith.Thefollowingscript,namedsafedit,usesacasestructurethatbranchesbasedonthenumberofcommandline
arguments($#).Itsavesabackupcopyofafileyouareeditingwithvim.
$catsafedit
#!/bin/bash
#UNIX/WORLD,IV:11
PATH=/bin:/usr/bin
script=$(basename$0)
case$#in
0)
vim
exit0
;;
1)
if[!-f"$1"]
then
vim"$1"
exit0
fi
if[!-r"$1"-o!-w"$1"]
then
echo"$script:checkpermissionson$1"1>&2
exit1
else
editfile=$1
fi
if[!-w"."]
then

echo"$script:backupcannotbe"\
"createdintheworkingdirectory"1>&2
exit1
fi
;;
*)
echo"Usage:$script[file-to-edit]"1>&2
exit1
;;
esac
tempfile=/tmp/$$.$script
cp$editfile$tempfile
ifvim$editfile
then
mv$tempfilebak.$(basename$editfile)
echo"$script:backupfilecreated"
else
mv$tempfileediterr
echo"$script:editerror--copyof"\
"originalfileisinediterr"1>&2
fi
Ifyoucallsafeditwithoutanyarguments,thecasestructureexecutesitsfirstbranchandcallsvimwithoutafilenameargument.
Becauseanexistingfileisnotbeingedited,safeditdoesnotcreateabackupfile.(Seethe:wcommandonpage153foran
explanationofhowtoexitfromvimwhenyouhavecalleditwithoutafilename.)Ifyoucallsafeditwithoneargument,itruns
thecommandsinthesecondbranchofthecasestructureandverifiesthatthefilespecifiedby$1doesnotyetexistoristhename
ofafileforwhichtheuserhasreadandwritepermission.Thesafeditscriptalsoverifiesthattheuserhaswritepermissionfor
theworkingdirectory.Iftheusercallssafeditwithmorethanoneargument,thethirdbranchofthecasestructurepresentsa
usagemessageandexitswithastatusof1.
SetPATH
Inadditiontousingacasestructureforbranchingbasedonthenumberofcommandlinearguments,thesafeditscriptintroduces
severalotherfeatures.First,atthebeginningofthescript,thePATHvariableissettosearch/binand/usr/bin.SettingPATHin
thiswayensuresthatthecommandsexecutedbythescriptarestandardutilities,whicharekeptinthosedirectories.Bysetting
PATHinsideascript,youcanavoidtheproblemsthatmightoccurifusershavesetPATHtosearchtheirowndirectoriesfirstand
havescriptsorprogramswiththesamenamesastheutilitiesthescriptcalls.Youcanalsoincludeabsolutepathnameswithina
scripttoachievethisend,butthispracticecanmakeascriptlessportable.
Nameoftheprogram

Inasecondsafeditfeature,thefollowinglinecreatesavariablenamedscriptandassignsthesimplefilenameofthescripttoit:
script=$(basename$0)
Thebasenameutilitysendsthesimplefilenamecomponentofitsargumenttostandardoutput,whichisassignedtothescript
variable,usingcommandsubstitution.The$0holdsthecommandthescriptwascalledwith(page481).Nomatterwhichofthe
followingcommandstheusercallsthescriptwith,theoutputofbasenameisthesimplefilenamesafedit:
$/home/alex/bin/safeditmemo
$./safeditmemo
$safeditmemo
Afterthescriptvariableisset,itreplacesthefilenameofthescriptinusageanderrormessages.Byusingavariablethatisderived
fromthecommandthatinvokedthescriptratherthanafilenamethatishardcodedintothescript,youcancreatelinkstothescript
orrenameit,andtheusageanderrormessageswillstillprovideaccurateinformation.
Namingtemporaryfiles
Athirdsignificantfeatureofsafeditrelatestotheuseofthe$$variableinthenameofatemporaryfile.Thestatementfollowing
theesacstatementcreatesandassignsavaluetothetempfilevariable.Thisvariablecontainsthenameofatemporaryfilethatis
storedinthe/tmpdirectory,asaremanytemporaryfiles.ThetemporaryfilenamebeginswiththePIDnumberoftheshelland
endswiththenameofthescript.UseofthePIDnumberensuresthatthefilenameisunique,andsafeditwillnotattemptto
overwriteanexistingfile,asmighthappeniftwopeoplewereusingsafeditatthesametime.Thenameofthescriptisappended
sothat,shouldthefilebeleftin/tmpforsomereason,youcanfigureoutwhereitcamefrom.
ThePIDnumberisusedinfrontofratherthanafter$scriptinthefilenamebecauseofthe14-characterlimitplacedonfilenamesby
someolderversionsofUNIX.Linuxsystemsdonothavethislimitation.BecausethePIDnumberensurestheuniquenessofthe
filename,itisplacedfirstsothatitcannotbetruncated.(Ifthe$scriptcomponentistruncated,thefilenameisstillunique.)For
thesamereason,whenabackupfileiscreatedinsidetheifcontrolstructureafewlinesdowninthescript,thefilenameis
composedofthestringbak.followedbythenameofthefilebeingedited.Onanoldersystem,ifbakwereusedasasuffixrather
thanaprefixandtheoriginalfilenamewere14characterslong,.bakmightbelostandtheoriginalfilewouldbeoverwritten.The
basenameutilityextractsthesimplefilenameof$editfilebeforeitisprefixedwithbak.
Fourth,safeditusesanunusualtest-commandintheifstructure:vim$editfile.Thetest-commandcallsvimtoedit$editfile.
Whenyoufinisheditingthefileandexitfromvim,vimreturnsanexitcode.Theifcontrolstructureusesthatexitcodeto
determinewhichbranchtotake.Iftheeditingsessioncompletedsuccessfully,vimreturns0andthestatementsfollowingthe
thenstatementareexecuted.Ifvimdoesnotterminatenormally(aswouldoccuriftheuserkilled[page693]thevim
process),vimreturnsanonzeroexitstatusandthescriptexecutesthestatementsfollowingelse.
select
Theselectcontrolstructure(notavailableintcsh)isbasedontheonefoundintheKornShell.It
displaysamenu,assignsavaluetoavariablebasedontheuser'schoiceofitems,andexecutesaseriesof
commands.Theselectcontrolstructurehasthefollowingsyntax:
selectvarname[inarg...]
do
commands
done
Theselectstructuredisplaysamenuoftheargitems.Ifyouomitthekeywordinandthelistofarguments,
selectusesthepositionalparametersinplaceoftheargitems.Themenuisformattedwithnumbers
beforeeachitem.Forexample,aselectstructurethatbeginswith
selectfruitinapplebananablueberrykiwiorangewatermelonSTOP
displaysthefollowingmenu:
1)apple3)blueberry5)orange7)STOP
2)banana4)kiwi6)watermelon
TheselectstructureusesthevaluesoftheLINESandCOLUMNSvariablestodeterminethesizeofthe
display.(LINEShasadefaultvalueof24;COLUMNShasadefaultvalueof80.)WithCOLUMNSset
to20,themenulookslikethis:
1)apple
2)banana
3)blueberry
4)kiwi
5)orange
6)watermelon
7)STOP
PS3
AfterdisplayingthemenuselectdisplaysthevalueofPS3,thespecialselectprompt.Thedefaultvalue
ofPS3is?#butyoutypicallysetPS3toamoremeaningfulvalue.Whenyouenteravalidnumber(onein
themenurange)inresponsetothePS3prompt,selectsetsvarnametotheargumentcorrespondingtothe
numberyouentered.Ifyoumakeaninvalidentry,varnameissettonull.Eitherwayselectstoresyour
responseinthekeywordvariableREPLYandthenexecutesthecommandsbetweendoanddone.Ifyou
pressRETURNwithoutenteringachoice,theshellredisplaysthemenuandthePS3prompt.
TheselectstructurecontinuestoissuethePS3promptandexecutethecommandsuntilsomethingcauses
ittoexittypicallyabreakorexitstatement.Abreakstatementexitsfromtheloopandanexitstatement
exitsfromthescript.
Thefollowingscriptillustratestheuseofselect:
$catfruit2
#!/bin/bash
PS3="Chooseyourfavoritefruitfromthesepossibilities:"
selectFRUITinapplebananablueberrykiwiorangewatermelonSTOP
do
if["$FRUIT"==""];then
echo-e"Invalidentry.\n"
continue
elif[$FRUIT=STOP];then
echo"Thanksforplaying!"
break
fi
echo"Youchose$FRUITasyourfavorite."
echo-e"Thatischoicenumber$REPLY.\n"
done
$fruit2
1)apple3)blueberry5)orange7)STOP
2)banana4)kiwi6)watermelon
Chooseyourfavoritefruitfromthesepossibilities:3
Youchoseblueberryasyourfavorite.
Thatischoicenumber3.
Chooseyourfavoritefruitfromthesepossibilities:99
Invalidentry.
Chooseyourfavoritefruitfromthesepossibilities:7
Thanksforplaying!
AftersettingthePS3promptandestablishingthemenuwiththeselectstatement,fruit2executesthe
commandsbetweendoanddone.Iftheusermakesaninvalidentry,theshellsetsvarname($FRUIT)to
anullvalue,sofruit2firsttestswhether$FRUITisnull.Ifitis,echodisplaysanerrorandcontinue
causestheshelltoredisplaythePS3prompt.Iftheentryisvalid,thescripttestswhethertheuserwantsto
stop.Ifso,echodisplaysamessageandbreakexitsfromtheselectstructure(andfromthescript).Ifthe
userenteredavalidresponseanddoesnotwanttostop,thescriptdisplaysthenameandnumberofthe
user'sresponse.(Seepage463forinformationabouttheeoptiontoecho.)
HereDocument
AHeredocumentallowsyoutoredirectinputtoashellscriptfromwithintheshellscriptitself.AHere
documentissocalledbecauseitishereimmediatelyaccessibleintheshellscriptinsteadofthere,perhaps
inanotherfile.
Thefollowingscript,namedbirthday,containsaHeredocument.Thetwolessthan(<<)symbolsinthe
firstlineindicatethataHeredocumentfollows.OneormorecharactersthatdelimittheHeredocument
followthelessthansymbolsthisexampleusesaplussign.Whereastheopeningdelimitermustappear
adjacenttothelessthansymbols,theclosingdelimitermustbeonalinebyitself.Theshellsends
everythingbetweenthetwodelimiterstotheprocessasstandardinput.Intheexampleitisasthoughyou
hadredirectedstandardinputtogrepfromafile,exceptthatthefileisembeddedintheshellscript:
$catbirthday
grep-i"$1"<<+
AlexJune22
BarbaraFebruary3
DarleneMay8
HelenMarch13
JennyJanuary23
NancyJune26
+
$birthdayJenny
JennyJanuary23
$birthdayjune
AlexJune22
NancyJune26
Whenyourunbirthday,itlistsalltheHeredocumentlinesthatcontaintheargumentyoucalleditwith.In
thiscasethefirsttimebirthdayisrun,itdisplaysJenny'sbirthdaybecauseitiscalledwithanargumentof
Jenny.ThesecondrundisplaysallthebirthdaysinJune.Theiargumentcausesgrep'ssearchnottobe
casesensitive.

optional
Thenextscript,namedbundle,[2]includesacleveruseofaHeredocument.Thebundlescriptisanelegantexampleofascript
thatcreatesashellarchive(shar)file.Thescriptcreatesafilethatisitselfashellscriptcontainingseveralotherfilesaswellasthe
codetore-createtheoriginalfiles:
$catbundle
#!/bin/bash
#bundle:groupfilesintodistributionpackage
echo"#Tounbundle,bashthisfile"
fori
do
echo"echo$i1>&2"
echo"cat>$i<<'Endof$i'"
cat$i
echo"Endof$i"
done
Justastheshelldoesnottreatspecialcharactersthatoccurinstandardinputofashellscriptasspecial,sotheshelldoesnottreat
thespecialcharactersthatoccurbetweenthedelimitersinaHeredocumentasspecial.
Asthefollowingexampleshows,theoutputofbundleisashellscript,whichisredirectedtoafilenamedbothfiles.Itcontains
thecontentsofeachfilegivenasanargumenttobundle(file1andfile2inthiscase)insideaHeredocument.Toextractthe
originalfilesfrombothfiles,yousimplyrunitasanargumenttoabashcommand.BeforeeachHeredocumentisacat
commandthatcausestheHeredocumenttobewrittentoanewfilewhenbothfilesisrun:
$catfile1
Thisisafile.
Itcontainstwolines.
$catfile2
Thisisanotherfile.
Itcontains
threelines.
$bundlefile1file2>bothfiles

$catbothfiles
#Tounbundle,bashthisfile
echofile11>&2
cat>file1<<'Endoffile1'
Thisisafile.
Itcontainstwolines.
Endoffile1
echofile21>&2
cat>file2<<'Endoffile2'
Thisisanotherfile.
Itcontains
threelines.
Endoffile2
Inthenextexample,file1andfile2areremovedbeforebothfilesisrun.Thebothfilesscriptechoesthenamesofthefilesit
createsasitcreatesthem.Thelscommandthenshowsthatbothfileshasre-createdfile1andfile2:
$rmfile1file2
$bashbothfiles
file1
file2
$ls
bothfiles
file1
file2
[2]ThankstoBrianW.KernighanandRobPike,TheUnixProgrammingEnvironment(EnglewoodCliffs,N.J.:Prentice-Hall,
1984),98.Reprintedwithpermission.
fileDescriptors
Asdiscussedonpage260,beforeaprocesscanreadfromorwritetoafileitmustopenthatfile.Whena
processopensafile,Linuxassociatesanumber(calledafiledescriptor)withthefile.Eachprocesshas
itsownsetofopenfilesanditsownfiledescriptors.Afteropeningafile,aprocessreadsfromand
writestothatfilebyreferringtoitsfiledescriptor.Whenitnolongerneedsthefile,theprocessclosesthe
file,freeingthefiledescriptor.
AtypicalLinuxprocessstartswiththreeopenfiles:standardinput(filedescriptor0),standardoutput
(filedescriptor1),andstandarderror(filedescriptor2).Oftenthosearetheonlyfilestheprocessneeds.
Recallthatyouredirectstandardoutputwiththesymbol>orthesymbol1>andthatyouredirectstandard
errorwiththesymbol2>.Althoughyoucanredirectotherfiledescriptors,becausefiledescriptorsother
than0,1,and2donothaveanyspecialconventionalmeaning,itisrarelyusefultodoso.
Theexceptionisinprogramsthatyouwriteyourself,inwhichcaseyoucontrolthemeaningofthefile
descriptorsandcantakeadvantageofredirection.
Openingafiledescriptor
TheBourneAgainShellopensfilesusingtheexecbuiltinasfollows:
execn>outfile
execm<infile
Thefirstlineopensoutfileforoutputandholdsitopen,associatingitwithfiledescriptorn.Thesecond
lineopensinfileforinputandholdsitopen,associatingitwithfiledescriptorm.
Duplicatingafiledescriptor
The<&tokenduplicatesaninputfiledescriptor;use>&toduplicateanoutputfiledescriptor.Youcan
duplicateafiledescriptorbymakingitrefertothesamefileasanotheropenfiledescriptor,suchas
standardinputoroutput.Usethefollowingformattoopenorredirectfiledescriptornasaduplicateof
filedescriptorm:
execn<&m
Onceyouhaveopenedafile,youcanuseitforinputandoutputintwodifferentways.First,youcanuse
I/Oredirectiononanycommandline,redirectingstandardoutputtoafiledescriptorwith>&nor
redirectingstandardinputfromafiledescriptorwith<&n.Second,youcanusetheread(page487)and
echobuiltins.Ifyouinvokeothercommands,includingfunctions(page315),theyinherittheseopenfiles
andfiledescriptors.Whenyouhavefinishedusingafile,youcancloseitwith
execn<&
Whenyouinvoketheshellfunctioninthenextexample,namedmycp,withtwoarguments,itcopiesthe
filenamedbythefirstargumenttothefilenamedbythesecondargument.Ifyousupplyonlyone
argument,thescriptcopiesthefilenamedbytheargumenttostandardoutput.Ifyouinvokemycpwithno
arguments,itcopiesstandardinputtostandardoutput.
tip:Afunctionisnotashellscript
Themycpexampleisashellfunction;itwillnotworkasyouexpectifyouexecuteitasa
shellscript.(Itwillwork:Thefunctionwillbecreatedinaveryshort-livedsubshell,
whichisprobablyoflittleuse.)Youcanenterthisfunctionfromthekeyboard.Ifyouputthe
functioninafile,youcanrunitasanargumenttothe.(dot)builtin(page259).Youcan
alsoputthefunctioninastartupfileifyouwantittobealwaysavailable(page317).
functionmycp()
{
case$#in
0)
#zeroarguments
#filedescriptor3duplicatesstandardinput
#filedescriptor4duplicatesstandardoutput
exec3<&04<&1
;;
1)
#oneargument
#openthefilenamedbytheargumentforinput
#andassociateitwithfiledescriptor3
#filedescriptor4duplicatesstandardoutput
exec3<$14<&1
;;
2)
#twoarguments
#openthefilenamedbythefirstargumentforinput
#andassociateitwithfiledescriptor3
#openthefilenamedbythesecondargumentforoutput
#andassociateitwithfiledescriptor4
exec3<$14>$2
;;
*)
echo"Usage:mycp[source[dest]]"
return1
;;
esac
#callcatwithinputcomingfromfiledescriptor3
#andoutputgoingtofiledescriptor4
cat<&3>&4
#closefiledescriptors3and4
exec3<&-4<&-
}
Therealworkofthisfunctionisdoneinthelinethatbeginswithcat.Therestofthescriptarrangesfor
filedescriptors3and4,whicharetheinputandoutputofthecatcommand,tobeassociatedwiththe
appropriatefiles.

optional
Thenextprogramtakestwofilenamesonthecommandline,sortsboth,andsendstheoutputtotemporaryfiles.Theprogram
thenmergesthesortedfilestostandardoutput,precedingeachlinebyanumberthatindicateswhichfileitcamefrom.
$catsortmerg
#!/bin/bash
usage()
{
if[$#-ne2];then
echo"Usage:$0file1file2"2>&1
exit1
fi
}
#Defaulttemporarydirectory
:${TEMPDIR:=/tmp}
#Checkargumentcount
usage"$@"
#Setuptemporaryfilesforsorting
file1=$TEMPDIR/$$.file1
file2=$TEMPDIR/$$.file2
#Sort
sort$1>$file1
sort$2>$file2
#Open$file1and$file2forreading.Usefiledescriptors3and4.
exec3<$file1
exec4<$file2
#Readthefirstlinefromeachfiletofigureouthowtostart.
readLine1<&3

status1=$?
readLine2<&4
status2=$?
#Strategy:whilethereisstillinputleftinbothfiles:
#Outputthelinethatshouldcomefirst.
#Readanewlinefromthefilethatlinecamefrom.
while[$status1-eq0-a$status2-eq0]
do
if[["$Line2">"$Line1"]];then
echo-e"1.\t$Line1"
read-u3Line1
status1=$?
else
echo-e"2.\t$Line2"
read-u4Line2
status2=$?
fi
done
#Nowoneofthefilesisatend-of-file.
#Readfromeachfileuntiltheend.
#Firstfile1:
while[$status1-eq0]
do
echo-e"1.\t$Line1"
readLine1<&3
status1=$?
done
#Nextfile2:
while[[$status2-eq0]]
do
echo-e"2.\t$Line2"

readLine2<&4
status2=$?
done
#Closeandremovebothinputfiles
exec3<&-4<&-
rm-f$file1$file2
exit0
ParametersAndVariables
Shellparametersandvariableswereintroducedonpage277.Thissectionaddstothepreviouscoverage
withadiscussionofarrayvariables,globalversuslocalvariables,specialandpositionalparameters,
andexpandingnullandunsetvariables.
ArrayVariables
TheBourneAgainShellsupportsone-dimensionalarrayvariables.Thesubscriptsareintegerswithzero-
basedindexing(i.e.,thefirstelementofthearrayhasthesubscript0).Thefollowingformatdeclaresand
assignsvaluestoanarray:
name=(element1element2...)
ThefollowingexampleassignsfourvaluestothearrayNAMES:
$NAMES=(maxhelensamzach)
Youreferenceasingleelementofanarrayasfollows:
$echo${NAMES[2]}
sam
Thesubscripts[*]and[@]bothextracttheentirearraybutworkdifferentlywhenusedwithindouble
quotationmarks.An@producesanarraythatisaduplicateoftheoriginalarray;an*producesasingle
elementofanarray(oraplainvariable)thatholdsalltheelementsofthearrayseparatedbythefirst
characterinIFS(normallyaSPACE).Inthefollowingexample,thearrayAisfilledwiththeelementsof
theNAMESvariableusingan*,andBisfilledusingan@.Thedeclarebuiltinwiththeaoption
displaysthevaluesofthearrays(andremindsyouthatbashuseszero-basedindexingforarrays):
$A=("${NAMES[*]}")
$B=("${NAMES[@]}")
$declare-a
declare-aA='([0]="maxhelensamzach")'
declare-aB='([0]="max"[1]="helen"[2]="sam"[3]="zach")'
...
declare-aNAMES='([0]="max"[1]="helen"[2]="sam"[3]="zach")'
Fromtheoutputofdeclare,youcanseethatNAMESandBhavemultipleelements.Incontrast,A,
whichwasassigneditsvaluewithan*withindoublequotationmarks,hasonlyoneelement:Ahasallits
elementsenclosedbetweendoublequotationmarks.
Inthenextexample,echoattemptstodisplayelement1ofarrayA.NothingisdisplayedbecauseAhas
onlyoneelementandthatelementhasanindexof0.Element0ofarrayAholdsallfournames.Element1
ofBholdstheseconditeminthearrayandelement0holdsthefirstitem.
$echo${A[1]}
$echo${A[0]}
maxhelensamzach
$echo${B[1]}
helen
$echo${B[0]}
max
Youcanapplythe${#name[*]}operatortoarrayvariables,returningthenumberofelementsinthearray:
$echo${#NAMES[*]}
4
Thesameoperator,whengiventheindexofanelementofanarrayinplaceof*,returnsthelengthofthe
element:
$echo${#NAMES[1]}
5
Youcanusesubscriptsontheleftsideofanassignmentstatementtoreplaceselectedelementsofthe
array:
$NAMES[1]=alex
$echo${NAMES[*]}
maxalexsamzach
LocalityofVariables
Bydefaultvariablesarelocaltotheprocessinwhichtheyaredeclared.Thusashellscriptdoesnothave
accesstovariablesdeclaredinyourloginshellunlessyouexplicitlymakethevariablesavailable
(global).Underbash,exportmakesavariableavailabletochildprocesses.Undertcsh,setenv
(page356)assignsavaluetoavariableandmakesitavailabletochildprocesses.Theexamplesinthis
sectionusethebashsyntaxbutthetheoryappliestobothshells.
Onceyouusetheexportbuiltinwithavariablenameasanargument,theshellplacesthevalueofthe
variableinthecallingenvironmentofchildprocesses.Thiscallbyvaluegiveseachchildprocessacopy
ofthevariableforitsownuse.
Thefollowingextest1shellscriptassignsavalueofamericantothevariablenamedcheeseandthen
displaysitsfilename(extest1)andthevalueofcheese.Theextest1scriptthencallssubtest,which
attemptstodisplaythesameinformation.Nextsubtestdeclaresacheesevariableanddisplaysitsvalue.
Whensubtestfinishes,itreturnscontroltotheparentprocess,whichisexecutingextest1.Atthispoint
extest1againdisplaysthevalueoftheoriginalcheesevariable.
$catextest1
cheese=american
echo"extest11:$cheese"
subtest
echo"extest12:$cheese"
$catsubtest
echo"subtest1:$cheese"
cheese=swiss
echo"subtest2:$cheese"
$extest1
extest11:american
subtest1:
subtest2:swiss
extest12:american
Thesubtestscriptneverreceivesthevalueofcheesefromextest1,andextest1neverlosesthevalue.
Unlikeintherealworld,achildcanneveraffectitsparent'sattributes.Whenaprocessattemptsto
displaythevalueofavariablethathasnotbeendeclared,asisthecasewithsubtest,theprocess
displaysnothing;thevalueofanundeclaredvariableisthatofanullstring.
Thefollowingextest2scriptisthesameasextest1exceptthatitusesexporttomakecheese
availabletothesubtestscript:
$catextest2
exportcheese=american
echo"extest21:$cheese"
subtest
echo"extest22:$cheese"
$extest2
extest21:american
subtest1:american
subtest2:swiss
extest22:american
Herethechildprocessinheritsthevalueofcheeseasamericanand,afterdisplayingthisvalue,changes
itscopytoswiss.Whencontrolisreturnedtotheparent,theparent'scopyofcheeseretainsitsoriginal
value:american.
Anexportbuiltincanoptionallyincludeanassignment:
exportcheese=american
Theprecedingstatementisequivalenttothefollowingtwostatements:
cheese=american
exportcheese
Althoughitisrarelydone,youcanexportavariablebeforeyouassignavaluetoit.Youdonotneedto
exportanalready-exportedvariableasecondtimeafteryouchangeitsvalue.Forexample,youdonot
usuallyneedtoexportPATHwhenyouassignavaluetoitin~/.bash_profilebecauseitistypically
exportedinthe/etc/profileglobalstartupfile.
Functions
Becausefunctionsruninthesameenvironmentastheshellthatcallsthem,variablesareimplicitlyshared
byashellandafunctionitcalls.
$functionnam(){
>echo$myname
>myname=zach
>}
$myname=sam
$nam
sam
$echo$myname
zach
Intheprecedingexample,themynamevariableissettosamintheinteractiveshell.Thenthenam
functioniscalled.Itdisplaysthevalueofmynameithas(sam)andsetsmynametozach.Thefinal
echoshowsthat,intheinteractiveshell,thevalueofmynamehasbeenchangedtozach.
Functionlocalvariables
Localvariablesarehelpfulinafunctionwrittenforgeneraluse.Becausethefunctioniscalledbymany
scriptsthatmaybewrittenbydifferentprogrammers,youneedtomakesurethatthenamesofthe
variablesusedwithinthefunctiondonotinteractwithvariablesofthesamenameintheprogramsthat
callthefunction.Localvariableseliminatethisproblem.Whenusedwithinafunction,thetypeset
builtindeclaresavariabletobelocaltothefunctionitisdefinedin.
Thenextexampleshowstheuseofalocalvariableinafunction.Itusestwovariablesnamedcount.The
firstisdeclaredandassignedavalueof10intheinteractiveshell.Itsvalueneverchanges,asecho
verifiesaftercount_downisrun.Theothercountisdeclared,usingtypeset,tobelocaltothe
function.Itsvalue,whichisunknownoutsidethefunction,rangesfrom4to1,astheechocommand
withinthefunctionconfirms.
Theexampleshowsthefunctionbeingenteredfromthekeyboard;itisnotashellscript.(Seethetip"A
functionisnotashellscript"onpage471).
$functioncount_down(){
>typesetcount
>count=$1
>while[$count-gt0]
>do
>echo"$count..."
>((count=count-1))
>sleep1
>done
>echo"BlastOff."
>}
$count=10
$count_down4
4...
3...
2...
1...
BlastOff\!
$echo$count
10
The((count=count1))assignmentisenclosedbetweendoubleparentheses,whichcausetheshellto
performanarithmeticevaluation(page501).Withinthedoubleparenthesesyoucanreferenceshell
variableswithouttheleadingdollarsign($).
SpecialParameters
Specialparametersenableyoutoaccessusefulvaluespertainingtocommandlineargumentsandthe
executionofshellcommands.Youreferenceashellspecialparameterbyprecedingaspecialcharacter
withadollarsign($).Aswithpositionalparameters,itisnotpossibletomodifythevalueofaspecial
parameterbyassignment.
$$:PIDNumber
Theshellstoresinthe$$parameterthePIDnumberoftheprocessthatisexecutingit.Inthefollowing
interaction,echodisplaysthevalueofthisvariableandthepsutilityconfirmsitsvalue.Bothcommands
showthattheshellhasaPIDnumberof5209:
$echo$$
5209
$ps
PIDTTYTIMECMD
5209pts/100:00:00bash
6015pts/100:00:00ps
Becauseechoisbuiltintotheshell,theshelldoesnothavetocreateanotherprocesswhenyougivean
echocommand.However,theresultsarethesamewhetherechoisabuiltinornot,becausetheshell
substitutesthevalueof$$beforeitforksanewprocesstorunacommand.Tryusingtheechoutility
(/bin/echo),whichisrunbyanotherprocess,andseewhathappens.Inthefollowingexample,theshell
substitutesthevalueof$$andpassesthatvaluetocpasaprefixforafilename:
$echo$$
8232
$cpmemo$$.memo
$ls
8232.memomemo
IncorporatingaPIDnumberinafilenameisusefulforcreatinguniquefilenameswhenthemeaningsofthe
namesdonotmatter;itisoftenusedinshellscriptsforcreatingnamesoftemporaryfiles.Whentwo
peoplearerunningthesameshellscript,theseuniquefilenameskeepthemfrominadvertentlysharingthe
sametemporaryfile.
Thefollowingexampledemonstratesthattheshellcreatesanewshellprocesswhenitrunsashellscript.
Theid2scriptdisplaysthePIDnumberoftheprocessrunningit(nottheprocessthatcalleditthe
substitutionfor$$isperformedbytheshellthatisforkedtorunid2):
$catid2
echo"$0PID=$$"
$echo$$
8232
$id2
./id2PID=8362
$echo$$
8232
ThefirstechodisplaysthePIDnumberoftheinteractiveshell.Thenid2displaysitsname($0)andthe
PIDofthesubshellthatitisrunningin.ThelastechoshowsthatthePIDnumberoftheinteractiveshell
hasnotchanged.
$!
ThevalueofthePIDnumberofthelastprocessthatyouraninthebackgroundisstoredin$!(not
availableintcsh).Thefollowingexampleexecutessleepasabackgroundtaskandusesechoto
displaythevalueof$!:
$sleep60&
8376
$echo$!
8376
$?:ExitStatus
Whenaprocessstopsexecutingforanyreason,itreturnsanexitstatustotheparentprocess.Theexit
statusisalsoreferredtoasaconditioncodeorareturncode.The$?($statusundertcsh)variable
storestheexitstatusofthelastcommand.
Byconventionanonzeroexitstatusrepresentsafalsevalueandmeansthatthecommandfailed.Azerois
trueandindicatesthatthecommandwassuccessful.Inthefollowingexample,thefirstlscommand
succeedsandthesecondfails:
$lses
es
$echo$?
0
$lsxxx
ls:xxx:Nosuchfileordirectory
$echo$?
1
Youcanspecifytheexitstatusthatashellscriptreturnsbyusingtheexitbuiltin,followedbyanumber,
toterminatethescript.Ifyoudonotuseexitwithanumbertoterminateascript,theexitstatusofthe
scriptisthatofthelastcommandthescriptran.
$cates
echoThisprogramreturnsanexitstatusof7.
exit7
$es
Thisprogramreturnsanexitstatusof7.
$echo$?
7
$echo$?
0
Theesshellscriptdisplaysamessageandterminatesexecutionwithanexitcommandthatreturnsan
exitstatusof7,theuser-definedexitstatusinthisscript.Thefirstechothendisplaysthevalueoftheexit
statusofes.Thesecondechodisplaysthevalueoftheexitstatusofthefirstecho.Thevalueis0
becausethefirstechowassuccessful.
PositionalParameters
Thepositionalparameterscomprisethecommandnameandcommandlinearguments.Theyarecalled
positionalbecausewithinashellscript,yourefertothembytheirpositiononthecommandline.Onlythe
setbuiltin(page484)allowsyoutochangethevaluesofpositionalparameterswithoneexception:You
cannotchangethevalueofthecommandnamefromwithinascript.Thetcshsetbuiltindoesnot
changethevaluesofpositionalparameters.
$#:NumberofCommandLineArguments
The$#parameterholdsthenumberofargumentsonthecommandline(positionalparameters),not
countingthecommanditself:
$catnum_args
echo"Thisscriptwascalledwith$#arguments."
$num_argssammaxzach
Thisscriptwascalledwith3arguments.
$0:NameoftheCallingProgram
Theshellstoresthenameofthecommandyouusedtocallaprograminparameter$0.Thisparameteris
numberedzerobecauseitappearsbeforethefirstargumentonthecommandline:
$catabc
echo"Thecommandusedtorunthisscriptis$0"
$abc
Thecommandusedtorunthisscriptis./abc
$/home/sam/abc
Thecommandusedtorunthisscriptis/home/sam/abc
Theprecedingshellscriptusesechotoverifythenameofthescriptyouareexecuting.Youcanusethe
basenameutilityandcommandsubstitutiontoextractanddisplaythesimplefilenameofthecommand:
$catabc2
echo"Thecommandusedtorunthisscriptis$(basename$0)"
$/home/sam/abc2
Thecommandusedtorunthisscriptisabc2
$1$n:CommandLineArguments
Thefirstargumentonthecommandlineisrepresentedbyparameter$1,thesecondargumentby$2,and
soonupto$n.Forvaluesofnover9,thenumbermustbeenclosedwithinbraces.Forexample,the
twelfthcommandlineargumentisrepresentedby${12}.Thefollowingscriptdisplayspositional
parametersthatholdcommandlinearguments:
$catdisplay_5args
echoFirst5argumentsare$1$2$3$4$5
$display_5argsjennyalexhelen
First5argumentsarejennyalexhelen
Thedisplay_5argsscriptdisplaysthefirstfivecommandlinearguments.Theshellassignsanullvalueto
eachparameterthatrepresentsanargumentthatisnotpresentonthecommandline.Thusthe$4and$5
variableshavenullvaluesinthisexample.
$*
The$*variablerepresentsallthecommandlinearguments,asthedisplay_allprogramdemonstrates:
$catdisplay_all
echoAllargumentsare$*
$display_allabcdefghijklmnop
Allargumentsareabcdefghijklmnop
Enclosereferencestopositionalparametersbetweendoublequotationmarks.Thequotationmarksare
particularlyimportantwhenyouareusingpositionalparametersasargumentstocommands.Without
doublequotationmarks,apositionalparameterthatisnotsetorthathasanullvaluedisappears:
$catshowargs
echo"$0wascalledwith$#arguments,thefirstis:$1:."
$showargsabc
./showargswascalledwith3arguments,thefirstis:a:.
$echo$xx
$showargs$xxabc
./showargswascalledwith3arguments,thefirstis:a:.
$showargs"$xx"abc
./showargswascalledwith4arguments,thefirstis::.
Theshowargsscriptdisplaysthenumberofarguments($#)followedbythevalueofthefirstargument
enclosedbetweencolons.Theprecedingexamplefirstcallsshowargswiththreesimplearguments.Next
theechocommanddemonstratesthatthe$xxvariable,whichisnotset,hasanullvalue.Inthefinaltwo
callstoshowargs,thefirstargumentis$xx.Inthefirstcasethecommandlinebecomesshowargsabc;
theshellpassesshowargsthreearguments.Inthesecondcasethecommandlinebecomesshowargs""a
bc,whichresultsincallingshowargswithfourarguments.Thedifferenceinthetwocallstoshowargs
illustratesasubtlepotentialproblemthatyoushouldkeepinmindwhenusingpositionalparametersthat
maynotbesetorthatmayhaveanullvalue.
"$*"versus"$@"
The$*and$@parametersworkthesamewayexceptwhentheyareenclosedwithindoublequotation
marks.Using"$*"yieldsasingleargument(withSPACEsorthevalueofIFS[page288]betweenthe
positionalparameters),whereas"$@"producesalistwhereineachpositionalparameterisaseparate
argument.Thisdifferencetypicallymakes"$@"moreusefulthan"$*"inshellscripts.
Thefollowingscriptshelptoexplainthedifferencebetweenthesetwospecialparameters.Inthesecond
lineofbothscripts,thesinglequotationmarkskeeptheshellfrominterpretingtheenclosedspecial
characterssotheycanbedisplayedasthemselves.Thebb1scriptshowsthatset"$*"assignsmultiple
argumentstothefirstcommandlineparameter:
$catbb1
set"$*"
echo$#parameterswith'"$*"'
echo1:$1
echo2:$2
echo3:$3
$bb1abc
1parameterswith"$*"
1:abc
2:
3:
Thebb2scriptshowsthatset"$@"assignseachargumenttoadifferentcommandlineparameter:
$catbb2
set"$@"
echo$#parameterswith'"$@"'
echo1:$1
echo2:$2
echo3:$3
$
$bb2abc
3parameterswith"$@"
1:a
2:b
3:c
shift:PromotesCommandLineArguments
Theshiftbuiltinpromoteseachcommandlineargument.Thefirstargument(whichwas$1)is
discarded.Thesecondargument(whichwas$2)becomesthefirstargument(now$1),thethirdbecomes
thesecond,andsoon.Becauseno"unshift"commandexists,youcannotbringbackargumentsthathave
beendiscarded.Anoptionalargumenttoshiftspecifiesthenumberofpositionstoshift(andthe
numberofargumentstodiscard);thedefaultis1.
Thefollowingdemo_shiftscriptiscalledwiththreearguments.Doublequotationmarksaroundthe
argumentstoechopreservethespacingoftheoutput.Theprogramdisplaystheargumentsandshifts
themrepeatedlyuntiltherearenomoreargumentslefttoshift:
$catdemo_shift
echo"arg1=$1arg2=$2arg3=$3"
shift
echo"arg1=$1arg2=$2arg3=$3"
shift
echo"arg1=$1arg2=$2arg3=$3"
shift
echo"arg1=$1arg2=$2arg3=$3"
shift
$demo_shiftalicehelenjenny
arg1=alicearg2=helenarg3=jenny
arg1=helenarg2=jennyarg3=
arg1=jennyarg2=arg3=
arg1=arg2=arg3=
Repeatedlyusingshiftisaconvenientwaytoloopoverallthecommandlineargumentsinshell
scriptsthatexpectanarbitrarynumberofarguments.Seepage442forashellscriptthatusesshift.
set:InitializesCommandLineArguments
Whenyoucallthesetbuiltinwithoneormorearguments,itassignsthevaluesoftheargumentstothe
positionalparameters,startingwith$1(notavailableintcsh).Thefollowingscriptusessettoassign
valuestothepositionalparameters$1,$2,and$3:
$catset_it
setthisisit
echo$3$2$1
$set_it
itisthis
Combiningcommandsubstitution(page329)withthesetbuiltinisaconvenientwaytogetstandard
outputofacommandinaformthatcanbeeasilymanipulatedinashellscript.Thefollowingscriptshows
howtousedateandsettoprovidethedateinausefulformat.Thefirstcommandshowstheoutputof
date.Thencatdisplaysthecontentsofthedatesetscript.Thefirstcommandinthisscriptuses
commandsubstitutiontosetthepositionalparameterstotheoutputofthedateutility.Thenextcommand,
echo$*,displaysallpositionalparametersresultingfromthepreviousset.Subsequentcommands
displaythevaluesofparameters$1,$2,$3,and$4.Thefinalcommanddisplaysthedateinaformatyou
canuseinaletterorreport:
$date
WedJan523:39:18PST2005
$catdateset
set$(date)
echo$*
echo
echo"Argument1:$1"
echo"Argument2:$2"
echo"Argument3:$3"
echo"Argument6:$6"
echo

echo"$2$3,$6"
$dateset
WedJan523:39:25PST2005
Argument1:Wed
Argument2:Jan
Argument3:5
Argument6:2005
Jan5,2005
Youcanalsousethe+formatargumenttodate(page630)tomodifytheformatofitsoutput.
Whenusedwithoutanyarguments,setdisplaysalistoftheshellvariablesthatareset,includinguser-
createdvariablesandkeywordvariables.Underbash,thislististhesameasthatdisplayedby
declareandtypesetwhentheyarecalledwithoutanyarguments.
Thesetbuiltinalsoacceptsoptionsthatletyoucustomizethebehavioroftheshell(notavailablein
tcsh).Formoreinformationreferto"set±o:TurnsShellFeaturesOnandOff"onpage319.
ExpandingNullandUnsetVariables
Theexpression${name}(orjust$nameifitisnotambiguous)expandstothevalueofthenamevariable.
Ifnameisnullornotset,bashexpands${name}toanullstring.TheBourneAgainShellprovidesthe
followingalternativestoacceptingtheexpandednullstringasthevalueofthevariable:
Useadefaultvalueforthevariable.

Useadefaultvalueandassignthatvaluetothevariable.
Displayanerror.
Youcanchooseoneofthesealternativesbyusingamodifierwiththevariablename.Inaddition,youcan
usesetonounset(page321)tocausebashtodisplayanerrorandexitfromascriptwheneveranunset
variableisreferenced.
:UsesaDefaultValue
The:modifierusesadefaultvalueinplaceofanullorunsetvariablewhileallowinganonnullvariable
torepresentitself:
${name:default}
Theshellinterprets:as"Ifnameisnullorunset,expanddefaultandusetheexpandedvalueinplaceof
name;elseusename."ThefollowingcommandliststhecontentsofthedirectorynamedbytheLIT
variable.IfLITisnullorunset,itliststhecontentsof/home/alex/literature:
$ls${LIT:-/home/alex/literature}
Thedefaultcanitselfhavevariablereferencesthatareexpanded:
$ls${LIT:-$HOME/literature}
:=AssignsaDefaultValue
The:modifierdoesnotchangethevalueofavariable.Youmaywanttochangethevalueofanullor
unsetvariabletoitsdefaultinascript,however.Youcandosowiththe:=modifier:
${name:=default}
Theshellexpandstheexpression${name:=default}inthesamemannerasitexpands${name:default}
butalsosetsthevalueofnametotheexpandedvalueofdefault.Ifascriptcontainsalinesuchasthe
followingandLITisunsetornullatthetimethislineisexecuted,LITisassignedthevalue
/home/alex/literature:
$ls${LIT:=/home/alex/literature}
:builtin
Shellscriptsfrequentlystartwiththe:(colon)builtinfollowedonthesamelinebythe:=expansion
modifiertosetanyvariablesthatmaybenullorunset.The:builtinevaluateseachtokenintheremainder
ofthecommandlinebutdoesnotexecuteanycommands.Withouttheleadingcolon(:),theshellevaluates
andattemptstoexecutethe"command"thatresultsfromtheevaluation.
Usethefollowingsyntaxtosetadefaultforanullorunsetvariableinashellscript(thereisaSPACE
followingthefirstcolon):
:${name:=default}
WhenascriptneedsadirectoryfortemporaryfilesandusesthevalueofTEMPDIRforthenameofthis
directory,thefollowinglinemakesTEMPDIRdefaultto/tmp:
:${TEMPDIR:=/tmp}
:?DisplaysAnErrorMessage
Sometimesascriptneedsthevalueofavariablebutyoucannotsupplyareasonabledefaultatthetime
youwritethescript.Ifthevariableisnullorunset,the:?modifiercausesthescripttodisplayanerror
messageandterminatewithanexitstatusof1:
${name:?message}
YoumustquotemessageifitcontainsSPACEs.Ifyouomitmessage,theshelldisplaysthedefaulterror
message(parameternullornotset).Interactiveshellsdonotexitwhenyouuse:?.Inthefollowing
command,TESTDIRisnotsetsotheshelldisplaysonstandarderrortheexpandedvalueofthestring
following:?.Inthiscasethestringincludescommandsubstitutionfordate,withthe%Tformatbeing
followedbythestringerror,variablenotset.
cd${TESTDIR:?$(date+%T)error,variablenotset.}
bash:TESTDIR:16:16:14error,variablenotset.
BuiltinCommands
BuiltincommandswereintroducedinChapter5.Commandsthatarebuiltintoashelldonotforkanew
processwhenyouexecutethem.Thissectiondiscussesthetype,read,exec,trap,kill,and
getoptsbuiltinsandconcludeswithTable11-6onpage500,whichlistsmanybashbuiltins.See
Table9-10onpage377foralistoftcshbuiltins.
type:DisplaysInformationAboutaCommand
Thetypebuiltin(usewhichundertcsh)providesinformationaboutacommand:
$typecatechowhoiflt
catishashed(/bin/cat)
echoisashellbuiltin
whois/usr/bin/who
ifisashellkeyword
ltisaliasedto'ls-ltrh|tail'
Theprecedingoutputshowsthefilesthatwouldbeexecutedifyougavecatorwhoasacommand.
Becausecathasalreadybeencalledfromthecurrentshell,itisinthehashtable(page878)andtype
reportsthatcatishashed.Theoutputalsoshowsthatacalltoechorunstheechobuiltin,ifisa
keyword,andltisanalias.
read:AcceptsUserInput
Whenyoubeginwritingshellscripts,yousoonrealizethatoneofthemostcommontasksforuser-created
variablesisstoringinformationauserentersinresponsetoaprompt.Usingread,scriptscanaccept
inputfromtheuserandstorethatinputinvariables.Seepage361forinformationaboutreadinguserinput
undertcsh.Thereadbuiltinreadsonelinefromstandardinputandassignsthewordsonthelineto
oneormorevariables:
$catread1
echo-n"Goahead:"
readfirstline
echo"Youentered:$firstline"
$read1
Goahead:Thisisaline.
Youentered:Thisisaline.
Thefirstlineoftheread1scriptusesechotopromptyoutoenteralineoftext.Thenoptionsuppresses
thefollowingNEWLINE,allowingyoutoenteralineoftextonthesamelineastheprompt.Thesecond
linereadsthetextintothevariablefirstline.Thethirdlineverifiestheactionofreadbydisplayingthe
valueoffirstline.Thevariableisquoted(alongwiththetextstring)inthisexamplebecauseyou,asthe
scriptwriter,cannotanticipatewhichcharacterstheusermightenterinresponsetotheprompt.Consider
whatwouldhappenifthevariablewerenotquotedandtheuserentered*inresponsetotheprompt:
$catread1_no_quote
echo-n"Goahead:"
readfirstline
echoYouentered:$firstline
$read1_no_quote
Goahead:*
Youentered:read1read1_no_quotescript.1
$ls
read1read1_no_quotescript.1
Thelscommandliststhesamewordsasthescript,demonstratingthattheshellexpandstheasteriskinto
alistoffilesintheworkingdirectory.Whenthevariable$firstlineissurroundedbydoublequotation
marks,theshelldoesnotexpandtheasterisk.Thustheread1scriptbehavescorrectly:
$read1
Goahead:*
Youentered:*
Ifyouwanttheshelltointerpretthespecialmeaningsofspecialcharacters,donotusequotationmarks.
REPLY
Thereadbuiltinhasfeaturesthatcanmakeiteasiertouse.Whenyoudonotspecifyavariableto
receiveread'sinput,bashputstheinputintothevariablenamedREPLY.Youcanusethepoptionto
prompttheuserinsteadofusingaseparateechocommand.Thefollowingread1ascriptperforms
exactlythesametaskasread1:
$catread1a
read-p"Goahead:"
echo"Youentered:$REPLY"
Theread2scriptpromptsforacommandlineandreadstheuser'sresponseintothevariablecmd.The
scriptthenattemptstoexecutethecommandlinethatresultsfromtheexpansionofthecmdvariable:
$catread2
read-p"Enteracommand:"cmd
$cmd
echo"Thanks"
Inthefollowingexample,read2readsacommandlinethatcallstheechobuiltin.Theshellexecutesthe
commandandthendisplaysThanks.Nextread2readsacommandlinethatexecutesthewhoutility:
$read2
Enteracommand:echoPleasedisplaythismessage.
Pleasedisplaythismessage.
Thanks
$read2
Enteracommand:who
alexpts/4Jun1707:50(:0.0)
scottpts/12Jun1711:54(bravo.example.com)
Thanks
Ifcmddoesnotexpandintoavalidcommandline,theshellissuesanerrormessage:
$read2
Enteracommand:xxx
./read2:line2:xxx:commandnotfound
Thanks
Theread3scriptreadsvaluesintothreevariables.Thereadbuiltinassignsoneword(asequenceof
nonblankcharacters)toeachvariable:
$catread3
read-p"Entersomething:"word1word2word3
echo"Word1is:$word1"
echo"Word2is:$word2"
echo"Word3is:$word3"
$read3
Entersomething:thisissomething
Word1is:this
Word2is:is
Word3is:something
Whenyouentermorewordsthanreadhasvariables,readassignsonewordtoeachvariable,withall
leftoverwordsgoingtothelastvariable.Bothread1andread2assignedthefirstwordandallleftover
wordstotheonevariabletheyeachhadtoworkwith.Inthefollowingexample,readacceptsfive
wordsintothreevariables,assigningthefirstwordtothefirstvariable,thesecondwordtothesecond
variable,andthethirdthroughfifthwordstothethirdvariable:
$read3
Entersomething:thisissomethingelse,really.
Word1is:this
Word2is:is
Word3is:somethingelse,really.

Table11-4listssomeoftheoptionssupportedbythereadbuiltin.
Table11-4.readoptions
Option Function
aaname(array) Assignseachwordofinputtoanelementofarray
aname.
ddelim(delimiter) UsesdelimtoterminatetheinputinsteadofNEWLINE.
e(Readline) Ifinputiscomingfromakeyboard,usetheReadline
Library(page305)togetinput.
nnum(numberofcharacters)
Readsnumcharactersandreturns.Assoonastheuser
typesnumcharacters,readreturns;thereisnoneedto
pressRETURN.
pprompt(prompt)
Displayspromptonstandarderrorwithoutaterminating
NEWLINEbeforereadinginput.Displayspromptonly
wheninputcomesfromthekeyboard.
s(silent) Doesnotechocharacters.
un(filedescriptor)
Usestheintegernasthefiledescriptorthatreadtakes
itsinputfrom.
readu4arg1arg2
isequivalentto
readarg1arg2<&4
See"FileDescriptors"(page470)foradiscussionof
redirectionandfiledescriptors.
Thereadbuiltinreturnsanexitstatusof0ifitsuccessfullyreadsanydata.Ithasanonzeroexitstatus
whenitreachestheEOF(endoffile).Thefollowingexamplerunsawhileloopfromthecommandline.It
takesitsinputfromthenamesfileandterminatesafterreadingthelastlinefromnames.
$catnames
AliceJones
RobertSmith
AlicePaulson
JohnQ.Public
$whilereadfirstrest
>do
>echo$rest,$first
>done<names
Jones,Alice
Smith,Robert
Paulson,Alice
Q.Public,John
$
Theplacementoftheredirectionsymbol(<)forthewhilestructureiscritical.Itisimportantthatyou
placetheredirectionsymbolatthedonestatementandnotatthecalltoread.

optional
Eachtimeyouredirectinput,theshellopenstheinputfileandrepositionsthereadpointeratthestartofthefile:
$readline1<names;echo$line1;readline2<names;echo$line2
AliceJones
AliceJones
Hereeachreadopensnamesandstartsatthebeginningofthenamesfile.Inthefollowingexample,namesisopenedonce,as
standardinputofthesubshellcreatedbytheparentheses.Eachreadthenreadssuccessivelinesofstandardinput.
$(readline1;echo$line1;readline2;echo$line2)<names
AliceJones
RobertSmith
Anotherwaytogetthesameeffectistoopentheinputfilewithexecandholditopen(referto"FileDescriptors"onpage470):
$exec3<names
$read-u3line1;echo$line1;read-u3line2;echo$line2
AliceJones
RobertSmith
$exec3<&-
exec:ExecutesaCommand
Theexecbuiltin(notavailableintcsh)hastwoprimarypurposes:torunacommandwithoutcreating
anewprocessandtoredirectafiledescriptorincludingstandardinput,output,orerrorofashellscript
fromwithinthescript(page470).Whentheshellexecutesacommandthatisnotbuiltintotheshell,it
typicallycreatesanewprocess.Thenewprocessinheritsenvironment(globalorexported)variables
fromitsparentbutdoesnotinheritvariablesthatarenotexportedbytheparent.(Formoreinformation
referto"LocalityofVariables"onpage475.)Incontrast,execexecutesacommandinplaceof
(overlays)thecurrentprocess.
execversus.(dot)
Insofarasexecrunsacommandintheenvironmentoftheoriginalprocess,itissimilartothe.(dot)
command(page259).However,unlikethe.command,whichcanrunonlyshellscripts,execcanrun
bothscriptsandcompiledprograms.Also,whereasthe.commandreturnscontroltotheoriginalscript
whenitfinishesrunning,execdoesnot.Finally,the.commandgivesthenewprogramaccesstolocal
variables,whereasexecdoesnot.
execrunsacommand
Theexecbuiltinusedforrunningacommandhasthefollowingsyntax:
execcommandarguments
execdoesnotreturncontrol
Becausetheshelldoesnotcreateanewprocesswhenyouuseexec,thecommandrunsmorequickly.
However,becauseexecdoesnotreturncontroltotheoriginalprogram,itcanbeusedonlyasthelast
commandthatyouwanttoruninascript.Thefollowingscriptshowsthatcontrolisnotreturnedtothe
script:
$catexec_demo
who
execdate
echo"Thislineisneverdisplayed."
$exec_demo
jennypts/7May307:05(bravo.example.com)
hlspts/1May306:59(:0.0)
MonMay3011:42:56PDT2005
Thenextexample,amodifiedversionoftheoutscript(page442),usesexectoexecutethefinal
commandthescriptruns.Becauseoutrunseithercatorlessandthenterminates,thenewversion,
namedout2,usesexecwithbothcatandless:
$catout2
if[$#-eq0]
then
echo"Usage:out2[-v]filenames"1>&2
exit1
fi
if["$1"="-v"]
then
shift
execless"$@"
else
execcat--"$@"
fi
execredirectsinputandoutput
Thesecondmajoruseofexecistoredirectafiledescriptorincludingstandardinput,output,or
errorfromwithinascript.Thenextcommandcausesallsubsequentinputtoascriptthatwouldhavecome
fromstandardinputtocomefromthefilenamedinfile:
exec<infile
Similarlythefollowingcommandredirectsstandardoutputandstandarderrortooutfileanderrfile,
respectively:
exec>outfile2>errfile
Whenyouuseexecinthismanner,thecurrentprocessisnotreplacedwithanewprocess,andexec
canbefollowedbyothercommandsinthescript.
/dev/tty
Whenyouredirecttheoutputfromascripttoafile,youmustmakesurethattheuserseesanypromptsthe
scriptdisplays.The/dev/ttydeviceisapseudonymforthescreentheuserisworkingon;youcanusethis
devicetorefertotheuser'sscreenwithoutknowingwhichdeviceitis.(Thettyutilitydisplaysthename
ofthedeviceyouareusing.)Byredirectingtheoutputfromascriptto/dev/tty,youensurethatprompts
andmessagesgototheuser'sterminal,regardlessofwhichterminaltheuserisloggedinon.Messages
sentto/dev/ttyarealsonotdivertedifstandardoutputandstandarderrorfromthescriptareredirected.
Theto_screen1scriptsendsoutputtothreeplaces:standardoutput,standarderror,andtheuser'sscreen.
Whenitisrunwithstandardoutputandstandarderrorredirected,to_screen1stilldisplaysthemessage
sentto/dev/ttyontheuser'sscreen.Theoutanderrfilesholdtheoutputsenttostandardoutputand
standarderror.
$catto_screen1
echo"messagetostandardoutput"
echo"messagetostandarderror"1>&2
echo"messagetotheuser">/dev/tty
$to_screen1>out2>err
messagetotheuser
$catout
messagetostandardoutput
$caterr
messagetostandarderror
Thefollowingcommandredirectstheoutputfromascripttotheuser'sscreen:
exec>/dev/tty
Puttingthiscommandatthebeginningofthepreviousscriptchangeswheretheoutputgoes.In
to_screen2,execredirectsstandardoutputtotheuser'sscreensothe>/dev/ttyissuperfluous.
Followingtheexeccommand,alloutputsenttostandardoutputgoesto/dev/tty(thescreen).Outputto
standarderrorisnotaffected.
$catto_screen2
exec>/dev/tty
echo"messagetostandardoutput"
echo"messagetostandarderror"1>&2
echo"messagetotheuser">/dev/tty
$to_screen2>out2>err
messagetostandardoutput
messagetotheuser
Onedisadvantageofusingexectoredirecttheoutputto/dev/ttyisthatallsubsequentoutputis
redirectedunlessyouuseexecagaininthescript.
Youcanalsoredirecttheinputtoread(standardinput)sothatitcomesfrom/dev/tty(thekeyboard):
readname</dev/tty
or
exec</dev/tty
trap:CatchesaSignal
Asignalisareporttoaprocessaboutacondition.Linuxusessignalstoreportinterruptsgeneratedbythe
user(forexample,pressingtheinterruptkey)aswellasbadsystemcalls,brokenpipes,illegal
instructions,andotherconditions.TheTRapbuiltin(tcshusesonintr)catches,ortraps,oneormore
signals,allowingyoutodirecttheactionsascripttakeswhenitreceivesaspecifiedsignal.
Thisdiscussioncoverssixsignalsthataresignificantwhenyouworkwithshellscripts.Table11-5lists
thesesignals,thesignalnumbersthatsystemsoftenascribetothem,andtheconditionsthatusually
generateeachsignal.Givethecommandkilll,trapl,orman7signalforalistofsignalnames.
Whenittrapsasignal,ascripttakeswhateveractionyouspecify:Itcanremovefilesorfinishanyother
processingasneeded,displayamessage,terminateexecutionimmediately,orignorethesignal.Ifyoudo
notusetrapinascript,anyofthesixactualsignalslistedinTable11-5(notEXIT,DEBUG,orERR)
terminatesthescript.BecauseaprocesscannottrapaKILLsignal,youcanusekillKILL(orkill9)asa
lastresorttoterminateascriptoranyotherprocess.(Seepage497formoreinformationonkill.)
TheTRapcommandhasthefollowingsyntax:
trap['commands'][signal]
Theoptionalcommandspartspecifiesthecommandsthattheshellexecuteswhenitcatchesoneofthe
signalsspecifiedbysignal.Thesignalcanbeasignalnameornumberforexample,INTor2.If
commandsisnotpresent,trapresetsthetraptoitsinitialcondition,whichisusuallytoexitfromthe
script.
Thetrapbuiltindoesnotrequiresinglequotationmarksaroundcommandsasshowninthepreceding
syntax,butitisagoodpracticetousethem.Thesinglequotationmarkscauseshellvariableswithinthe
commandstobeexpandedwhenthesignaloccurs,notwhentheshellevaluatestheargumentstoTRap.
Evenifyoudonotuseanyshellvariablesinthecommands,youneedtoencloseanycommandthattakes
argumentswithineithersingleordoublequotationmarks.Quotingthecommandscausestheshelltopass
totraptheentirecommandasasingleargument.
Afterexecutingthecommands,theshellresumesexecutingthescriptwhereitleftoff.Ifyouwanttrap
topreventascriptfromexitingwhenitreceivesasignalbutnottorunanycommandsexplicitly,youcan
specifyanull(empty)commandsstring,asshowninthelockttyscript(page458).Thefollowing
commandtrapssignalnumber15afterwhichthescriptcontinues.
trap''15
ThefollowingscriptdemonstrateshowtheTRapbuiltincancatchtheterminalinterruptsignal(2).You
canuseSIGINT,INT,or2tospecifythissignal.Thescriptreturnsanexitstatusof1:
$catinter
#!/bin/bash
trap'echoPROGRAMINTERRUPTED;exit1'INT
whiletrue
do
echo"Programrunning."
sleep1
done
$inter
Programrunning.
Programrunning.
Programrunning.
CONTROL-C
PROGRAMINTERRUPTED
$
:(null)builtin
ThesecondlineofintersetsupatrapfortheterminalinterruptsignalusingINT.Whentrapcatchesthe
signal,theshellexecutesthetwocommandsbetweenthesinglequotationmarksinthetrapcommand.
TheechobuiltindisplaysthemessagePROGRAMINTERRUPTED,exitterminatestheshell
runningthescript,andtheparentshelldisplaysaprompt.Ifexitwerenotthere,theshellwouldreturn
controltothewhileloopafterdisplayingthemessage.Thewhilelooprepeatscontinuouslyuntilthescript
receivesasignalbecausethetrueutilityalwaysreturnsatrueexitstatus.Inplaceoftrueyoucanuse
the:(null)builtin,whichiswrittenasacolonandalwaysreturnsa0(true)status.
Thetrapbuiltinfrequentlyremovestemporaryfileswhenascriptisterminatedprematurelysothatthe
filesarenotlefttoclutterthefilesystem.Thefollowingshellscript,namedaddbanner,usestwotraps
toremoveatemporaryfilewhenthescriptterminatesnormallyorowingtoahangup,softwareinterrupt,
quit,orsoftwareterminationsignal:
$cataddbanner
#!/bin/bash
script=$(basename$0)
if[!-r"$HOME/banner"]
then
echo"$script:needreadable$HOME/bannerfile"1>&2
exit1
fi
trap'exit1'12315
trap'rm/tmp/$$.$script2>/dev/null'0
forfile
do
if[-r"$file"-a-w"$file"]
then
cat$HOME/banner$file>/tmp/$$.$script
cp/tmp/$$.$script$file
echo"$script:banneraddedto$file"1>&2
else
echo"$script:needreadandwritepermissionfor$file"
1>&2
fi
done
Whencalledwithoneormorefilenamearguments,addbannerloopsthroughthefiles,addingaheaderto
thetopofeach.Thisscriptisusefulwhenyouuseastandardformatatthetopofyourdocuments,suchas
astandardlayoutformemos,orwhenyouwanttoaddastandardheadertoshellscripts.Theheaderis
keptinafilenamed~/banner.BecauseaddbannerusestheHOMEvariable,whichcontainsthe
pathnameoftheuser'shomedirectory,thescriptcanbeusedbyseveraluserswithoutmodification.If
Alexhadwrittenthescriptwith/home/alexinplaceof$HOMEandthengiventhescripttoJenny,either
shewouldhavehadtochangeitoraddbannerwouldhaveusedAlex'sbannerfilewhenJennyranit
(assumingJennyhadreadpermissionforthefile).
Thefirsttrapinaddbannercausesittoexitwithastatusof1whenitreceivesahangup,software
interrupt(terminalinterruptorquitsignal),orsoftwareterminationsignal.ThesecondTRapusesa0in
placeofsignal-number,whichcausestraptoexecuteitscommandargumentwheneverthescriptexits
becauseitreceivesanexitcommandorreachesitsend.Togetherthesetrapsremoveatemporaryfile
whetherthescriptterminatesnormallyorprematurely.Standarderrorofthesecondtrapissentto
/dev/nullforcasesinwhichtrapattemptstoremoveanonexistenttemporaryfile.Inthosecasesrm
sendsanerrormessagetostandarderror;becausestandarderrorisredirected,theuserdoesnotseethis
message.
Seepage458foranotherexamplethatusesTRap.
kill:AbortsaProcess
Thekillbuiltinsendsasignaltoaprocessorjob.Thekillcommandhasthefollowingsyntax:
kill[signal]PID
wheresignalisthesignalnameornumber(forexample,INTor2)andPIDistheprocessidentification
numberoftheprocessthatistoreceivethesignal.Youcanspecifyajobnumber(page125)as%nin
placeofPID.Ifyouomitsignal,killsendsaTERM(softwaretermination,number15)signal.For
moreinformationonsignalnamesandnumbersseeTable11-5onpage494.
ThefollowingcommandsendstheTERMsignaltojobnumber1:
$kill-TERM%1
BecauseTERMisthedefaultsignalforkill,youcanalsogivethiscommandaskill%1.Givethe
commandkilll(lowercase"l")todisplayalistofsignalnames.
Aprogramthatisinterruptedoftenleavesmattersinanunpredictablestate:Temporaryfilesmaybeleft
behind(whentheyarenormallyremoved),andpermissionsmaybechanged.Awell-writtenapplication
traps,ordetects,signalsandcleansupbeforeexiting.MostcarefullywrittenapplicationstraptheINT,
QUIT,andTERMsignals.
Toterminateaprogram,firsttryINT(pressCONTROL-C,ifthejobisintheforeground).Becausean
applicationcanbewrittentoignorethesesignals,youmayneedtousetheKILLsignal,whichcannotbe
trappedorignored;itisa"surekill."Refertopage693formoreinformationonkill.Seealsothe
relatedutilitykillall(page695).
getopts:ParsesOptions
Thegetoptsbuiltin(notavailableintcsh)parsescommandlinearguments,therebymakingiteasier
towriteprogramsthatfollowtheLinuxargumentconventions.Thesyntaxforgetoptsis
getoptsoptstringvarname[arg...]
whereoptstringisalistofthevalidoptionletters,varnameisthevariablethatreceivestheoptionsone
atatime,andargistheoptionallistofparameterstobeprocessed.Ifargisnotpresent,getopts
processesthecommandlinearguments.Ifoptstringstartswithacolon(:),thescripttakescareof
generatingerrormessages;otherwise,getoptsgenerateserrormessages.
ThegetoptsbuiltinusestheOPTIND(optionindex)andOPTARG(optionargument)variablesto
storeoption-relatedvalues.Whenashellscriptstarts,thevalueofOPTINDis1.Eachtimegetopts
locatesanargument,itincrementsOPTINDtotheindexofthenextoptiontobeprocessed.Iftheoption
takesanargument,bashassignsthevalueoftheargumenttoOPTARG.
Toindicatethatanoptiontakesanargument,followthecorrespondingletterinoptstringwithacolon(:).
Theoptionstringdxo:lt:rindicatesthatgetoptsshouldsearchford,x,o,l,t,androptionsandthat
theoandtoptionstakearguments.
Usinggetoptsasthetest-commandinawhilecontrolstructureallowsyoutoloopovertheoptions
oneatatime.Thegetoptsbuiltincheckstheoptionlistforoptionsthatareinoptstring.Eachtime
throughtheloop,getoptsstorestheoptionletteritfindsinvarname.
Supposethatyouwanttowriteaprogramthatcantakethreeoptions:
1. Aboptionindicatesthattheprogramshouldignorewhitespaceatthestartofinputlines.
2. Atoptionfollowedbythenameofadirectoryindicatesthattheprogramshouldusethatdirectory
fortemporaryfiles.Otherwise,itshoulduse/tmp.
3. Auoptionindicatesthattheprogramshouldtranslateallitsoutputtouppercase.
Inaddition,theprogramshouldignoreallotheroptionsandendoptionprocessingwhenitencounterstwo
hyphens().
Theproblemistowritetheportionoftheprogramthatdetermineswhichoptionstheuserhassupplied.
Thefollowingsolutiondoesnotusegetopts:
SKIPBLANKS=
TMPDIR=/tmp
CASE=lower
while[["$1"=-*]]#[[=]]doespatternmatch
do
case$1in
-b)SKIPBLANKS=TRUE;;
-t)if[-d"$2"]
then
TMPDIR=$2
shift
else
echo"$0:-ttakesadirectoryargument.">&2
exit1
fi;;
-u)CASE=upper;;
--)break;;#Stopprocessingoptions
*)echo"$0:Invalidoption$1ignored.">&2;;
esac
shift
done
Thisprogramfragmentusesalooptocheckandshiftargumentswhiletheargumentisnot.Aslongas
theargumentisnottwohyphens,theprogramcontinuestoloopthroughacasestatementthatchecksfor
possibleoptions.Thecaselabelbreaksoutofthewhileloop.The*caselabelrecognizesanyoption;it
appearsasthelastcaselabeltocatchanyunknownoptions,displaysanerrormessage,andallows
processingtocontinue.Oneachpassthroughtheloop,theprogramdoesashifttogettothenext
argument.Ifanoptiontakesanargument,theprogramdoesanextrashifttogetpastthatargument.
Thefollowingprogramfragmentprocessesthesameoptions,butusesgetopts:
SKIPBLANKS=
TMPDIR=/tmp
CASE=lower
whilegetopts:bt:uarg
do
case$argin
b)SKIPBLANKS=TRUE;;
t)if[-d"$OPTARG"]
then
TMPDIR=$OPTARG
else
echo"$0:$OPTARGisnotadirectory.">&2
exit1
fi;;
u)CASE=upper;;
:)echo"$0:Mustsupplyanargumentto-$OPTARG.">&2
exit1;;
\?)echo"Invalidoption-$OPTARGignored.">&2;;
esac
done
Inthisversionofthecode,thewhilestructureevaluatesthegetoptsbuiltineachtimeitcomestothe
topoftheloop.ThegetoptsbuiltinusestheOPTINDvariabletokeeptrackoftheindexofthe
argumentitistoprocessthenexttimeitiscalled.Thereisnoneedtocallshiftinthisexample.
Inthegetoptsversionofthescriptthecasepatternsdonotstartwithahyphenbecausethevalueof
argisjusttheoptionletter(getoptsstripsoffthehyphen).Also,getoptsrecognizesastheendof
theoptions,soyoudonothavetospecifyitexplicitlyasinthecasestatementinthefirstexample.
Becauseyoutellgetoptswhichoptionsarevalidandwhichrequirearguments,itcandetecterrorsin
thecommandlineandhandlethemintwoways.Thisexampleusesaleadingcoloninoptstringtospecify
thatyoucheckforandhandleerrorsinyourcode;whengetoptsfindsaninvalidoption,itsets
varnameto?andOPTARGtotheoptionletter.Whenitfindsanoptionthatismissinganargument,
getoptssetsvarnameto:andOPTARGtotheoptionlackinganargument.
The\?casepatternspecifiestheactiontotakewhengetoptsdetectsaninvalidoption.The:case
patternspecifiestheactiontotakewhengetoptsdetectsamissingoptionargument.Inbothcases
getoptsdoesnotwriteanyerrormessage;itleavesthattasktoyou.
Ifyouomittheleadingcolonfromoptstring,bothaninvalidoptionandamissingoptionargumentcause
varnametobeassignedthestring?.OPTARGisnotsetandgetoptswritesitsowndiagnostic
messagetostandarderror.Generallythismethodislessdesirablebecauseyouhavelesscontrolover
whattheuserseeswhenanerrorismade.
Usinggetoptswillnotnecessarilymakeyourprogramsshorter.Itsprincipaladvantagesarethatit
providesauniformprogramminginterfaceanditenforcesstandardoptionhandling.
APartialListofBuiltins
Table11-6listssomeofthebashbuiltins.See"Listingbashbuiltins"onpage133forinstructionson
howtodisplaycompletelistsofbuiltins.

Expressions
Anexpressioniscomposedofconstants,variables,andoperatorsthatcanbeprocessedtoreturnavalue.
Thissectioncoversarithmetic,logical,andconditionalexpressionsaswellasoperators.Table11-8on
page505liststhebashoperators.
Table11-8.Operators
Typeofoperator/operator Function
Post
var++
var
Postincrement
Postdecrement
Pre
++var
var
Preincrement
Predecrement
Unary
Unaryminus
+Unaryplus
Negation
!BooleanNOT(logicalnegation)
~Complement(bitwisenegation)
Exponentiation
** Exponent
Multiplication,
division,remainder
*Multiplication
/Division
%Remainder

Addition,subtraction
Subtraction
+Addition
Bitwiseshifts
<< Leftbitwiseshift
>> Rightbitwiseshift
Comparison
<= Lessthanorequal
>= Greaterthanorequal
<Lessthan
>Greaterthan
Equality,inequality
== Equality
!= Inequality
Bitwise
&BitwiseAND
^BitwiseXOR(exclusiveOR)
|BitwiseOR
Boolean(logical)
&& BooleanAND
|| BooleanOR
Conditionalevaluation
?: Ternaryoperator

Assignment
=,*=,/=,%=,+=,=,
<<=,>>=,&=,^=,|=
Assignment
Comma
, Comma
ArithmeticEvaluation
TheBourneAgainShellcanperformarithmeticassignmentsandevaluatemanydifferenttypesof
arithmeticexpressions,allusingintegers.Theshellperformsarithmeticassignmentsinanumberofways.
Oneiswithargumentstotheletbuiltin:
$let"VALUE=VALUE*10+NEW"
Intheprecedingexample,thevariablesVALUEandNEWcontainintegervalues.Withinaletstatement
youdonotneedtousedollarsigns($)infrontofvariablenames.Doublequotationmarksmustenclosea
singleargument,orexpression,thatcontainsSPACEs.BecausemostexpressionscontainSPACEsand
needtobequoted,bashaccepts((expression))asasynonymforlet"expression",obviatingtheneed
forbothquotationmarksanddollarsigns:
$((VALUE=VALUE*10+NEW))
YoucanuseeitherformwhereveracommandisallowedandcanremovetheSPACEsifyoulike.Inthe
followingexample,theasterisk(*)doesnotneedtobequotedbecausetheshelldoesnotperform
pathnameexpansionontherightsideofanassignment(page280):
$letVALUE=VALUE*10+NEW
Becauseeachargumenttoletisevaluatedasaseparateexpression,youcanassignvaluestomorethan
onevariableonasingleline:
$let"COUNT=COUNT+1"VALUE=VALUE*10+NEW
Youneedtousecommastoseparatemultipleassignmentswithinasetofdoubleparentheses:
$((COUNT=COUNT+1,VALUE=VALUE*10+NEW))
tip:Arithmeticevaluationversusarithmeticexpansion
Arithmeticevaluationdiffersfromarithmeticexpansion.Asexplainedonpage327,
arithmeticexpansionusesthesyntax$((expression)),evaluatesexpression,andreplaces
$((expression))withtheresult.Youcanusearithmeticexpansiontodisplaythevalueofan
expressionortoassignthatvaluetoavariable.
Arithmeticevaluationusestheletexpressionor((expression))syntax,evaluates
expression,andreturnsastatuscode.Youcanusearithmeticevaluationtoperforma
logicalcomparisonoranassignment.
Logicalexpressions
Youcanusethe((expression))syntaxforlogicalexpressions,althoughthattaskisfrequentlyleftto
[[expression]].Thenextexampleexpandstheage_checkscript(page327)toincludelogicalarithmetic
evaluationinadditiontoarithmeticexpansion:
$catage2
#!/bin/bash
echo-n"Howoldareyou?"
readage
if((30<age&&age<60));then
echo"Wow,in$((60-age))years,you'llbe60!"
else
echo"Youaretooyoungortoooldtoplay."
fi
$age2
Howoldareyou?25
Youaretooyoungortoooldtoplay.
Thetest-statementfortheifstructureevaluatestwologicalcomparisonsjoinedbyaBooleanANDand
returns0(true)iftheyarebothtrueor1(false)otherwise.
LogicalEvaluation(ConditionalExpressions)
Thesyntaxofaconditionalexpressionis
[[expression]]
whereexpressionisaBoolean(logical)expression.Youmustprecedeavariablenamewithadollarsign
($)withinexpression.Theresultofexecutingthisbuiltin,likethetestbuiltin,isareturnstatus.The
conditionsallowedwithinthebracketsarealmostasupersetofthoseacceptedbytest(page794).
WherethetestbuiltinusesaasaBooleanANDoperator,[[expression]]uses&&.Similarly,where
testusesoasaBooleanORoperator,[[expression]]uses||.
Youcanreplacethelinethattestsageintheage2script(preceding)withthefollowingconditional
expression.Youmustsurroundthe[[and]]tokenswithwhitespaceoracommandterminator,andplace
dollarsignsbeforethevariables:
if[[30<$age&&$age<60]];then
Youcanalsousetest'srelationaloperatorsgt,ge,lt,le,eq,andne:
if[[30-lt$age&&$age-lt60]];then
Stringcomparisons
Thetestbuiltintestswhetherstringsareequalorunequal.The[[expression]]syntaxadds
comparisontestsforstringoperators.The>and<operatorscomparestringsfororder(forexample,
"aa"<"bbb").The=operatortestsforpatternmatch,notjustequality:[[string=pattern]]istrueif
stringmatchespattern.Thisoperatorisnotsymmetrical;thepatternmustappearontherightsideofthe
equalsign.Forexample,[[artist=a*]]istrue(=0),whereas[[a*=artist]]isfalse(=1):
$[[artist=a*]]
$echo$?
0
$[[a*=artist]]
$echo$?
1
Thenextexampleusesacommandlistthatstartswithacompoundcondition.Theconditionteststhatthe
directorybinandthefilesrc/myscript.bashexist.Ifthisistrue,cpcopiessrc/myscript.bashto
bin/myscript.Ifthecopysucceeds,chmodmakesmyscriptexecutable.Ifanyofthesestepsfails,echo
displaysamessage.
$[[-dbin&&-fsrc/myscript.bash]]&&cpsrc/myscript.bash\
bin/myscript&&chmod+xbin/myscript||echo"Cannotmake\
executableversionofmyscript"

StringPatternMatching
TheBourneAgainShellprovidesstringpattern-matchingoperatorsthatcanmanipulatepathnamesand
otherstrings.Theseoperatorscandeletefromstringsprefixesorsuffixesthatmatchpatterns.Thefour
operatorsarelistedinTable11-7.
Table11-7.Stringoperators
Operator Function
#Removesminimalmatchingprefixes
## Removesmaximalmatchingprefixes
%Removesminimalmatchingsuffixes
%% Removesmaximalmatchingsuffixes
Thesyntaxfortheseoperatorsis
${varnameoppattern}
whereopisoneoftheoperatorslistedinTable11-7andpatternisamatchpatternsimilartothatused
forfilenamegeneration.Theseoperatorsarecommonlyusedtomanipulatepathnamessoastoextractor
removecomponentsortochangesuffixes:
$SOURCEFILE=/usr/local/src/prog.c
$echo${SOURCEFILE#/*/}
local/src/prog.c
$echo${SOURCEFILE##/*/}
prog.c
$echo${SOURCEFILE%/*}
/usr/local/src
$echo${SOURCEFILE%%/*}
$echo${SOURCEFILE%.c}
/usr/local/src/prog
$CHOPFIRST=${SOURCEFILE#/*/}
$echo$CHOPFIRST
local/src/prog.c
$NEXT=${CHOPFIRST%%/*}
$echo$NEXT
local
Herethestring-lengthoperator,${#name},isreplacedbythenumberofcharactersinthevalueofname:
$echo$SOURCEFILE
/usr/local/src/prog.c
$echo${#SOURCEFILE}
21
Operators
Arithmeticexpansionandarithmeticevaluationusethesamesyntax,precedence,andassociativityof
expressionsastheClanguage.Table11-8listsoperatorsinorderofdecreasingprecedence(priorityof
evaluation);eachgroupofoperatorshasequalprecedence.Withinanexpressionyoucanuseparentheses
tochangetheorderofevaluation.
Pipe
Thepipetokenhashigherprecedencethanoperators.Youcanusepipesanywhereinacommandthatyou
canusesimplecommands.Forexample,thecommandline
$cmd1|cmd2||cmd3|cmd4&&cmd5|cmd6
isinterpretedasifyouhadtyped
$((cmd1|cmd2)||(cmd3|cmd4))&&(cmd5|cmd6)
tip:Donotrelyonrulesofprecedence:useparentheses
Donotrelyontheprecedenceruleswhenyouusecompoundcommands.Instead,use
parenthesestoexplicitlystatetheorderinwhichyouwanttheshelltointerpretthe
commands.
Incrementanddecrementoperators
Thepostincrement,postdecrement,preincrement,andpredecrementoperatorsworkwithvariables.The
pre-operators,whichappearinfrontofthevariablenameasin++COUNTandVALUE,firstchangethe
valueofthevariable(++adds1;subtracts1)andthenprovidetheresultforuseintheexpression.The
post-operatorsappearafterthevariablenameasinCOUNT++andVALUE;theyfirstprovidethe
unchangedvalueofthevariableforuseintheexpressionandthenchangethevalueofthevariable.
$N=10
$echo$N
10
$echo$((--N+3))
12
$echo$N
9
$echo$((N++-3))
6
$echo$N
10
Remainder
Theremainderoperator(%)givestheremainderwhenitsfirstoperandisdividedbyitssecond.For
example,theexpression$((15%7))hasthevalue1.
Boolean
TheresultofaBooleanoperationiseither0(false)or1(true).
The&&(AND)and||(OR)Booleanoperatorsarecalledshort-circuitingoperators.Iftheresultofusing
oneoftheseoperatorscanbedecidedbylookingonlyattheleftoperand,therightoperandisnot
evaluated.The&&operatorcausestheshelltotesttheexitstatusofthecommandprecedingit.Ifthe
commandsucceeded,bashexecutesthenextcommand;otherwise,itskipstheremainingcommandson
thecommandline.Youcanusethisconstructtoexecutecommandsconditionally:
$mkdirbkup&&cp-rsrcbkup
Thiscompoundcommandcreatesthedirectorybkup.Ifmkdirsucceeds,thecontentsofdirectorysrcis
copiedrecursivelytobkup.
The||separatoralsocausesbashtotesttheexitstatusofthefirstcommandbuthastheoppositeeffect:
Theremainingcommand(s)areexecutedonlyifthefirstonefailed(thatis,exitedwithnonzerostatus):
$mkdirbkup||echo"mkdirofbkupfailed">>/tmp/log
Theexitstatusofacommandlististheexitstatusofthelastcommandinthelist.Youcangrouplistswith
parentheses.Forexample,youcouldcombinetheprevioustwoexamplesas
$(mkdirbkup&&cp-rsrcbkup)||echo"mkdirfailed">>/tmp/log
Intheabsenceofparentheses,&&and||haveequalprecedenceandaregroupedfromlefttoright.The
followingexamplesusethetrueandfalseutilities.Theseutilitiesdonothingandreturntrue(0)and
false(1)exitstatuses,respectively:
$false;echo$?
1
The$?variableholdstheexitstatusoftheprecedingcommand(page479).Thenexttwocommandsyield
anexitstatusof1(false):
$true||false&&false
$echo$?
1
$(true||false)&&false
$echo$?
1
Similarlythenexttwocommandsyieldanexitstatusof0(true):
$false&&false||true
$echo$?
0
$(false&&false)||true
$echo$?
0
Because||and&&haveequalprecedence,theparenthesesinthetwoprecedingpairsofexamplesdo
nothingtochangetheorderofoperations.
Becausetheexpressionontherightsideofashort-circuitingoperatormaynevergetexecuted,youmust
becarefulwithassignmentstatementsinthatlocation.Thefollowingexampledemonstrateswhatcan
happen:
$((N=10,Z=0))
$echo$((N||((Z+=1))))
1
$echo$Z
0
BecausethevalueofNisnonzero,theresultofthe||(OR)operationis1(true),nomatterwhatthevalue
oftherightsideis.Asaconsequence((Z+=1))isneverevaluatedandZisnotincremented.
Ternary
Theternaryoperator,?:,decideswhichoftwoexpressionsshouldbeevaluated,basedonthevalue
returnedfromathirdexpression:
expression1?expression2:expression3
Ifexpression1producesafalse(0)value,expression3isevaluated;otherwise,expression2is
evaluated.Thevalueoftheentireexpressionisthevalueofexpression2orexpression3,dependingon
whichoneisevaluated.Ifexpression1istrue,expression3isnotevaluated.Ifexpression1isfalse
expression2isnotevaluated:
$((N=10,Z=0,COUNT=1))
$((T=N>COUNT?++Z:--Z))
$echo$T
1
$echo$Z
1
Assignment
Theassignmentoperators,suchas+=,areshorthandnotations.Forexample,N+=3isthesameas
((N=N+3)).
Otherbases
Thefollowingcommandsusethesyntaxbase#ntoassignbase2(binary)values.Firstv1isassigneda
valueof0101(5decimal)andv2isassignedavalueof0110(6decimal).Theechoutilityverifiesthe
decimalvalues.
$((v1=2#0101))
$((v2=2#0110))
$echo"$v1and$v2"
5and6
NextthebitwiseANDoperator(&)selectsthebitsthatareoninboth5(0101binary)and6(0110
binary).Theresultisbinary0100,whichis4decimal.
$echo$((v1&v2))
4
TheBooleanANDoperator(&&)producesaresultof1ifbothofitsoperandsarenonzeroandaresult
of0otherwise.ThebitwiseinclusiveORoperator(|)selectsthebitsthatareonineither0101or0110,
resultingin0111,whichis7decimal.TheBooleanORoperator(||)producesaresultof1ifeitherofits
operandsisnonzeroandaresultof0otherwise.
$echo$((v1&&v2))
1
$echo$((v1|v2))
7
$echo$((v1||v2))
1
NextthebitwiseexclusiveORoperator(^)selectsthebitsthatareonineither,butnotboth,ofthe
operands0101and0110,yielding0011,whichis3decimal.TheBooleanNOToperator(!)producesa
resultof1ifitsoperandis0andaresultof0otherwise.Becausetheexclamationpointin$((!v1))is
enclosedwithindoubleparentheses,itdoesnotneedtobeescapedtopreventtheshellfrominterpreting
theexclamationpointasahistoryevent.Thecomparisonoperatorsproducearesultof1ifthe
comparisonistrueandaresultof0otherwise.
$echo$((v1^v2))
3
$echo$((!v1))
0
$echo$((v1<v2))
1
$echo$((v1>v2))
0

ShellPrograms
TheBourneAgainShellhasmanyfeaturesthatmakeitagoodprogramminglanguage.Thestructuresthat
bashprovidesarenotarandomassortment.Rather,theyhavebeenchosentoprovidemostofthe
structuralfeaturesthatareinotherprocedurallanguages,suchasCorPascal.Aprocedurallanguage
providestheabilityto
Declare,assign,andmanipulatevariablesandconstantdata.TheBourneAgainShellprovidesstring
variables,togetherwithpowerfulstringoperators,andintegervariables,alongwithacompleteset
ofarithmeticoperators.
Breaklargeproblemsintosmallonesbycreatingsubprograms.TheBourneAgainShellallowsyou
tocreatefunctionsandcallscriptsfromotherscripts.Shellfunctionscanbecalledrecursively;that
is,aBourneAgainShellfunctioncancallitself.Youmaynotneedtouserecursionoften,butitmay
allowyoutosolvesomeapparentlydifficultproblemswithease.
Executestatementsconditionally,usingstatementssuchasif.
Executestatementsiteratively,usingstatementssuchaswhileandfor.
Transferdatatoandfromtheprogram,communicatingwithbothdatafilesandusers.
Programminglanguagesimplementthesecapabilitiesindifferentwaysbutwiththesameideasinmind.
Whenyouwanttosolveaproblembywritingaprogram,youmustfirstfigureoutaprocedurethatleads
youtoasolutionthatis,analgorithm.Typicallyyoucanimplementthesamealgorithminroughlythe
samewayindifferentprogramminglanguages,usingthesamekindsofconstructsineachlanguage.
Chapter8andthischapterhaveintroducednumerousbashfeatures,manyofwhichareusefulfor
interactiveuseaswellasforshellprogramming.Thissectiondevelopstwocompleteshellprograms,
demonstratinghowtocombinesomeofthesefeatureseffectively.Theprogramsarepresentedas
problemsforyoutosolvealongwithsamplesolutions.
ARecursiveShellScript
Arecursiveconstructisonethatisdefinedintermsofitself.Alternatively,youmightsaythatarecursive
programisonethatcancallitself.Thismayseemcircular,butitneednotbe.Toavoidcircularitya
recursivedefinitionmusthaveaspecialcasethatisnotself-referential.Recursiveideasoccurin
everydaylife.Forexample,youcandefineanancestorasyourmother,yourfather,oroneoftheir
ancestors.Thisdefinitionisnotcircular;itspecifiesunambiguouslywhoyourancestorsare:yourmother
oryourfather,oryourmother'smotherorfatheroryourfather'smotherorfather,andsoon.
AnumberofLinuxsystemutilitiescanoperaterecursively.SeetheRoptiontothechmod(page604),
chown(page608),andcp(page616)utilitiesforexamples.
Solvethefollowingproblembyusingarecursiveshellfunction:
Writeashellfunctionnamedmakepaththat,givenapathname,createsallcomponentsin
thatpathnameasdirectories.Forexample,thecommandmakepatha/b/c/dshouldcreate
directoriesa,a/b,a/b/c,anda/b/c/d.(Themkdirutilitysupportsapoptionthatdoes
exactlythis.Solvetheproblemwithoutusingmkdirp.)
Onealgorithmforarecursivesolutionfollows:
1. Examinethepathargument.Ifitisanullstringorifitnamesanexistingdirectory,donothingand
return.
2. Ifitisasimplepathcomponent,createit(usingmkdir)andreturn.
3. Otherwise,callmakepathusingthepathprefixoftheoriginalargument.Thisstepeventuallycreates
allthedirectoriesuptothelastcomponent,whichyoucanthencreatewithmkdir.
Ingeneral,arecursivefunctionmustinvokeitselfwithasimplerversionoftheproblemthanitwasgiven
untilitisfinallycalledwithasimplecasethatdoesnotneedtocallitself.Followingisonepossible
solutionbasedonthisalgorithm:
makepath
#thisisafunction
#enteritatthekeyboard,donotrunitasashellscript
#
functionmakepath()
{
if[[${#1}-eq0||-d"$1"]]
then
return0#Donothing
fi
if[["${1%/*}"="$1"]]
then
mkdir$1
return$?
fi
makepath${1%/*}||return1
mkdir$1
return$?
}
Inthetestforasimplecomponent(theifstatementinthemiddleofthefunction),theleftexpressionisthe
argumentaftertheshortestsuffixthatstartswitha/characterhasbeenstrippedaway(page504).Ifthere
isnosuchcharacter(forexample,if$1isalex),nothingisstrippedoffandthetwosidesareequal.Ifthe
argumentisasimplefilenameprecededbyaslash,suchas/usr,theexpression${1%/*}evaluatestoa
nullstring.Tomakethefunctionworkinthiscase,youmusttaketwoprecautions:Puttheleftexpression
withinquotationmarksandensurethattherecursivefunctionbehavessensiblywhenitispassedanull
stringasanargument.Ingeneral,goodprogramsarerobust:Theyshouldbepreparedforborderline,
invalid,ormeaninglessinputandbehaveappropriatelyinsuchcases.
Bygivingthefollowingcommandfromtheshellyouareworkingin,youturnondebuggingtracingsothat
youcanwatchtherecursionwork:
$set-oxtrace
(Givethesamecommand,butreplacethehyphenwithaplussign(+)toturndebuggingoff.)With
debuggingturnedon,theshelldisplayseachlineinitsexpandedformasitexecutestheline.A+precedes
eachlineofdebuggingoutput.Inthefollowingexample,thefirstlinethatstartswith+showstheshell
callingmakepath.Themakepathfunctioniscalledfromthecommandlinewithargumentsofa/b/c.
Subsequentlyitcallsitselfwithargumentsofa/bandfinallya.Alltheworkisdone(usingmkdir)as
eachcalltomakepathreturns.
$makepatha/b/c
+makepatha/b/c
+[[5-eq0]]
+[[-da/b/c]]
+[[a/b=\a\/\b\/\c]]
+makepatha/b
+[[3-eq0]]
+[[-da/b]]
+[[a=\a\/\b]]
+makepatha
+[[1-eq0]]
+[[-da]]
+[[a=\a]]
+mkdira
+return0
+mkdira/b
+return0
+mkdira/b/c
+return0
Thefunctionworksitswaydowntherecursivepathandbackupagain.
Itisinstructivetoinvokemakepathwithaninvalidpathandseewhathappens.Thefollowingexample,
runwithdebuggingturnedon,triestocreatethepath/a/b,whichrequiresthatyoucreatedirectoryainthe
rootdirectory.Unlessyouhavepermissiontowritetotherootdirectory,youarenotpermittedtocreate
thisdirectory.
$makepath/a/b
+makepath/a/b
+[[4-eq0]]
+[[-d/a/b]]
+[[/a=\/\a\/\b]]
+makepath/a
+[[2-eq0]]
+[[-d/a]]
+[[''=\/\a]]
+makepath
+[[0-eq0]]
+return0
+mkdir/a
mkdir:cannotcreatedirectory'/a':Permissiondenied
+return1
+return1
Therecursionstopswhenmakepathisdeniedpermissiontocreatethe/adirectory.Theerrorreturnis
passedallthewayback,sotheoriginalmakepathexitswithnonzerostatus.

tip:Uselocalvariableswithrecursivefunctions
Theprecedingexampleglossedoverapotentialproblemthatyoumayencounterwhenyou
usearecursivefunction.Duringtheexecutionofarecursivefunction,manyseparate
instancesofthatfunctionmaybeactivesimultaneously.Allbutoneofthemarewaitingfor
theirchildinvocationtocomplete.
Becausefunctionsruninthesameenvironmentastheshellthatcallsthem,variablesare
implicitlysharedbyashellandafunctionitcallssothatallinstancesofthefunctionshare
asinglecopyofeachvariable.Sharingvariablescangiverisetosideeffectsthatarerarely
whatyouwant.Asarule,youshouldusetypesettomakeallvariablesofarecursive
functionbelocalvariables.Seepage477formoreinformation.
ThequizShellScript
Solvethefollowingproblemusingabashscript:
Writeagenericmultiple-choicequizprogram.Theprogramshouldgetitsquestionsfrom
datafiles,presentthemtotheuser,andkeeptrackofthenumberofcorrectandincorrect
answers.Theusermustbeabletoexitfromtheprogramatanytimewithasummaryof
resultstothatpoint.
Thedetaileddesignofthisprogramandeventhedetaileddescriptionoftheproblemdependonanumber
ofchoices:Howwilltheprogramknowwhichsubjectsareavailableforquizzes?Howwilltheuser
chooseasubject?Howwilltheprogramknowwhenthequizisover?Shouldtheprogrampresentthe
samequestions(foragivensubject)inthesameordereachtime,orshoulditscramblethem?
Ofcourse,youcanmakemanyperfectlygoodchoicesthatimplementthespecificationoftheproblem.
Thefollowingdetailsnarrowtheproblemspecification:
Eachsubjectwillcorrespondtoasubdirectoryofamasterquizdirectory.Thisdirectorywillbe
namedintheenvironmentvariableQUIZDIR,whosedefaultwillbe/usr/games/quiz.Forexample,
youcouldhavethefollowingdirectoriescorrespondtothesubjectsengineering,art,andpolitics:
/usr/games/quiz/engineering,/usr/games/quiz/art,and/usr/games/quiz/politics.
Eachsubjectcanhaveseveralquestions.Eachquestionisrepresentedbyafileinitssubject's

directory.
Thefirstlineofeachfilethatrepresentsaquestionisthetextofthequestion.Ifittakesmorethan
oneline,youmustescapetheNEWLINEwithabackslash.(Thissetupmakesiteasytoreadasingle
questionwiththereadbuiltin.)Thesecondlineofthefileisanintegerthatspecifiesthenumberof
choices.Thenextlinesarethechoicesthemselves.Thelastlineisthecorrectanswer.Followingis
asamplequestionfile:
Whodiscoveredtheprincipleofthelever?
4
Euclid
Archimedes
ThomasEdison
TheLeverBrothers
Archimedes
Theprogrampresentsallthequestionsinasubjectdirectory.Atanypointtheusercaninterruptthe
quizwithCONTROL-C,whereupontheprogramwillsummarizetheresultssofarandexit.Ifthe
userdoesnotinterrupt,theprogramsummarizestheresultsandexitswhenithasaskedallquestions
forthechosensubject.
Theprogramscramblesthequestionsinasubjectbeforepresentingthem.
Followingisatop-leveldesignforthisprogram:
1.
Initialize.Thisinvolvesanumberofsteps,suchassettingthecountsofthenumberofquestionsasked
sofarandthenumberofcorrectandwronganswerstozero.SetsuptotrapCONTROL-C.
2. Presenttheuserwithachoiceofsubjectsandgettheuser'sresponse.
3. Changetothecorrespondingsubjectdirectory.
4.
Determinethequestionstobeasked(thatis,thefilenamesinthatdirectory).Arrangetheminrandom
order.
5. Repeatedlypresentquestionsandaskforanswersuntilthequizisoverorisinterruptedbytheuser.
6. Presenttheresultsandexit.
Clearlysomeofthesesteps(suchasstep3)aresimple,whereasothers(suchasstep4)arecomplexand
worthyofanalysisontheirown.Useshellfunctionsforanycomplexstep,andusethetrapbuiltinto
handleauserinterrupt.
Hereisaskeletonversionoftheprogramwithemptyshellfunctions:
functioninitialize
{
#Initializesvariables.
}
functionchoose_subj
{
#Writeschoicetostandardoutput.
}
functionscramble
{
#Storesnamesofquestionfiles,scrambled,
#inanarrayvariablenamedquestions.
}
functionask
{
#Readsaquestionfile,asksthequestion,andchecksthe
#answer.Returns1iftheanswerwascorrect,0otherwise.Ifit
#encountersaninvalidquestionfile,exitwithstatus2.
}
functionsummarize
{
#Presentstheuser'sscore.
}
#Mainprogram
initialize#Step1intop-leveldesign
subject=$(choose_subj)#Step2
[[$?-eq0]]||exit2#Ifnovalidchoice,exit
cd$subject||exit2#Step3
echo#Skipaline
scramble#Step4
forquesin${questions[*]};do#Step5
ask$ques
result=$?
((num_ques=num_ques+1))
if[[$result==1]];then
((num_correct+=1))
fi
echo#Skipalinebetweenquestions
sleep${QUIZDELAY:=1}
done
summarize#Step6
exit0
Tomakereadingtheresultsabiteasierfortheuser,asleepcallappearsinsidethequestionloop.It
delays$QUIZDELAYseconds(default=1)betweenquestions.
Nowthetaskistofillinthemissingpiecesoftheprogram.Inasensethisprogramisbeingwritten
backward.Thedetails(theshellfunctions)comefirstinthefilebutcomelastinthedevelopmentprocess.
Thiscommonprogrammingpracticeiscalledtop-downdesign.Intop-downdesignyoufillinthebroad
outlineoftheprogramfirstandsupplythedetailslater.Inthiswayyoubreaktheproblemupintosmaller
problems,eachofwhichyoucanworkonindependently.Shellfunctionsareagreathelpinusingthetop-
downapproach.
Onewaytowritetheinitializefunctionfollows.ThecdcommandcausesQUIZDIRtobetheworking
directoryfortherestofthescriptanddefaultsto/usr/games/quizifQUIZDIRisnotset.
functioninitialize()
{
trap'summarize;exit0'INT#Handleuserinterrupts
num_ques=0#Numberofquestionsaskedsofar
num_correct=0#Numberansweredcorrectlysofar
first_time=true#trueuntilfirstquestionis
asked
cd${QUIZDIR:=/usr/games/quiz}||exit2
}
Bepreparedforthecdcommandtofail.Thedirectorymaybeunsearchableorconceivablyanotheruser
mayhaveremovedit.Theprecedingfunctionexitswithastatuscodeof2ifcdfails.
Thenextfunction,choose_subj,isabitmorecomplicated.Itdisplaysamenuusingaselectstatement:
functionchoose_subj()
{
subjects=($(ls))
PS3="Chooseasubjectforthequizfromtheprecedinglist:"
selectSubjectin${subjects[*]};do
if[[-z"$Subject"]];then
echo"Nosubjectchosen.Bye.">&2
exit1
fi
echo$Subject
return0
done
}
Thefunctionfirstusesanlscommandandcommandsubstitutiontoputalistofsubjectdirectoriesinthe
subjectsarray.Nexttheselectstructure(page466)presentstheuserwithalistofsubjects(the
directoriesfoundbyls)andassignsthechosendirectorynametotheSubjectvariable.Finallythe
functionwritesthenameofthesubjectdirectorytostandardoutput.Themainprogramusescommand
substitutiontoassignthisvaluetothesubjectvariable[subject=$(choose_subj)].
Thescramblefunctionpresentsanumberofdifficulties.Inthissolutionitusesanarrayvariable
(questions)toholdthenamesofthequestions.ItscramblestheentriesinanarrayusingtheRANDOM
variable(eachtimeyoureferenceRANDOMithasthevalueofa[random]integerbetween0and
32767):
functionscramble()
{
typeset-iindexquescount
questions=($(ls))
quescount=${#questions[*]}#Numberofelements
((index=quescount-1))
while[[$index>0]];do
((target=RANDOM%index))
exchange$target$index
((index-=1))
done
}
Thisfunctioninitializesthearrayvariablequestionstothelistoffilenames(questions)intheworking
directory.Thevariablequescountissettothenumberofsuchfiles.Thenthefollowingalgorithmisused:
Letthevariableindexcountdownfromquescount1(theindexofthelastentryinthearrayvariable).
Foreachvalueofindex,thefunctionchoosesarandomvaluetargetbetween0andindex,inclusive.The
command
((target=RANDOM%index))
producesarandomvaluebetween0andindex1bytakingtheremainder(the%operator)when
$RANDOMisdividedbyindex.Thefunctionthenexchangestheelementsofquestionsatpositions
targetandindex.Itisconvenienttodothisinanotherfunctionnamedexchange:
functionexchange()
{
temp_value=${questions[$1]}
questions[$1]=${questions[$2]}
questions[$2]=$temp_value
}
Theaskfunctionalsousestheselectstructure.Itreadsthequestionfilenamedinitsargumentanduses
thecontentsofthatfiletopresentthequestion,accepttheanswer,anddeterminewhethertheansweris
correct.(Seethecodethatfollows.)
Theaskfunctionusesfiledescriptor3toreadsuccessivelinesfromthequestionfile,whosenamewas
passedasanargumentandisrepresentedby$1inthefunction.Itreadsthequestionintothequesvariable
andthenumberofquestionsintonum_opts.Thefunctionconstructsthevariablechoicesbyinitializingit
toanullstringandsuccessivelyappendingthenextchoice.ThenitsetsPS3tothevalueofquesanduses
aselectstructuretoprompttheuserwithques.Theselectstructureplacestheuser'sanswerinanswer,
andthefunctionthenchecksitagainstthecorrectanswerfromthefile.
Theconstructionofthechoicesvariableisdonewithaneyetowardavoidingapotentialproblem.
Supposethatoneanswerhassomewhitespaceinit.Thenitmightappearastwoormoreargumentsin
choices.Toavoidthisproblem,makesurethatchoicesisanarrayvariable.Theselectstatementdoesthe
restofthework:
quiz
$catquiz
#!/bin/bash
#removethe#onthefollowinglinetoturnondebugging
#set-oxtrace
#==================
functioninitialize()
{
trap'summarize;exit0'INT#Handleuserinterrupts
num_ques=0#Numberofquestionsaskedsofar
num_correct=0#Numberansweredcorrectlysofar
first_time=true#trueuntilfirstquestionis
asked
cd${QUIZDIR:=/usr/games/quiz}||exit2
}
#==================
functionchoose_subj()
{
subjects=($(ls))
PS3="Chooseasubjectforthequizfromtheprecedinglist:"
selectSubjectin${subjects[*]};do
if[[-z"$Subject"]];then
echo"Nosubjectchosen.Bye.">&2
exit1
fi
echo$Subject
return0
done
}
#==================
functionexchange()
{
temp_value=${questions[$1]}
questions[$1]=${questions[$2]}
questions[$2]=$temp_value
}
#==================
functionscramble()
{
typeset-iindexquescount
questions=($(ls))
quescount=${#questions[*]}#Numberofelements
((index=quescount-1))
while[[$index>0]];do
((target=RANDOM%index))
exchange$target$index
((index-=1))
done
}
#==================
functionask()
{
exec3<$1
read-u3ques||exit2
read-u3num_opts||exit2
index=0
choices=()
while((index<num_opts));do
read-u3next_choice||exit2
choices=("${choices[@]}""$next_choice")
((index+=1))
done
read-u3correct_answer||exit2
exec3<&-
if[[$first_time=true]];then
first_time=false
echo-e"Youmaypresstheinterruptkeyatanytimetoquit.\n"
fi
PS3=$ques""#Make$questhepromptforselect
#andaddsomespacesfor
legibility.
selectanswerin"${choices[@]}";do
if[[-z"$answer"]];then
echoNotavalidchoice.Pleasechooseagain.
elif[["$answer"="$correct_answer"]];then
echo"Correct!"
return1
else
echo"No,theansweris$correct_answer."
return0
fi
done
}
#==================
functionsummarize()
{
echo#Skipaline
if((num_ques==0));then
echo"Youdidnotansweranyquestions"
exit0
fi
((percent=num_correct*100/num_ques))
echo"Youanswered$num_correctquestionscorrectly,outof\
$num_questotalquestions."
echo"Yourscoreis$percentpercent."
}
#==================
#Mainprogram
initialize#Step1intop-leveldesign
subject=$(choose_subj)#Step2
[[$?-eq0]]||exit2#Ifnovalidchoice,exit
cd$subject||exit2#Step3
echo#Skipaline
scramble#Step4
forquesin${questions[*]};do#Step5
ask$ques
result=$?
((num_ques=num_ques+1))
if[[$result==1]];then
((num_correct+=1))
fi
echo#Skipalinebetweenquestions
sleep${QUIZDELAY:=1}
done
summarize#Step6
exit0
ChapterSummary
Theshellisaprogramminglanguage.Programswritteninthislanguagearecalledshellscripts,orsimply
scripts.Shellscriptsprovidethedecisionandloopingcontrolstructurespresentinhigh-level
programminglanguageswhileallowingeasyaccesstosystemutilitiesanduserprograms.Shellscripts
canusefunctionstomodularizeandsimplifycomplextasks.
Controlstructures
Thecontrolstructuresthatusedecisionstoselectalternativesareif...then,if...then...else,and
if...then...elif.Thecasecontrolstructureprovidesamultiwaybranchandcanbeusedwhenyouwantto
expressalternativesusingasimplepattern-matchingsyntax.
Theloopingcontrolstructuresarefor...in,for,until,andwhile.Thesestructuresperformoneormore
tasksrepetitively.
Thebreakandcontinuecontrolstructuresaltercontrolwithinloops:breaktransferscontroloutofa
loop,andcontinuetransferscontrolimmediatelytothetopofaloop.
TheHeredocumentallowsinputtoacommandinashellscripttocomefromwithinthescriptitself.
Filedescriptors
TheBourneAgainShellprovidestheabilitytomanipulatefiledescriptors.Coupledwiththereadand
echobuiltins,filedescriptorsallowshellscriptstohaveasmuchcontroloverinputandoutputas
programswritteninlower-levellanguages.
Variables
Youassignattributes,suchasreadonly,tobashvariablesusingthetypesetbuiltin.TheBourneAgain
Shellprovidesoperatorstoperformpatternmatchingonvariables,providedefaultvaluesforvariables,
andevaluatethelengthofvariables.Thisshellalsosupportsarrayvariablesandlocalvariablesfor
functionsandprovidesbuilt-inintegerarithmeticcapability,usingtheletbuiltinandanexpression
syntaxsimilartotheCprogramminglanguage.
Builtins
BourneAgainShellbuiltinsincludetype,read,exec,TRap,kill,andgetopts.Thetype
builtindisplaysinformationaboutacommand,includingitslocation;readallowsascripttoacceptuser
input.
Theexecbuiltinexecutesacommandwithoutcreatinganewprocess.Thenewcommandoverlaysthe
currentprocess,assumingthesameenvironmentandPIDnumberofthatprocess.Thisbuiltinexecutes
userprogramsandotherLinuxcommandswhenitisnotnecessarytoreturncontroltothecallingprocess.
TheTRapbuiltincatchesasignalsentbyLinuxtotheprocessrunningthescriptandallowsyouto
specifyactionstobetakenuponreceiptofoneormoresignals.Youcanusethisbuiltintocauseascript
toignorethesignalthatissentwhentheuserpressestheinterruptkey.
Thekillbuiltinallowsyoutoterminatearunningprogram.Thegetoptsbuiltinparsescommandline
arguments,makingiteasiertowriteprogramsthatfollowstandardLinuxconventionsforcommandline
argumentsandoptions.
Utilitiesinscripts
Inadditiontousingcontrolstructures,builtins,andfunctions,shellscriptsgenerallycallLinuxutilities.
Thefindutility,forinstance,iscommonplaceinshellscriptsthatsearchforfilesinthesystemhierarchy
andcanperformavastrangeoftasks,fromsimpletocomplex.
Awell-writtenshellscriptadherestostandardprogrammingpractices,suchasspecifyingtheshellto
executethescriptonthefirstlineofthescript,verifyingthenumberandtypeofargumentsthatthescript
iscalledwith,displayingastandardusagemessagetoreportcommandlineerrors,andredirectingall
informationalmessagestostandarderror.
Expressions
Therearetwobasictypesofexpressions:arithmeticandlogical.Arithmeticexpressionsallowyoutodo
arithmeticonconstantsandvariables,yieldinganumericresult.Logical(Boolean)expressionscompare
expressionsorstrings,ortestconditionstoyieldatrueorfalseresult.AswithalldecisionswithinLinux
shellscripts,atruestatusisrepresentedbythevaluezero;false,byanynonzerovalue.
Exercises
1.
RewritethejournalscriptofChapter8(question5,page335)byaddingcommandstoverifythattheuserhaswritepermissionfora
filenamedjournal-fileintheuser'shomedirectory,ifsuchafileexists.Thescriptshouldtakeappropriateactionsifjournal-fileexists
andtheuserdoesnothavewritepermissiontothefile.Verifythatthemodifiedscriptworks.
2. Thespecialparameter"$@"isreferencedtwiceintheoutscript(page442).Explainwhatwouldbedifferentiftheparameter"$*"were
usedinitsplace.
3. Writeafilterthattakesalistoffilesasinputandoutputsthebasename(page465)ofeachfileinthelist.
4.
1. Writeafunctionthattakesasinglefilenameasanargumentandaddsexecutepermissiontothefilefortheuser.
2. Whenmightsuchafunctionbeuseful?
3. Revisethescriptsothatittakesoneormorefilenamesasargumentsandaddsexecutepermissionfortheuserforeachfile
argument.
4. Whatcanyoudotomakethefunctionavailableeverytimeyoulogin?
5. Supposethat,inadditiontohavingthefunctionavailableonsubsequentloginsessions,youwanttomakethefunctionavailable
nowinyourcurrentshell.Howwouldyoudoso?
5. Whenmightitbenecessaryoradvisabletowriteashellscriptinsteadofashellfunction?Giveasmanyreasonsasyoucanthinkof.
6. Writeashellscriptthatdisplaysthenamesofalldirectoryfiles,butnoothertypesoffiles,intheworkingdirectory.
7. Writeascripttodisplaythetimeevery15seconds.Readthedatemanpageanddisplaythetime,usingthe%rfielddescriptor.Clear
thewindow(usingtheclearcommand)eachtimebeforeyoudisplaythetime.
8.
Enterthefollowingscriptnamedsavefiles,andgiveyourselfexecutepermissiontothefile:
$catsavefiles
#!/bin/bash
echo"Savingfilesincurrentdirectoryinfilesavethem."
exec>savethem
foriin*
do
echo"==================================================="
echo"File:$i"
echo"==================================================="
cat"$i"
done
1. Whaterrormessagedoyougetwhenyouexecutethisscript?Rewritethescriptsothattheerrordoesnotoccur,makingsure
theoutputstillgoestosavethem.
2. Whatmightbeaproblemwithrunningthisscripttwiceinthesamedirectory?Discussasolutiontothisproblem.
9.
Readthebashmanorinfopage,trysomeexperiments,andanswerthefollowingquestions:
1. Howdoyouexportafunction?
2. Whatdoesthehashbuiltindo?
3. Whathappensiftheargumenttoexecisnotexecutable?
10.
Usingthefindutility,performthefollowingtasks:
1. Listallfilesintheworkingdirectoryandallsubdirectoriesthathavebeenmodifiedwithinthelastday.
2. Listallfilesthatyouhavereadaccesstoonthesystemthatarelargerthan1megabyte.
3. Removeallfilesnamedcorefromthedirectorystructurerootedatyourhomedirectory.
4. Listtheinodenumbersofallfilesintheworkingdirectorywhosefilenamesendin.c.
5. Listallfilesthatyouhavereadaccesstoontherootfilesystemthathavebeenmodifiedinthelast30days.
11.
Writeashortscriptthattellsyouwhetherthepermissionsfortwofiles,whosenamesaregivenasargumentstothescript,areidentical.
Ifthepermissionsforthetwofilesareidentical,outputthecommonpermissionfield.Otherwise,outputeachfilenamefollowedbyits
permissionfield.(Hint:Tryusingthecututility.)
12.
Writeascriptthattakesthenameofadirectoryasanargumentandsearchesthefilehierarchyrootedatthatdirectoryforzero-length
files.Writethenamesofallzero-lengthfilestostandardoutput.Ifthereisnooptiononthecommandline,havethescriptdeletethefile
afterdisplayingitsname,askingtheuserforconfirmation,andreceivingpositiveconfirmation.Af(force)optiononthecommandline
indicatesthatthescriptshoulddisplaythefilenamebutnotaskforconfirmationbeforedeletingthefile.
AdvancedExercises
13. Writeascriptthattakesacolon-separatedlistofitemsandoutputstheitems,oneperline,tostandardoutput(withoutthecolons).
14. Generalizethescriptwritteninexercise13sothatthecharacterseparatingthelistitemsisgivenasanargumenttothefunction.Ifthis
argumentisabsent,theseparatorshoulddefaulttoacolon.
15.
Writeafunctionnamedfunloadthattakesasitssingleargumentthenameofafilecontainingotherfunctions.Thepurposeoffunload
istomakeallfunctionsinthenamedfileavailableinthecurrentshell;thatis,funloadloadsthefunctionsfromthenamedfile.Tolocate
thefile,funloadsearchesthecolon-separatedlistofdirectoriesgivenbytheenvironmentvariableFUNPATH.Assumethattheformatof
FUNPATHisthesameasPATHandthatsearchingFUNPATHissimilartotheshell'ssearchofthePATHvariable.
16.
Rewritebundle(page469)sothatthescriptitcreatestakesanoptionallistoffilenamesasarguments.Ifoneormorefilenamesare
givenonthecommandline,onlythosefilesshouldbere-created;otherwise,allfilesintheshellarchiveshouldbere-created.For
example,supposethatallfileswiththefilenameextension.carebundledintoanarchivenamedsrcshell,andyouwanttounbundlejust
thefilestest1.candtest2.c.Thefollowingcommandwillunbundlejustthesetwofiles:
$bashsrcshelltest1.ctest2.c
17. Whatkindoflinkswillthelnksscript(page445)notfind?Why?
18. Inprinciple,recursionisnevernecessary.Itcanalwaysbereplacedbyaniterativeconstruct,suchaswhileoruntil.Rewrite
makepath(page511)asanonrecursivefunction.Whichversiondoyouprefer?Why?
19.
Listsarecommonlystoredinenvironmentvariablesbyputtingacolon(:)betweeneachofthelistelements.(ThevalueofthePATH
variableisagoodexample.)Youcanaddanelementtosuchalistbycatenatingthenewelementtothefrontofthelist,asin
PATH=/opt/bin:$PATH
Iftheelementyouaddisalreadyinthelist,younowhavetwocopiesofitinthelist.Writeashellfunctionnamedaddenvthattakestwo
arguments:(1)thenameofashellvariableand(2)astringtoprependtothelistthatisthevalueoftheshellvariableonlyifthatstringis
notalreadyanelementofthelist.Forexample,thecall
addenvPATH/opt/bin
wouldadd/opt/bintoPATHonlyifthatpathnameisnotalreadyinPATH.Besurethatyoursolutionworkseveniftheshellvariable
startsoutempty.Alsomakesurethatyoucheckthelistelementscarefully.If/usr/opt/binisinPATHbut/opt/binisnot,theexample
justgivenshouldstilladd/opt/bintoPATH.(Hint:Youmayfindthisexerciseeasiertocompleteifyoufirstwriteafunction
locate_fieldthattellsyouwhetherastringisanelementinthevalueofavariable.)
20.
Writeafunctionthattakesadirectorynameasanargumentandwritestostandardoutputthemaximumofthelengthsofallfilenamesin
thatdirectory.Ifthefunction'sargumentisnotadirectoryname,writeanerrormessagetostandardoutputandexitwithnonzero
status.
21. Modifythefunctionyouwroteforexercise20todescendallsubdirectoriesofthenameddirectoryrecursivelyandtofindthemaximum
lengthofanyfilenameinthathierarchy.
22.
Writeafunctionthatliststhenumberofregularfiles,directories,blockspecialfiles,characterspecialfiles,FIFOs,andsymboliclinksin
theworkingdirectory.Dothisintwodifferentways:
1. Usethefirstletteroftheoutputoflsltodetermineafile'stype.
2. Usethefiletypeconditiontestsofthe[[expression]]syntaxtodetermineafile'stype.
23. Modifythequizprogram(page518)sothatthechoicesforaquestionarerandomlyarranged.
Chapter12.ThegawkPatternProcessingLanguage
INTHISCHAPTER
Syntax528
Arguments528
Options529
Patterns530
Actions531
Variables531
Functions532
AssociativeArrays534
ControlStructures535
Examples537
getline:ControllingInput554
Coprocess:Two-WayI/O557
GettingInputfromaNetwork558
ErrorMessages559
Thegawk(GNUawk)utilityisapattern-scanningandprocessinglanguagethatsearchesoneormore
filestoseewhethertheycontainrecords(usuallylines)thatmatchspecifiedpatterns.Itprocesseslinesby
performingactions,suchaswritingtherecordtostandardoutputorincrementingacounter,eachtimeit
findsamatch.Asopposedtoprocedurallanguages,thegawklanguageisdatadriven:Youdescribethe
datayouwanttoworkwithandtellgawkwhattodowiththedataonceitfindsit.
Youcanusegawktogeneratereportsorfiltertext.Itworksequallywellwithnumbersandtext;when
youmixthetwo,gawkusuallycomesupwiththerightanswer.Theauthorsofawk(AlfredV.Aho,Peter
J.Weinberger,andBrianW.Kernighan),onwhichgawkisbased,designedtheoriginalutilitytobeeasy
touse.Toachievethisendtheysacrificedexecutionspeed.
ThegawkutilitytakesmanyofitsconstructsfromtheCprogramminglanguage.Itincludesthefollowing
features:

Flexibleformat
Conditionalexecution
Loopingstatements
Numericvariables
Stringvariables
Regularexpressions
Relationalexpressions
C'sprintf
Coprocessexecution
Networkdataexchange
Syntax
Agawkcommandlinehasthefollowingsyntax:
gawk[options][program][file-list]
gawk[options]fprogram-file[file-list]
Thegawkutilitytakesitsinputfromfilesyouspecifyonthecommandlineorfromstandardinput.An
advancedcommand,getline,givesyoumorechoicesaboutwhereinputcomesfromandhowyoureadit.
Usingacoprocess,gawkcaninteractwithanotherprogramorexchangedataoveranetwork.Unlessyou
redirectoutputfromgawk,itgoestostandardoutput.
Arguments
Intheprecedingsyntax,programisagawkprogramthatyouincludeonthecommandline.The
program-fileisthenameofthefilethatholdsagawkprogram.Puttingtheprogramonthecommandline
allowsyoutowriteshortgawkprogramswithouthavingtocreateaseparateprogram-file.Toprevent
theshellfrominterpretingthegawkcommandsasshellcommands,enclosetheprogramwithinsingle
quotationmarks.Puttingalongorcomplexprograminafilecanreduceerrorsandretyping.
Thefile-listcontainspathnamesoftheordinaryfilesthatgawkprocesses.Thesefilesaretheinputfiles.
Whenyoudonotspecifyafile-list,gawktakesinputfromstandardinputorasspecifiedbygetline(page
554)oracoprocess(page557).
Options
field-separatorfs
Ffs
Usesfsasthevalueoftheinputfieldseparator(FSvariable).
fileprogram-file
fprogram-file
Readsthegawkprogramfromthefilenamedprogram-fileinsteadof
thecommandline.Youcanspecifythisoptionmorethanonceona
commandline.
help Whelp
Summarizeshowtousegawk.
lint Wlint
Warnsaboutconstructsthatmaynotbecorrectorportable.
posix Wposix
RunsaPOSIX-compliantversionofgawk.Thisoptionintroducessome
restrictions;seethegawkmanpagefordetails.
traditional Wtraditional
IgnoresthenewGNUfeaturesinagawkprogram,makingtheprogram
conformtoUNIXawk.

LanguageBasics
Agawkprogram(fromthecommandlineorfromprogram-file)consistsofoneormorelinescontaining
apatternand/oractioninthefollowingformat:
pattern{action}
Thepatternselectslinesfromtheinput.Thegawkutilityperformstheactiononalllinesthatthepattern
selects.Thebracessurroundingtheactionenablegawktodifferentiateitfromthepattern.Ifaprogram
linedoesnotcontainapattern,gawkselectsalllinesintheinput.Ifaprogramlinedoesnotcontainan
action,gawkcopiestheselectedlinestostandardoutput.
Tostart,gawkcomparesthefirstlineofinput(fromthefile-listorstandardinput)witheachpatternin
theprogram.Ifapatternselectstheline(ifthereisamatch),gawktakestheactionassociatedwiththe
pattern.Ifthelineisnotselected,gawktakesnoaction.Whengawkhascompleteditscomparisonsfor
thefirstlineofinput,itrepeatstheprocessforthenextlineofinput,continuingthisprocessofcomparing
subsequentlinesofinputuntilithasreadalloftheinput.
Ifseveralpatternsselectthesameline,gawktakestheactionsassociatedwitheachofthepatternsin
theorderinwhichtheyappearintheprogram.Itispossibleforgawktosendasinglelinefromtheinput
tostandardoutputmorethanonce.
Patterns
Youcanusearegularexpression(AppendixA),enclosedwithinslashes,asapattern.The~operator
testswhetherafieldorvariablematchesaregularexpression.The!~operatortestsfornomatch.Youcan
performbothnumericandstringcomparisonsusingtherelationaloperatorslistedinTable12-1.Youcan
combineanyofthepatternsusingtheBooleanoperators||(OR)or&&(AND).
Table12-1.Relationaloperators
Relop Meaning
< Lessthan
<= Lessthanorequalto
== Equalto

!= Notequalto
>= Greaterthanorequalto
> Greaterthan
BEGINandEND
Twouniquepatterns,BEGINandEND,executecommandsbeforegawkstartsitsprocessingandafterit
finishes.ThegawkutilityexecutestheactionsassociatedwiththeBEGINpatternbefore,andwiththe
ENDpatternafter,itprocessesalltheinput.
,(comma)
Thecommaistherangeoperator.Ifyouseparatetwopatternswithacommaonasinglegawkprogram
line,gawkselectsarangeoflines,beginningwiththefirstlinethatmatchesthefirstpattern.Thelast
linegawkselectsisthenextsubsequentlinethatmatchesthesecondpattern.Ifnolinematchesthe
secondpattern,gawkselectseverylinethroughtheendoftheinput.Aftergawkfindsthesecond
pattern,itbeginstheprocessagainbylookingforthefirstpatternagain.
Actions
Theactionportionofagawkcommandcausesgawktotakethatactionwhenitmatchesapattern.
Whenyoudonotspecifyanaction,gawkperformsthedefaultaction,whichistheprintcommand
(explicitlyrepresentedas{print}).Thisactioncopiestherecord(normallyalinesee"Variables")from
theinputtostandardoutput.
Whenyoufollowaprintcommandwitharguments,gawkdisplaysonlytheargumentsyouspecify.These
argumentscanbevariablesorstringconstants.Youcansendtheoutputfromaprintcommandtoafile
(>),appendittoafile(>>),orsenditthroughapipetotheinputofanotherprogram(|).Acoprocess
(|&)isatwo-waypipethatexchangesdatawithaprogramrunninginthebackground(page557).
Unlessyouseparateitemsinaprintcommandwithcommas,gawkcatenatesthem.Commascausegawk
toseparatetheitemswiththeoutputfieldseparator(OFS,normallyaSPACEsee"Variables").
Youcanincludeseveralactionsononelinebyseparatingthemwithsemicolons.
Comments

Thegawkutilitydisregardsanythingonaprogramlinefollowingapoundsign(#).Youcandocumenta
gawkprogrambyprecedingcommentswiththissymbol.
Variables
Althoughyoudonotneedtodeclaregawkvariablespriortotheiruse,youcanoptionallyassigninitial
valuestothem.Unassignednumericvariablesareinitializedto0;stringvariablesareinitializedtothe
nullstring.Inadditiontouservariables,gawkmaintainsprogramvariables.Youcanusebothuserand
programvariablesinthepatternandintheactionportionofagawkprogram.Table12-2listsafew
programvariables.
Table12-2.Variables
Variable Meaning
$0 Thecurrentrecord(asasinglevariable)
$1$n Fieldsinthecurrentrecord
FILENAME Nameofthecurrentinputfile(nullforstandardinput)
FS Inputfieldseparator(default:SPACEorTAB)
NF Numberoffieldsinthecurrentrecord
NR Recordnumberofthecurrentrecord
OFS Outputfieldseparator(default:SPACE)
ORS Outputrecordseparator(default:NEWLINE)
RS Inputrecordseparator(default:NEWLINE)
Inadditiontoinitializingvariableswithinaprogram,youcanusetheassign(v)optiontoinitialize
variablesonthecommandline.Thisfeatureisusefulwhenthevalueofavariablechangesfromonerun
ofgawktothenext.
BydefaulttheinputandoutputrecordseparatorsareNEWLINEcharacters.Thusgawktakeseachlineof
inputtobeaseparaterecordandappendsaNEWLINEtotheendofeachoutputrecord.Bydefaultthe
inputfieldseparatorsareSPACEsandTABs.ThedefaultoutputfieldseparatorisaSPACE.Youcan
changethevalueofanyoftheseparatorsatanytimebyassigninganewvaluetoitsassociatedvariable

eitherfromwithintheprogramorfromthecommandlinebyusingtheassign(v)option.
Functions
Table12-3listsafewofthefunctionsthatgawkprovidesformanipulatingnumbersandstrings.
Table12-3.Functions
Function Meaning
length(str)Returnsthenumberofcharactersinstr;withoutanargument,
returnsthenumberofcharactersinthecurrentrecord
int(num)Returnstheintegerportionofnum
index(str1,str2)Returnstheindexofstr2instr1or0ifstr2isnotpresent
split(str,arr,del)Placeselementsofstr,delimitedbydel,inthearrayarr[1]...arr
[n];returnsthenumberofelementsinthearray
sprintf(fmt,args)Formatsargsaccordingtofmtandreturnstheformattedstring;
mimicstheCprogramminglanguagefunctionofthesamename
substr(str,pos,len)Returnsthesubstringofstrthatbeginsatposandislen
characterslong
tolower(str)Returnsacopyofstrinwhichalluppercaselettersarereplaced
withtheirlowercasecounterparts
toupper(str)Returnsacopyofstrinwhichalllowercaselettersarereplaced
withtheiruppercasecounterparts
ArithmeticOperators
ThegawkarithmeticoperatorslistedinTable12-4arefromtheCprogramminglanguage.
Table12-4.Arithmeticoperators
Operator Meaning
*Multipliestheexpressionprecedingtheoperatorbytheexpression
followingit

/Dividestheexpressionprecedingtheoperatorbytheexpression
followingit
%Takestheremainderafterdividingtheexpressionprecedingthe
operatorbytheexpressionfollowingit
+Addstheexpressionprecedingtheoperatortotheexpression
followingit
Subtractstheexpressionfollowingtheoperatorfromthe
expressionprecedingit
=Assignsthevalueoftheexpressionfollowingtheoperatortothe
variableprecedingit
++ Incrementsthevariableprecedingtheoperator
Decrementsthevariableprecedingtheoperator
+=
Addstheexpressionfollowingtheoperatortothevariable
precedingitandassignstheresulttothevariableprecedingthe
operator
=
Subtractstheexpressionfollowingtheoperatorfromthevariable
precedingitandassignstheresulttothevariableprecedingthe
operator
*=
Multipliesthevariableprecedingtheoperatorbytheexpression
followingitandassignstheresulttothevariableprecedingthe
operator
/=
Dividesthevariableprecedingtheoperatorbytheexpression
followingitandassignstheresulttothevariableprecedingthe
operator
%=
Assignstheremainder,afterdividingthevariableprecedingthe
operatorbytheexpressionfollowingit,tothevariablepreceding
theoperator
AssociativeArrays
Anassociativearrayisoneofgawk'smostpowerfulfeatures.Thesearraysusestringsasindexes.Using
anassociativearray,youcanmimicatraditionalarraybyusingnumericstringsasindexes.
Youassignavaluetoanelementofanassociativearrayjustasyouwouldassignavaluetoanyother
gawkvariable.Thesyntaxis

array[string]=value
wherearrayisthenameofthearray,stringistheindexoftheelementofthearrayyouareassigninga
valueto,andvalueisthevalueyouareassigningtothatelement.
Youcanuseaspecialforstructurewithanassociativearray.Thesyntaxis
for(eleminarray)action
whereelemisavariablethattakesonthevalueofeachelementofthearrayastheforstructureloops
throughthem,arrayisthenameofthearray,andactionistheactionthatgawktakesforeachelementin
thearray.Youcanusetheelemvariableinthisaction.
The"Examples"sectionfoundlaterinthischaptercontainsprogramsthatuseassociativearrays.
printf
Youcanusetheprintfcommandinplaceofprinttocontroltheformatoftheoutputthatgawkgenerates.
ThegawkversionofprintfissimilartothatfoundintheClanguage.Aprintfcommandhasthe
followingsyntax:
printf"control-string",arg1,arg2,...,argn
Thecontrol-stringdetermineshowprintfformatsarg1,arg2,...,argn.Theseargumentscanbe
variablesorotherexpressions.Withinthecontrol-stringyoucanuse\ntoindicateaNEWLINEand\tto
indicateaTAB.Thecontrol-stringcontainsconversionspecifications,oneforeachargument.A
conversionspecificationhasthefollowingsyntax:
%[][x[.y]]conv
wherecausesprintftoleft-justifytheargument;xistheminimumfieldwidth,and.yisthenumberof
placestotherightofadecimalpointinanumber.Theconvindicatesthetypeofnumericconversionand
canbeselectedfromthelettersinTable12-5.Referto"Examples"laterinthischapterforexamplesof
howtouseprintf.
Table12-5.Numericconversion

conv Typeofconversion
dDecimal
eExponentialnotation
fFloating-pointnumber
gUsefore,whicheverisshorter
oUnsignedoctal
sStringofcharacters
xUnsignedhexadecimal
ControlStructures
Control(flow)statementsaltertheorderofexecutionofcommandswithinagawkprogram.Thissection
detailstheif...else,while,andforcontrolstructures.Inaddition,thebreakandcontinuestatementswork
inconjunctionwiththecontrolstructurestoaltertheorderofexecutionofcommands.Seepage436for
moreinformationoncontrolstructures.Youdonotneedtousebracesaroundcommandswhenyou
specifyasingle,simplecommand.
if...else
Theif...elsecontrolstructureteststhestatusreturnedbytheconditionandtransferscontrolbasedonthis
status.Thesyntaxofanif...elsestructureisshownbelow.Theelsepartisoptional.
if(condition)
{commands}
[else
{commands}]
Thesimpleifstatementshownheredoesnotusebraces:
if($5<=5000)print$0
Nextisagawkprogramthatusesasimpleif...elsestructure.Again,therearenobraces.
$catif1
BEGIN{
nam="sam"
if(nam=="max")
print"namismax"
else
print"namisnotmax,itis",nam
}
$gawk-fif1
namisnotmax,itissam
while
Thewhilestructureloopsthroughandexecutesthecommandsaslongastheconditionistrue.The
syntaxofawhilestructureis
while(condition)
{commands}
Thenextgawkprogramusesasimplewhilestructuretodisplaypowersof2.Thisexampleusesbraces
becausethewhileloopcontainsmorethanonestatement.
$catwhile1
BEGIN{
n=1
while(n<=5)
{
printn"^2",2**n
n++
}
}
$gawk-fwhile1
1^22
2^24
3^28
4^216
5^232
for
Thesyntaxofaforcontrolstructureis
for(init;condition;increment)
{commands}
Aforstructurestartsbyexecutingtheinitstatement,whichusuallysetsacounterto0or1.Itthenloops
throughthecommandsaslongastheconditionistrue.Aftereachloopitexecutestheincrement
statement.Thefor1gawkprogramdoesthesamethingastheprecedingwhile1programexceptthatit
usesaforstatement,whichmakestheprogramsimpler:
$catfor1
BEGIN{
for(n=1;n<=5;n++)
printn"^2",2**n
}
$gawk-ffor1
1^22
2^24
3^28
4^216
5^232
Thegawkutilitysupportsanalternativeforsyntaxforworkingwithassociativearrays:
for(varinarray)
{commands}
Thisforstructureloopsthroughelementsoftheassociativearraynamedarray,assigningthevalueofthe
indexofeachelementofarraytovareachtimethroughtheloop.
END{for(nameinmanuf)printname,manuf[name]}
break
Thebreakstatementtransferscontroloutofafororwhileloop,terminatingexecutionoftheinnermost
loopitappearsin.
continue
Thecontinuestatementtransferscontroltotheendofafororwhileloop,causingexecutionofthe
innermostloopitappearsintocontinuewiththenextiteration.
Examples
carsdatafile
Manyoftheexamplesinthissectionworkwiththecarsdatafile.Fromlefttorightthecolumnsinthefile
containeachcar'smake,model,yearofmanufacture,mileageinthousandsofmiles,andprice.All
whitespaceinthisfileiscomposedofsingleTABs(thefiledoesnotcontainanySPACEs).
$catcars
plymfury1970732500
chevymalibu1999603000
fordmustang19654510000
volvos8019981029850
fordthundbd20031510500
chevymalibu2000503500
bmw325i1985115450
hondaaccord2001306000
fordtaurus20041017000
toyotarav42002180750
chevyimpala1985851550
fordexplor2003259500
Missingpattern
Asimplegawkprogramis
{print}
Thisprogramconsistsofoneprogramlinethatisanaction.Becausethepatternismissing,gawkselects
alllinesofinput.Whenusedwithoutanyargumentstheprintcommanddisplayseachselectedlineinits
entirety.Thisprogramcopiestheinputtostandardoutput.
$gawk'{print}'cars
plymfury1970732500
chevymalibu1999603000
fordmustang19654510000
volvos8019981029850
...
Missingaction
Thenextprogramhasapatternbutnoexplicitaction.Theslashesindicatethatchevyisaregular
expression.
/chevy/
Inthiscasegawkselectsfromtheinputalllinesthatcontainthestringchevy.Whenyoudonotspecifyan
action,gawkassumesthattheactionisprint.Thefollowingexamplecopiestostandardoutputalllines
fromtheinputthatcontainthestringchevy:
$gawk'/chevy/'cars
chevymalibu1999603000
chevymalibu2000503500
chevyimpala1985851550
Singlequotationmarks
Althoughneithergawknorshellsyntaxrequiressinglequotationmarksonthecommandline,itisstilla
goodideatousethembecausetheycanpreventproblems.Ifthegawkprogramyoucreateonthe
commandlineincludesSPACEsorspecialshellcharacters,youmustquotethem.Alwaysenclosingthe
programinsinglequotationmarksistheeasiestwayofmakingsurethatyouhavequotedanycharacters
thatneedtobequoted.
Fields
Thenextexampleselectsalllinesfromthefile(ithasnopattern).Thebracesenclosetheaction;you
mustalwaysusebracestodelimittheactionsothatgawkcandistinguishitfromthepattern.This
exampledisplaysthethirdfield($3),aSPACE(theoutputfieldseparator,indicatedbythecomma),and
thefirstfield($1)ofeachselectedline:
$gawk'{print$3,$1}'cars
1970plym
1999chevy
1965ford
1998volvo
...
Thenextexample,whichincludesbothapatternandanaction,selectsalllinesthatcontainthestring
chevyanddisplaysthethirdandfirstfieldsfromthelinesitselects:
$gawk'/chevy/{print$3,$1}'cars
1999chevy
2000chevy
1985chevy
Nextgawkselectslinesthatcontainamatchfortheregularexpressionh.Becausethereisnoexplicit
action,gawkdisplaysallthelinesitselects:
$gawk'/h/'cars
chevymalibu1999603000
fordthundbd20031510500
chevymalibu2000503500
hondaaccord2001306000
chevyimpala1985851550
~(matchesoperator)
Thenextpatternusesthematchesoperator(~)toselectalllinesthatcontaintheletterhinthefirstfield:
$gawk'$1~/h/'cars
chevymalibu1999603000
chevymalibu2000503500
hondaaccord2001306000
chevyimpala1985851550
Thecaret(^)inaregularexpressionforcesamatchatthebeginningoftheline(page830)or,inthiscase,
thebeginningofthefirstfield:
$gawk'$1~/^h/'cars
hondaaccord2001306000
Bracketssurroundacharacter-classdefinition(page829).Inthenextexample,gawkselectslinesthat
haveasecondfieldthatbeginswithtormanddisplaysthethirdandsecondfields,adollarsign,andthe
fifthfield.Becausethereisnocommabetweenthe"$"andthe$5,gawkdoesnotputaSPACEbetween
themintheoutput.
$gawk'$2~/^[tm]/{print$3,$2,"$"$5}'cars
1999malibu$3000
1965mustang$10000
2003thundbd$10500
2000malibu$3500
2004taurus$17000
Dollarsigns
Thenextexampleshowsthreerolesadollarsigncanplayinagawkprogram.Adollarsignfollowedby
anumbernamesafield.Withinaregularexpressionadollarsignforcesamatchattheendofalineor
field(5$).Withinastringadollarsignrepresentsitself.
$gawk'$3~/5$/{print$3,$1,"$"$5}'cars
1965ford$10000
1985bmw$450
1985chevy$1550
Inthenextexample,theequal-torelationaloperator(==)causesgawktoperformanumericcomparison
betweenthethirdfieldineachlineandthenumber1985.Thegawkcommandtakesthedefaultaction,
print,oneachlinewherethecomparisonistrue.
$gawk'$3==1985'cars
bmw325i1985115450
chevyimpala1985851550
Thenextexamplefindsallcarspricedatorlessthan$3,000:
$gawk'$5<=3000'cars
plymfury1970732500
chevymalibu1999603000
bmw325i1985115450
toyotarav42002180750
chevyimpala1985851550
Textualcomparisons
Whenyouusedoublequotationmarks,gawkperformstextualcomparisonsbyusingtheASCII(orother
local)collatingsequenceasthebasisofthecomparison.Inthefollowingexample,gawkshowsthatthe
strings450and750fallintherangethatliesbetweenthestrings2000and9000,whichisprobablynot
theintendedresult:
$gawk'"2000"<=$5&&$5<"9000"'cars
plymfury1970732500
chevymalibu1999603000
chevymalibu2000503500
bmw325i1985115450
hondaaccord2001306000
toyotarav42002180750
Whenyouneedtoperformanumericcomparison,donotusequotationmarks.Thenextexamplegivesthe
intendedresult.Itisthesameasthepreviousexampleexceptthatitomitsthedoublequotationmarks.
$gawk'2000<=$5&&$5<9000'cars
plymfury1970732500
chevymalibu1999603000
chevymalibu2000503500
hondaaccord2001306000
,(rangeoperator)
Therangeoperator(,)selectsagroupoflines.Thefirstlineitselectsistheonespecifiedbythepattern
beforethecomma.Thelastlineistheoneselectedbythepatternafterthecomma.Ifnolinematchesthe
patternafterthecomma,gawkselectseverylinethroughtheendoftheinput.Thenextexampleselects
alllines,startingwiththelinethatcontainsvolvoandconcludingwiththelinethatcontainsbmw:
$gawk'/volvo/,/bmw/'cars
volvos8019981029850
fordthundbd20031510500
chevymalibu2000503500
bmw325i1985115450
Aftertherangeoperatorfindsitsfirstgroupoflines,itbeginstheprocessagain,lookingforalinethat
matchesthepatternbeforethecomma.Inthefollowingexample,gawkfindsthreegroupsoflinesthat
fallbetweenchevyandford.
Althoughthefifthlineofinputcontainsford,gawkdoesnotselectitbecauseatthetimeitisprocessing
thefifthline,itissearchingforchevy.
$gawk'/chevy/,/ford/'cars
chevymalibu1999603000
fordmustang19654510000
chevymalibu2000503500
bmw325i1985115450
hondaaccord2001306000
fordtaurus20041017000
chevyimpala1985851550
fordexplor2003259500
fileoption
Whenyouarewritingalongergawkprogram,itisconvenienttoputtheprograminafileandreference
thefileonthecommandline.Usetheforfileoptionfollowedbythenameofthefilecontainingthe
gawkprogram.
BEGIN
Thefollowinggawkprogram,storedinafilenamedpr_header,hastwoactionsandusestheBEGIN
pattern.ThegawkutilityperformstheactionassociatedwithBEGINbeforeprocessinganylinesofthe
datafile:Itdisplaysaheader.Thesecondaction,{print},hasnopatternpartanddisplaysallthelines
fromtheinput.
$catpr_header
BEGIN{print"MakeModelYearMilesPrice"}
{print}
$gawk-fpr_headercars
MakeModelYearMilesPrice
plymfury1970732500
chevymalibu1999603000
fordmustang19654510000
volvos8019981029850
...
ThenextexampleexpandstheactionassociatedwiththeBEGINpattern.Inthepreviousandfollowing
examples,thewhitespaceintheheadersiscomposedofsingleTABs,sothatthetitleslineupwiththe
columnsofdata.
$catpr_header2
BEGIN{
print"MakeModelYearMilesPrice"
print"----------------------------------------"
}
{print}
$gawk-fpr_header2cars
MakeModelYearMilesPrice
----------------------------------------
plymfury1970732500
chevymalibu1999603000
fordmustang19654510000
volvos8019981029850
...
lengthfunction
Whenyoucallthelengthfunctionwithoutanargument,itreturnsthenumberofcharactersinthecurrent
line,includingfieldseparators.The$0variablealwayscontainsthevalueofthecurrentline.Inthenext
example,gawkprependsthelinelengthtoeachlineandthenapipesendstheoutputfromgawktosort
(thenoptionspecifiesanumericsort;page762)sothatthelinesofthecarsfileappearinorderoflength:
$gawk'{printlength,$0}'cars|sort-n
21bmw325i1985115450
22plymfury1970732500
23volvos8019981029850
24fordexplor2003259500
24toyotarav42002180750
25chevyimpala1985851550
25chevymalibu1999603000
25chevymalibu2000503500
25fordtaurus20041017000
25hondaaccord2001306000
26fordmustang19654510000
26fordthundbd20031510500
TheformattingofthisreportdependsonTABsforhorizontalalignment.Thethreeextracharactersatthe
beginningofeachlinethrowofftheformatofseverallines.Aremedyforthissituationiscoveredshortly.
NR(recordnumber)
TheNRvariablecontainstherecord(line)numberofthecurrentline.Thefollowingpatternselectsall
linesthatcontainmorethan24characters.Theactiondisplaysthelinenumberofeachoftheselected
lines.
$gawk'length>24{printNR}'cars
2
3
5
6
8
9
11
Youcancombinetherangeoperator(,)andtheNRvariabletodisplayagroupoflinesofafilebasedon
theirlinenumbers.Thenextexampledisplayslines2through4:
$gawk'NR==2,NR==4'cars
chevymalibu1999603000
fordmustang19654510000
volvos8019981029850
END
TheENDpatternworksinamannersimilartotheBEGINpattern,exceptthatgawktakestheactions
associatedwithitafterprocessingthelastlineofinput.Thefollowingreportdisplaysinformationonly
afterithasprocessedalltheinput.TheNRvariableretainsitsvalueaftergawkfinishesprocessingthe
datafile,sothatanactionassociatedwithanENDpatterncanuseit:
$gawk'END{printNR,"carsforsale."}'cars
12carsforsale.
Thenextexampleusesifcontrolstructurestoexpandtheabbreviationsusedinsomeofthefirstfields.As
longasgawkdoesnotchangearecord,itleavestheentirerecordincludingseparatorsintact.Onceit
makesachangetoarecord,gawkchangesallseparatorsinthatrecordtothevalueoftheoutputfield
separator.ThedefaultoutputfieldseparatorisaSPACE.
$catsepar_demo
{
if($1~/ply/)$1="plymouth"
if($1~/chev/)$1="chevrolet"
print
}
$gawk-fsepar_democars
plymouthfury1970732500
chevroletmalibu1999603000
fordmustang19654510000
volvos8019981029850
fordthundbd20031510500
chevroletmalibu2000503500
bmw325i1985115450
hondaaccord2001306000
fordtaurus20041017000
toyotarav42002180750
chevroletimpala1985851550
fordexplor2003259500
Stand-alonescript
Insteadofcallinggawkfromthecommandlinewiththefoptionandthenameoftheprogramyouwantto
run,youcanwriteascriptthatcallsgawkwiththecommandsyouwanttorun.Thenextexampleisa
stand-alonescriptthatrunsthesameprogramasthepreviousexample.The#!/bin/gawkfcommand(page
265)runsthegawkutilitydirectly.Youneedbothreadandexecutepermissiontothefileholdingthe
script(page263).
$chmodu+rxsepar_demo2
$catsepar_demo2
#!/bin/gawk-f
{
if($1~/ply/)$1="plymouth"
if($1~/chev/)$1="chevrolet"
print
}
$separ_demo2cars
plymouthfury1970732500
chevroletmalibu1999603000
fordmustang19654510000
...
OFSvariable
YoucanchangethevalueoftheoutputfieldseparatorbyassigningavaluetotheOFSvariable.The
followingexampleassignsaTABcharactertoOFS,usingthebackslashescapesequence\t.Thisfix
improvestheappearanceofthereportbutdoesnotlineupthecolumnsproperly.
$catofs_demo
BEGIN{OFS="\t"}
{
if($1~/ply/)$1="plymouth"
if($1~/chev/)$1="chevrolet"
print
}
$gawk-fofs_democars
plymouthfury1970732500
chevroletmalibu1999603000
fordmustang19654510000
volvos8019981029850
fordthundbd20031510500
chevroletmalibu2000503500
bmw325i1985115450
hondaaccord2001306000
fordtaurus20041017000
toyotarav42002180750
chevroletimpala1985851550
fordexplor2003259500
printf
Youcanuseprintf(page534)torefinetheoutputformat.Thefollowingexampleusesabackslashatthe
endofseveralprogramlinestoquotethefollowingNEWLINE.Youcanusethistechniquetocontinuea
longlineoveroneormorelineswithoutaffectingtheoutcomeoftheprogram.
$catprintf_demo
BEGIN{
print"Miles"
print"MakeModelYear(000)Price"
print\
"--------------------------------------------------"
}
{
if($1~/ply/)$1="plymouth"
if($1~/chev/)$1="chevrolet"
printf"%-10s%-8s%2d%5d$%8.2f\n",\
$1,$2,$3,$4,$5
}
$gawk-fprintf_democars
Miles
MakeModelYear(000)Price
--------------------------------------------------
plymouthfury197073$2500.00
chevroletmalibu199960$3000.00
fordmustang196545$10000.00
volvos801998102$9850.00
fordthundbd200315$10500.00
chevroletmalibu200050$3500.00
bmw325i1985115$450.00
hondaaccord200130$6000.00
fordtaurus200410$17000.00
toyotarav42002180$750.00
chevroletimpala198585$1550.00
fordexplor200325$9500.00
Redirectingoutput
Thenextexamplecreatestwofiles:onewiththelinesthatcontainchevyandonewiththelinesthat
containford:
$catredirect_out
/chevy/{print>"chevfile"}
/ford/{print>"fordfile"}
END{print"done."}
$gawk-fredirect_outcars
done.
$catchevfile
chevymalibu1999603000
chevymalibu2000503500
chevyimpala1985851550
Thesummaryprogramproducesasummaryreportonallcarsandnewercars.Althoughtheyarenot
required,theinitializationsatthebeginningoftheprogramrepresentgoodprogrammingpractice;gawk
automaticallydeclaresandinitializesvariablesasyouusethem.Afterreadingalltheinputdata,gawk
computesanddisplaysaverages.
$catsummary
BEGIN{
yearsum=0;costsum=0
newcostsum=0;newcount=0
}
{
yearsum+=$3
costsum+=$5
}
$3>2000{newcostsum+=$5;newcount++}
END{
printf"Averageageofcarsis%4.1fyears\n",\
2006-(yearsum/NR)
printf"Averagecostofcarsis$%7.2f\n",\
costsum/NR
printf"Averagecostofnewercarsis$%7.2f\n",\
newcostsum/newcount
}
$gawk-fsummarycars
Averageageofcarsis13.1years
Averagecostofcarsis$6216.67
Averagecostofnewercarsis$8750.00
Thefollowinggawkcommandshowstheformatofalinefromthepasswdfilethatthenextexampleuses:
$awk'/mark/{print}'/etc/passwd
mark:x:107:100:ext112:/home/mark:/bin/tcsh
Thenextexampledemonstratesatechniqueforfindingthelargestnumberinafield.Becauseitworks
withthepasswdfile,whichdelimitsfieldswithcolons(:),theexamplechangestheinputfieldseparator
(FS)beforereadinganydata.ItreadsthepasswdfileanddeterminesthenextavailableuserIDnumber
(field3).Thenumbersdonothavetobeinorderinthepasswdfileforthisprogramtowork.
Thepattern($3>saveit)causesgawktoselectrecordsthatcontainauserIDnumbergreaterthanany
previoususerIDnumberthatithasprocessed.Eachtimeitselectsarecord,gawkassignsthevalueof
thenewuserIDnumbertothesaveitvariable.Thengawkusesthenewvalueofsaveittotesttheuser
IDsofallsubsequentrecords.Finallygawkadds1tothevalueofsaveitanddisplaystheresult.
$catfind_uid
BEGIN{FS=":"
saveit=0}
$3>saveit{saveit=$3}
END{print"NextavailableUIDis"saveit+1}
$gawk-ffind_uid/etc/passwd
NextavailableUIDis192
Thenextexampleproducesanotherreportbasedonthecarsfile.Thisreportusesnestedif...elsecontrol
structurestosubstitutevaluesbasedonthecontentsofthepricefield.Theprogramhasnopatternpart;it
processeseveryrecord.
$catprice_range
{
if($5<=5000)$5="inexpensive"
elseif(5000<$5&&$5<10000)$5="pleaseask"
elseif(10000<=$5)$5="expensive"
#
printf"%-10s%-8s%2d%5d%-12s\n",\
$1,$2,$3,$4,$5
}
$gawk-fprice_rangecars
plymfury197073inexpensive
chevymalibu199960inexpensive
fordmustang196545expensive
volvos801998102pleaseask
fordthundbd200315expensive
chevymalibu200050inexpensive
bmw325i1985115inexpensive
hondaaccord200130pleaseask
fordtaurus200410expensive
toyotarav42002180inexpensive
chevyimpala198585inexpensive
fordexplor200325pleaseask
Associativearrays
Nextthemanufassociativearrayusesthecontentsofthefirstfieldofeachrecordinthecarsfileasan
index.Thearrayiscomposedoftheelementsmanuf[plym],manuf[chevy],manuf[ford],andsoon.
Eachnewelementisinitializedto0(zero)asitiscreated.TheClanguageoperator++incrementsthe
variablethatitfollows.
TheactionfollowingtheENDpatternisthespecialforstructurethatloopsthroughtheelementsofan
associativearray.Apipesendstheoutputthroughsorttoproduceanalphabeticallistofcarsandthe
quantitiesinstock.Becauseitisashellscriptandnotagawkprogramfile,youmusthavebothreadand
executepermissiontothemanuffiletoexecuteitasacommand.DependingonhowthePATHvariable
(page284)isset,youmayhavetoexecutethescriptas./manuf.
$catmanuf
gawk'{manuf[$1]++}
END{for(nameinmanuf)printname,manuf[name]}
'cars|
sort
$manuf
bmw1
chevy3
ford4
honda1
plym1
toyota1
volvo1
Thenextprogram,namedmanuf.sh,isamoregeneralshellscriptthatincludessomeerrorchecking.This
scriptlistsandcountsthecontentsofacolumninafile,withboththecolumnnumberandthenameofthe
filebeingspecifiedonthecommandline.
Thefirstaction(theonethatstartswith{count)usestheshellvariable$1inthemiddleofthegawk
programtospecifyanarrayindex.Becauseofthewaythesinglequotationmarksarepaired,the$1that
appearstobewithinsinglequotationmarksisactuallynotquoted:Thetwoquotedstringsinthegawk
programsurround,butdonotinclude,the$1.Becausethe$1isnotquoted,andbecausethisisashell
script,theshellsubstitutesthevalueofthefirstcommandlineargumentinplaceof$1(page481).Asa
resultthe$1isinterpretedbeforethegawkcommandisinvoked.Theleadingdollarsign(theonebefore
thefirstsinglequotationmarkonthatline)causesgawktointerpretwhattheshellsubstitutesasafield
number.
$catmanuf.sh
if[$#!=2]
then
echo"Usage:manuf.shfieldfile"
exit1
fi
gawk<$2'
{count[$'$1']++}
END{for(itemincount)printf"%-20s%-20s\n",\
item,count[item]}'|
sort
$manuf.sh
Usage:manuf.shfieldfile
$manuf.sh1cars
bmw1
chevy3
ford4
honda1
plym1
toyota1
volvo1
$manuf.sh3cars
19651
19701
19852
19981
19991
20001
20011
20021
20032
20041
Awayaroundthetrickyuseofquotationmarksthatallowparameterexpansionwithinthegawkprogram
istousethevoptiononthecommandlinetopassthefieldnumbertogawkasavariable.Thischange
makesiteasierforsomeoneelsetoreadanddebugthescript.Youcallthemanuf2.shscriptthesameway
youcallmanuf.sh:
$catmanuf2.sh
if[$#!=2]
then
echo"Usage:manuf.shfieldfile"
exit1
fi
gawk-v"field=$1"<$2'
{count[$field]++}
END{for(itemincount)printf"%-20s%-20s\n",\
item,count[item]}'|
sort
Theword_usagescriptdisplaysawordusagelistforafileyouspecifyonthecommandline.TheTR
utility(page804)liststhewordsfromstandardinput,onetoaline.Thesortutilityordersthefile,with
themostfrequentlyusedwordsfirst.Thisscriptsortsgroupsofwordsthatareusedthesamenumberof
timesinalphabeticalorder.
$catword_usage
tr-cs'a-zA-Z''[\n*]'<$1|
gawk'
{count[$1]++}
END{for(itemincount)printf"%-15s%3s\n",item,count[item]}'
|
sort+1nr+0f-1
$word_usagetextfile
the42
file29
fsck27
system22
you22
to21
it17
SIZE14
and13
MODE13
...
Followingisasimilarprograminadifferentformat.ThestylemimicsthatofaCprogramandmaybe
easiertoreadandworkwithformorecomplexgawkprograms:
$catword_count
tr-cs'a-zA-Z''[\n*]'<$1|
gawk'{
count[$1]++
}
END{
for(itemincount)
{
if(count[item]>4)
{
printf"%-15s%3s\n",item,count[item]
}
}
}'|
sort+1nr+0f-1
Thetailutilitydisplaysthelasttenlinesofoutput,illustratingthatwordsoccurringfewerthanfive
timesarenotlisted:
$word_counttextfile|tail
directories5
if5
information5
INODE5
more5
no5
on5
response5
this5
will5
Thenextexampleshowsonewaytoputadateonareport.Thefirstlineofinputtothegawkprogram
comesfromdate.Theprogramreadsthislineasrecordnumber1(NR==1),processesitaccordingly,
andprocessesallsubsequentlineswiththeactionassociatedwiththenextpattern(NR>1).
$catreport
if(test$#=0)then
echo"Youmustsupplyafilename."
exit1
fi
(date;cat$1)|
gawk'
NR==1{print"Reportfor",$1,$2,$3","$6}
NR>1{print$5"\t"$1}'
$reportcars
ReportforMonJan31,2005
2500plym
3000chevy
10000ford
9850volvo
10500ford
3500chevy
450bmw
6000honda
17000ford
750toyota
1550chevy
9500ford
Thenextexamplesumseachofthecolumnsinafileyouspecifyonthecommandline;ittakesitsinput
fromthenumbersfile.Theprogramperformserrorchecking,reportingonanddiscardingrowsthat
containnonnumericentries.Itusesthenextcommand(withthecommentskipbadrecords)toskipthe
restofthecommandsforthecurrentrecordiftherecordcontainsanonnumericentry.Attheendofthe
program,gawkdisplaysagrandtotalforthefile.
$catnumbers
102030.340.5
203045.766.1
30xyz5070
4075107.255.6
502030.340.5
603045.O66.1
701134.75070
8075107.255.6
9017630.340.5
1001027.4545.766.1
1101235057a.5
12075107.255.6
$cattally
gawk'BEGIN{
ORS=""
}
NR==1{#firstrecordonly
nfields=NF#setnfieldsto
numberof
}#fieldsinthe
record(NF)
{
if($0~/[^0-9.\t]/)#checkeachrecord
toseeifitcontains
{#anycharacters
thatarenotnumbers,
print"\nRecord"NR"skipped:\n\t"#periods,spaces,
orTABs
print$0"\n"
next#skipbadrecords
}
else
{
for(count=1;count<=nfields;count++)#forgoodrecords
loopthroughfields
{
printf"%10.2f",$count>"tally.out"
sum[count]+=$count
gtotal+=$count
}
print"\n">"tally.out"
}
}
END{#afterprocessing
lastrecord
for(count=1;count<=nfields;count++)#printsummary
{
print"-------">"tally.out"
}
print"\n">"tally.out"
for(count=1;count<=nfields;count++)
{
printf"%10.2f",sum[count]>"tally.out"
}
print"\n\nGrandTotal"gtotal"\n">"tally.out"
}'<numbers
$tally
Record3skipped:
30xyz5070
Record6skipped:
603045.O66.1
Record11skipped:
1101235057a.5
$cattally.out
10.0020.0030.3040.50
20.0030.0045.7066.10
40.0075.00107.2055.60
50.0020.0030.3040.50
70.001134.7050.0070.00
80.0075.00107.2055.60
90.00176.0030.3040.50
100.001027.4545.7066.10
120.0075.00107.2055.60
----------------------------
580.002633.15553.90490.50
GrandTotal4257.55
Thenextexamplereadsthepasswdfile,listinguserswhodonothavepasswordsanduserswhohave
duplicateuserIDnumbers.(Thepwckutilityperformssimilarchecks.)
$cat/etc/passwd
bill::102:100:ext123:/home/bill:/bin/bash
roy:x:104:100:ext475:/home/roy:/bin/bash
tom:x:105:100:ext476:/home/tom:/bin/bash
lynn:x:166:100:ext500:/home/lynn:/bin/bash
mark:x:107:100:ext112:/home/mark:/bin/bash
sales:x:108:100:ext102:/m/market:/bin/bash
anne:x:109:100:ext355:/home/anne:/bin/bash
toni::164:100:ext357:/home/toni:/bin/bash
ginny:x:115:100:ext109:/home/ginny:/bin/bash
chuck:x:116:100:ext146:/home/chuck:/bin/bash
neil:x:164:100:ext159:/home/neil:/bin/bash
rmi:x:118:100:ext178:/home/rmi:/bin/bash
vern:x:119:100:ext201:/home/vern:/bin/bash
bob:x:120:100:ext227:/home/bob:/bin/bash
janet:x:122:100:ext229:/home/janet:/bin/bash
maggie:x:124:100:ext244:/home/maggie:/bin/bash
dan::126:100::/home/dan:/bin/bash
dave:x:108:100:ext427:/home/dave:/bin/bash
mary:x:129:100:ext303:/home/mary:/bin/bash
$catpasswd_check
gawk</etc/passwd'BEGIN{
uid[void]=""#tellgawkthatuidis
anarray
}
{#nopatternindicates
processallrecords
dup=0#initializeduplicate
flag
split($0,field,":")#splitintofields
delimitedby":"
if(field[2]=="")#checkfornull
passwordfield
{
if(field[5]=="")#checkfornullinfo
field
{
printfield[1]"hasnopassword."
}
else
{
printfield[1]"("field[5]")hasnopassword."
}
}
for(nameinuid)#loopthroughuid
array
{
if(uid[name]==field[3])#checkforseconduse
ofUID
{
printfield[1]"hasthesameUIDas"name":UID="
uid[name]
dup=1#setduplicateflag
}
}
if(!dup)#sameasif(dup==0)
#assignUIDandlogin
nametouidarray
{
uid[field[1]]=field[3]
}
}'
$passwd_check
bill(ext123)hasnopassword.
toni(ext357)hasnopassword.
neilhasthesameUIDastoni:UID=164
danhasnopassword.
davehasthesameUIDassales:UID=108
Thenextexampleshowsacompleteinteractiveshellscriptthatusesgawktogenerateareportonthe
carsfilebasedonpriceranges:
$catlist_cars
trap'rm-f$$.tem>/dev/null;echo$0aborted.;exit1'1215
echo-n"Pricerange(forexample,50007500):"
readlowrangehirange
echo'
Miles
MakeModelYear(000)Price
--------------------------------------------------'>$$.tem
gawk<cars'
$5>='$lowrange'&&$5<='$hirange'{
if($1~/ply/)$1="plymouth"
if($1~/chev/)$1="chevrolet"
printf"%-10s%-8s%2d%5d$%8.2f\n",$1,$2,$3,
$4,
$5
}'|sort-n+5>>$$.tem
cat$$.tem
rm$$.tem
$list_cars
Pricerange(forexample,50007500):30008000
Miles
MakeModelYear(000)Price
--------------------------------------------------
chevroletmalibu199960$3000.00
chevroletmalibu200050$3500.00
hondaaccord200130$6000.00
$list_cars
Pricerange(forexample,50007500):02000
Miles
MakeModelYear(000)Price
--------------------------------------------------
bmw325i1985115$450.00
toyotarav42002180$750.00
chevroletimpala198585$1550.00
$list_cars
Pricerange(forexample,50007500):15000100000
Miles
MakeModelYear(000)Price
--------------------------------------------------
fordtaurus200410$17000.00

optional:AdvancedGawkProgramming
ThissectiondiscussessomeoftheadvancedfeaturesthattheGNUdevelopersaddedwhentheyrewroteawktocreategawk.It
covershowtocontrolinputusingthegetlinestatement,howtouseacoprocesstoexchangeinformationbetweengawkanda
programrunninginthebackground,andhowtouseacoprocesstoexchangedataoveranetwork.
getline:CONTROLLINGINPUT
Thegetlinestatementgivesyoumorecontroloverthedatagawkreadsthanothermethodsofinputdo.Whenyougiveavariable
nameasanargumenttogetline,itreadsdataintothatvariable.TheBEGINblockoftheg1programusesgetlinetoreadoneline
intothevariableaafromstandardinput:
$catg1
BEGIN{
getlineaa
printaa
}
$echoaaaa|gawk-fg1
aaaa
Thealphafileisusedinthenextfewexamples:
$catalpha
aaaaaaaaa
bbbbbbbbb
ccccccccc
ddddddddd
Evenwheng1isgivenmorethanonelineofinput,itprocessesonlythefirstline:
$gawk-fg1<alpha
aaaaaaaaa
Whengetlineisnotgivenanargument,itreadsinto$0andmodifiesthefieldvariables($1,$2,...):
$gawk'BEGIN{getline;print$1}'<alpha
aaaaaaaaa

Theg2programusesawhileloopintheBEGINblocktoloopoverthelinesinstandardinput.Thegetlinestatementreadseach
lineintoholdmeandprintoutputseachvalueofholdme.
$catg2
BEGIN{
while(getlineholdme)
printholdme
}
$gawk-fg2<alpha
aaaaaaaaa
bbbbbbbbb
ccccccccc
ddddddddd
Theg3programdemonstratesthatgawkautomaticallyreadseachlineofinputinto$0whenithasstatementsinitsbody(andnot
justaBEGINblock).Thisprogramoutputstherecordnumber(NR),thestring$0:,andthevalueof$0(thecurrentrecord)for
eachlineofinput.
$catg3
{printNR,"$0:",$0}
$gawk-fg3<alpha
1$0:aaaaaaaaa
2$0:bbbbbbbbb
3$0:ccccccccc
4$0:ddddddddd
Nextg4demonstratesthatgetlineworksindependentlyofgawk'sautomaticreadsand$0.Whengetlinereadsintoavariable,it
doesnotmodify$0nordoesitmodifyanyofthefieldsinthecurrentrecord($1,$2,...).Thefirststatementing4isthesameas
thestatementing3andoutputsthelinethatgawkhasautomaticallyread.Thegetlinestatementreadsthenextlineofinputinto
thevariablenamedaa.Thethirdstatementoutputstherecordnumber,thestringaa:,andthevalueofaa.Theoutputfromg4
showsthatgetlineprocessesrecordsindependentlyofgawk'sautomaticreads.
$catg4
{
printNR,"$0:",$0
getlineaa

printNR,"aa:",aa
}
$gawk-fg4<alpha
1$0:aaaaaaaaa
2aa:bbbbbbbbb
3$0:ccccccccc
4aa:ddddddddd
Theg5programoutputseachlineofinputexceptthatitskipslinesthatbeginwiththeletterb.Thefirstprintstatementoutputs
eachlinethatgawkreadsautomatically.Nextthe/^b/patternselectsalllinesthatbeginwithbforspecialprocessing.Theaction
usesgetlinetoreadthenextlineofinputintothevariablehold,outputsthestringskipthisline:followedbythevalueofhold,
andoutputsthevalueof$1.The$1holdsthevalueofthefirstfieldoftherecordthatgawkreadautomatically,nottherecordread
bygetline.ThefinalstatementdisplaysastringandthevalueofNR,thecurrentrecordnumber.Eventhoughgetlinedoesnot
change$0whenitreadsintoavariable,gawkincrementsNR.
$catg5
#printalllinesexceptthosereadwithgetline
{print"line#",NR,$0}
#iflinebeginswith"b"processitspecially
/^b/{
#usegetlinetoreadthenextlineintovariablenamedhold
getlinehold
#printvalueofhold
print"skipthisline:",hold
#$0isnotaffectedwhengetlinereadsintoavariable
#$1stillholdspreviousvalue
print"previouslinebeganwith:",$1
}
{
print">>>>finishedprocessingline#",NR
print""

}
$gawk-fg5<alpha
line#1aaaaaaaaa
>>>>finishedprocessingline#1
line#2bbbbbbbbb
skipthisline:ccccccccc
previouslinebeganwith:bbbbbbbbb
>>>>finishedprocessingline#3
line#4ddddddddd
>>>>finishedprocessingline#4
COPROCESS:TWO-WAYI/O
Acoprocessisaprocessthatrunsinparallelwithanotherprocess.Startingwithversion3.1,gawkcaninvokeacoprocessto
exchangeinformationdirectlywithabackgroundprocess.Acoprocesscanbeusefulwhenyouareworkinginaclient/server
environment,settingupanSQL(902)frontend/backend,orexchangingdatawitharemotesystemoveranetwork.Thegawk
syntaxidentifiesacoprocessbyprecedingthenameoftheprogramthatstartsthebackgroundprocesswitha|&operator.
Thecoprocesscommandmustbeafilter(i.e.,itreadsfromstandardinputandwritestostandardoutput)andmustflushits
outputwheneverithasacompletelineratherthanaccumulatinglinesforsubsequentoutput.Whenacommandisinvokedasa
coprocess,itisconnectedviaatwo-waypipetoagawkprogramsothatyoucanreadfromandwritetothecoprocess.
to_upper
WhenusedalonetheTRutility(page804)doesnotflushitsoutputaftereachline.Theto_uppershellscriptisawrapperfortr
thatdoesflushitsoutput;thisfiltercanberunasacoprocess.Foreachlineread,to_upperwritestheline,translatedto
uppercase,tostandardoutput.Removethe#beforesetxifyouwantto_uppertodisplaydebuggingoutput.
$catto_upper
#!/bin/bash
#set-x
whilereadarg
do
echo"$arg"|tr'[a-z]''[A-Z]'
done
$echoabcdef|to_upper

ABCDEF
Theg6programinvokesto_upperasacoprocess.Thisgawkprogramreadsstandardinputorafilespecifiedonthecommand
line,translatestheinputtouppercase,andwritesthetranslateddatatostandardoutput.
$catg6
{
print$0|&"to_upper"
"to_upper"|&getlinehold
printhold
}
$gawk-fg6<alpha
AAAAAAAAA
BBBBBBBBB
CCCCCCCCC
DDDDDDDDD
Theg6programhasonecompoundstatement,enclosedwithinbraces,comprisingthreestatements.Becausethereisnopattern,
gawkexecutesthecompoundstatementonceforeachlineofinput.
Inthefirststatement,print$0sendsthecurrentrecordtostandardoutput.The|&operatorredirectsstandardoutputtothe
programnamedto_upper,whichisrunningasacoprocess.Thequotationmarksaroundthenameoftheprogramarerequired.
Thesecondstatementredirectsstandardoutputfromto_uppertoagetlinestatement,whichcopiesitsstandardinputtothe
variablenamedhold.Thethirdstatement,printhold,sendsthecontentsoftheholdvariabletostandardoutput.
GETTINGINPUTFRO MANETWO RK
Buildingontheconceptofacoprocess,gawkcanexchangeinformationwithaprocessonanothersystemviaanIPnetwork
connection.Whenyouspecifyoneofthespecialfilenamesthatbeginswith/inet/,gawkprocessesyourrequestusinganetwork
connection.Theformatofthesespecialfilenamesis
/inet/protocol/local-port/remote-host/remote-port
whereprotocolisusuallytcpbutcanbeudp,local-portis0(zero)ifyouwantgawktopickaport(otherwiseitisthenumberof
theportyouwanttouse),remote-hostistheIPaddress(page882)orfullyqualifieddomainname(page876)oftheremotehost,
andremote-portistheportnumberontheremotehost.Insteadofaportnumberinlocal-portandremote-port,youcanspecifya
servicenamesuchashttporftp.
Theg7programreadsthecarsfilefromtheserveratwww.sobell.com;theauthorhassetupthisfileforyoutoexperimentwith.
Onwww.sobell.comthefileislocatedat/CMDREF1/code/chapter_12/cars.Thefirststatementing7assignsthespecialfilename
totheservervariable.ThefilenamespecifiesaTCPconnection,allowsthelocalsystemtoselectanappropriateport,and
connectstowww.sobell.comonport80.Youcanusehttpinplaceof80tospecifythestandardHTTPport.
ThesecondstatementusesacoprocesstosendaGETrequesttotheremoteserver.Thisrequestincludesthepathnameofthefile
gawkisrequesting.Awhileloopusesacoprocesstoredirectlinesfromtheservertogetline.Becausegetlinehasnovariable
nameasanargument,itsavesitsinputinthecurrentrecordbuffer$0.Thefinalprintstatementsendseachrecordtostandard

output.Experimentwiththisscript,replacingthefinalprintstatementwithgawkstatementsthatprocessthefile.
$catg7
BEGIN{
#setvariablenamedserver
#tospecialnetworkingfilename
server="/inet/tcp/0/www.sobell.com/80"
#usecoprocesstosendGETrequesttoremoteserver
print"GET/CMDREF1/code/chapter_12/cars"|&server
#whileloopusescoprocesstoredirect
#outputfromservertogetline
while(server|&getline)
print$0
}
$gawk-fg7
plymfury1970732500
chevymalibu1999603000
fordmustang19654510000
volvos8019981029850
...
ErrorMessages
Thefollowingexamplesshowsomeofthemorecommoncausesofgawkerrormessages(and
nonmessages).Theseexamplesarerununderbash.Whenyouusegawkwithtcsh,theerrormessages
fromtheshellwillbedifferent.
Thefirstexampleleavesthesinglequotationmarksoffthecommandline,sotheshellinterprets$3and$1
asshellvariables.Also,becausetherearenosinglequotationmarks,theshellpassesgawkfour
argumentsinsteadoftwo.
$gawk{print$3,$1}cars
gawk:cmd.line:2:(ENDOFFILE)
gawk:cmd.line:2:syntaxerror
Thenextcommandlineincludesatypo(prinnt)thatgawkdoesnotcatch.Insteadofissuinganerror
message,gawksimplydoesnotdoanythinguseful.
$gawk'$3>=83{prinnt$1}'cars
Thenextexamplehasnobracesaroundtheaction:
$gawk'/chevy/print$3,$1'cars
gawk:cmd.line:1:/chevy/print$3,$1
gawk:cmd.line:1:^syntaxerror
Thereisnoproblemwiththenextexample;gawkdidjustwhatyouaskedittodo(noneofthelinesinthe
filecontainsaz).
$gawk'/z/'cars
Thenextexampleshowsanimproperactionforwhichgawkdoesnotissueanerrormessage:
$gawk'{$3"madeby"$1}'cars
Thefollowingexampledoesnotdisplaytheheadingbecausethereisnobackslashaftertheprint
commandintheBEGINblock.ThebackslashisneededtoquotethefollowingNEWLINEsothattheline
canbecontinued.Withoutit,gawkseestwoseparatestatements;theseconddoesnothing.
$catprint_cars
BEGIN{print
"ModelYearPrice"}
/chevy/{printf"%5s\t%4d\t%5d\n",$2,$3,$5}
$gawk-fprint_carscars
malibu19993000
malibu20003500
impala19851550
Youmustusedoublequotationmarks,notsingleones,todelimitstrings.
$catprint_cars2
BEGIN{OFS='\t'}
$3~/5$/{print$3,$1,"$"$5}
$gawk-fprint_cars2cars
gawk:print_cars2:1:BEGIN{OFS='\t'}
gawk:print_cars2:1:^invalidchar'''inexpression
ChapterSummary
Thegawkutilityisapattern-scanningandprocessinglanguagethatsearchesoneormorefilestosee
whethertheycontainrecords(usuallylines)thatmatchspecifiedpatterns.Itprocesseslinesby
performingactions,suchaswritingtherecordtostandardoutputorincrementingacounter,eachtimeit
findsamatch.
Agawkprogramconsistsofoneormorelinescontainingapatternand/oractioninthefollowing
format:
pattern{action}
Thepatternselectslinesfromtheinput.Thegawkutilityperformstheactiononalllinesthatthepattern
selects.Ifaprogramlinedoesnotcontainapattern,gawkselectsalllinesintheinput.Ifaprogramline
doesnotcontainanaction,gawkcopiestheselectedlinestostandardoutput.
Agawkprogramcanusevariables,functions,arithmeticoperators,associativearrays,control
statements,andC'sprintfstatement.Advancedgawkprogrammingtakesadvantageofgetlinestatements
tofine-tuneinput,coprocessestoenablegawktoexchangedatawithotherprograms,andnetwork
connectionstoexchangedatawithprogramsrunningonremotesystemsonanetwork.
Exercises
1. Writeagawkprogramthatnumberseachlineinafileandsendsitsoutputtostandardoutput.
2. Writeagawkprogramthatdisplaysthenumberofcharactersinthefirstfieldfollowedbythefirstfieldandsendsitsoutputtostandard
output.
3. Writeagawkprogramthatusesthecarsfile(page537),displaysallcarspricedatmorethan$5000,andsendsitsoutputtostandard
output.
4. Usegawktodeterminehowmanylinesin/etc/termcapcontainthestringvt100.Verifyyouranswerusinggrep.
AdvancedExercises
5. Experimentwithpgawk.Whatdoesitdo?Howcanitbeuseful?
6. Writeagawkprogramnamednet_listthatreadsfromthecarsfileonwww.sobell.com(see"GettingInputfromaNetwork"onpage
558)anddisplaysalistofeachofthecars'make,model,andprice.SeparatetheoutputfieldswithTABs.
7. Expandthenet_listprogramdevelopedinexercise6touseto_upper(page557)asacoprocesstodisplaythelistofcarswithonlythe
makeofthecarsinuppercase.Themodelandsubsequentfieldsoneachlineshouldappearastheydointhecarsfile.
8. Howcanyougetgawktoneatlyformatthatis"prettyprint"agawkprogramfile?(Hint:Seethegawkmanpage.)
Chapter13.ThesedEditor
INTHISCHAPTER
Syntax564
Arguments564
Options564
EditorBasics565
Addresses565
Instructions566
ControlStructures567
ThePatternSpaceandtheHoldSpace568
Examples568
Thesed(streameditor)utilityisabatch(noninteractive)editor.Ittransformsaninputstreamthatcan
comefromafileorstandardinput.Itisfrequentlyusedasafilterinapipe.Becauseitmakesonlyone
passthroughitsinput,sedismoreefficientthananinteractiveeditorsuchased.Thischapterdescribes
GNUsed.
Syntax
Asedcommandlinehasthefollowingsyntax:
sed[n]program[file-list]
sed[n]fprogram-file[file-list]
Thesedutilitytakesitsinputfromfilesyouspecifyonthecommandlineorfromstandardinput.Unless
youdirectoutputfromsedelsewhere,itgoestostandardoutput.
Arguments
Theprogramisasedprogramthatisincludedonthecommandline.Thisformatallowsyoutowrite
simple,shortsedprogramswithoutcreatingaseparateprogram-file.Theprogram-fileisthepathname
ofafilecontainingasedprogram(see"EditorBasics").Thefile-listcontainspathnamesoftheordinary
filesthatsedprocesses.Thesearetheinputfiles.Whenyoudonotspecifyafile,sedtakesitsinput
fromstandardinput.
Options
fileprogram-file
fprogram-file
Causessedtoreaditsprogramfromthefilenamedprogram-file
insteadoffromthecommandline.Youcanusethisoptionmorethan
onceonthecommandline.
in-place[=suffix]
i[suffix]
Editsfilesinplace.Withoutthisoptionsedsendsitsoutputtostandard
output.Withthisoptionsedreplacesthefileitisprocessingwithits
output.Whenyouspecifyasuffix,sedmakesabackupoftheoriginal
file.Thisbackuphastheoriginalfilenamewithsuffixappended.You
mustincludeaperiodinsuffixifyouwantaperiodtoappearbetween
theoriginalfilenameandsuffix.
help Summarizeshowtousesed.
quietor
silent n Causessednottocopylinestostandardoutputexceptasspecifiedby
thePrint(p)instructionorflag.
EditorBasics
Asedprogramconsistsofoneormorelineswiththefollowingsyntax:
[address[,address]]instruction[argument-list]
Theaddressesareoptional.Ifyouomittheaddress,sedprocessesalllinesfromtheinput.The
instructionistheeditinginstructionthatmodifiesthetext.Theaddressesselecttheline(s)thatthe
instructionpartofthecommandoperateson.Thenumberandkindsofargumentsintheargument-list
dependontheinstruction.Ifyouwanttoputseveralsedcommandsononelineyoucanseparatethe
commandswithsemicolons(;).
Thesedutilityprocessesinputasfollows:
1. Readsonelineofinputfromfile-listorstandardinput.
2. Readsthefirstinstructionfromtheprogramorprogram-file.Iftheaddress(es)selecttheinputline,
actsontheinputlineastheinstructionspecifies.
3. Readsthenextinstructionfromtheprogramorprogram-file.Iftheaddress(es)selecttheinputline,
actsontheinputline(possiblymodifiedbythepreviousinstruction)astheinstructionspecifies.
4. Repeatsstep3untilithasexecutedallinstructionsintheprogramorprogram-file.
5. Startsoveragainwithstep1ifthereisanotherlineofinput;otherwise,itisfinished.
Addresses
Alinenumberisanaddressthatselectsaline.Asaspecialcase,thelinenumber$representsthelastline
ofinput.
Aregularexpression(refertoAppendixA)isanaddressthatselectsthoselinescontainingastringthat
theregularexpressionmatches.Althoughslashesareoftenusedtodelimittheseregularexpressions,sed
permitsyoutouseanycharacterotherthanabackslashorNEWLINEforthispurpose.
Exceptasnoted,zero,one,ortwoaddresses(eitherlinenumbersorregularexpressions)canprecedean
instruction.Ifyoudonotuseanaddress,sedselectsalllines,causingtheinstructiontoactoneveryline
ofinput.Providingoneaddresscausestheinstructiontoactoneachinputlinethattheaddressselects.
Providingtwoaddressescausestheinstructiontoactongroupsoflines.Thefirstaddressselectsthefirst
lineinthefirstgroup.Thesecondaddressselectsthenextsubsequentlinethatitmatches;thislineisthe
lastlineinthefirstgroup.Ifnomatchforthesecondaddressisfound,thesecondaddresspointstothe

endofthefile.Afterselectingthelastlineinagroup,sedstartstheselectionprocessoveragain,looking
forthenextlinethatthefirstaddressmatches.Thislineisthefirstlineinthenextgroup.Thesedutility
continuesthisprocessuntilithasfinishedgoingthroughtheentirefile.
Instructions
d
(delete)TheDeleteinstructioncausessednottowriteoutthelinesitselectsandnotto
finishprocessingthelines.AftersedexecutesaDeleteinstruction,itreadsthenextinput
lineandbeginsoveragainwiththefirstinstructionfromtheprogramorprogram-file.
n
(next)TheNextinstructionwritesoutthecurrentlyselectedlineifappropriate,readsthe
nextinputline,andstartsprocessingthenewlinewiththenextinstructionfromthe
programorprogram-file.
a
(append)TheAppendinstructionappendsoneormorelinestothecurrentlyselectedline.
IfyouprecedeanAppendinstructionwithtwoaddresses,itappendstoeachlinethatis
selectedbytheaddresses;earlierversionsofseddidnotacceptAppendinstructionswith
twoaddresses.IfyoudonotprecedeanAppendinstructionwithanaddress,itappendsto
eachinputline.AnAppendinstructionhasthefollowingformat:
[address[,address]]a\
text\
text\
...
text
Youmustendeachlineofappendedtext,exceptthelast,withabackslash(thebackslashquotesthe
followingNEWLINE).Theappendedtextconcludeswithalinethatdoesnotendwithabackslash.The
sedutilityalwayswritesoutappendedtext,regardlessofwhetheryouuseanflagonthecommandline.
Itevenwritesoutthetextifyoudeletethelinetowhichyouareappendingthetext.
i(insert)TheInsertinstructionisidenticaltotheAppendinstructionexceptthatit
placesthenewtextbeforetheselectedline.
c
(change)TheChangeinstructionissimilartoAppendandInsertexceptthatitchanges
theselectedlinessothattheycontainthenewtext.Whenyouspecifyanaddress
range,Changereplacestheentirerangeoflineswithasingleoccurrenceofthenew
text.
s(substitute)TheSubstituteinstructioninsedissimilartothatinvim(page166).It
hasthefollowingformat:
[address[,address]]s/pattern/replacement-string
/[g][p][wfile]
Thepatternisaregularexpression(refertoAppendixA)thatisdelimitedbyany
characterotherthanaSPACEorNEWLINE,traditionallyaslash(/).The
replacement-stringstartsimmediatelyfollowingtheseconddelimiterandmustbe
terminatedbythesamedelimiter.Thefinal(third)delimiterisrequired.The
replacement-stringcancontainanampersand(&),whichsedreplaceswiththe
matchedpattern.Unlessyouusethegflag,theSubstituteinstructionreplacesonlythe
firstoccurrenceofthepatternoneachselectedline.
Theg(global)flagcausestheSubstituteinstructiontoreplaceallnonoverlapping
occurrencesofthepatternontheselectedlines.
Thep(print)flagcausessedtosendalllinesonwhichitmakessubstitutionsto
standardoutput.Thisflagoverridesthenoptiononthecommandline.
Thew(write)flagissimilartothepflagbutitsendsitsoutputtothefilespecifiedby
file.AsingleSPACEandthenameoftheoutputfilemustfollowawflag.
p
(print)ThePrintinstructionwritestheselectedlinestostandardoutput,writingthe
linesimmediately,anddoesnotreflecttheeffectsofsubsequentinstructions.This
instructionoverridesthenoptiononthecommandline.(Thenoptionpreventssed
fromcopyinglinestostandardoutput.)
wfile
(write)ThisinstructionissimilartothePrintinstructionexceptthatitsendsoutputto
thefilespecifiedbyfile.AsingleSPACEandthenameoftheoutputfilemustfollowa
Writeinstruction.
rfile
(read)TheReadinstructionreadsthecontentsofthespecifiedfileandappendsitto
theselectedline.AsingleSPACEandthenameoftheinputfilemustfollowaRead
instruction.
q(quit)TheQuitinstructioncausessedtoterminateimmediately.
ControlStructures
!
(NOT)Causessedtoapplythefollowinginstruction,locatedonthesameline,toeach
ofthelinesnotselectedbytheaddressportionoftheinstruction.Forexample,3!d
deletesalllinesexceptline3and$!pdisplaysalllinesexceptthelast.
{}
(groupinstructions)Whenyouencloseagroupofinstructionswithinapairof
braces,asingleaddress(oraddresspair)selectsthelinesonwhichthegroupof
instructionsoperates.Usesemicolons(;)toseparatemultiplecommandsappearingon
asingleline.
Branchinstructions
Thesedinfopageliststhebranchinstructionsas"Commandsforsedgurus"andsuggeststhatifyou
needthemyoumightbebetteroffwritingyourprograminawkorPerl.
:label Identifiesalocationwithinasedprogram.Thelabelisusefulasatargetforthe
bandtbranchinstructions.
b[label]
Unconditionallytransferscontrol(branches)tolabel.Withoutlabel,skipsthe
restoftheinstructionsforthecurrentlineofinputandreadsthenextlineof
input(page565).
t[label]
Transferscontrol(branches)tolabelonlyifaSubstituteinstructionhasbeen
successfulsincethemostrecentlineofinputwasread(conditionalbranch).
Withoutlabel,skipstherestoftheinstructionsforthecurrentlineofinputand
readsthenextlineofinput(page565).
ThePatternSpaceandtheHoldSpace
Thesedutilityhastwobuffers.ThecommandsrevieweduptothispointworkwiththePatternspace,
whichinitiallyholdsthelineofinputthatsedjustread.TheHoldspacecanholddatawhileyou
manipulatedatainthePatternspace;itisatemporarybuffer.UntilyouplacedataintheHoldspaceitis
empty.ThissectiondiscussescommandsthatmovedatabetweenthePatternspaceandtheHoldspace.
gCopiesthecontentsoftheHoldspacetothePatternspace.Theoriginalcontentsofthe
Patternspaceislost.
GAppendsaNEWLINEandthecontentsoftheHoldspacetothePatternspace.
hCopiesthecontentsofthePatternspacetotheHoldspace.Theoriginalcontentsofthe
Holdspaceislost.
HAppendsaNEWLINEandthecontentsofthePatternspacetotheHoldspace.
xExchangesthecontentsofthePatternspaceandtheHoldspace.
Examples
newdatafile Thefollowingexamplesusetheinputfilenew:
$catnew
Lineone.
Thesecondline.
Thethird.
Thisislinefour.
Five.
Thisisthesixthsentence.
Thisislineseven.
Eighthandlast.
Unlessyouinstructitnotto,sedsendsalllinesselectedornottostandardoutput.Whenyouusethen
optiononthecommandline,sedsendsonlycertainlines,suchasthoseselectedbyaPrint(p)
instruction,tostandardoutput.
Thefollowingcommandlinedisplaysallthelinesinthenewfilethatcontainthewordline(all
lowercase).Inaddition,becausethereisnonoption,seddisplaysallthelinesofinput.Asaresultthe
linesthatcontainthewordlinearedisplayedtwice.
$sed'/line/p'new
Lineone.
Thesecondline.
Thesecondline.
Thethird.
Thisislinefour.
Thisislinefour.
Five.
Thisisthesixthsentence.
Thisislineseven.
Thisislineseven.
Eighthandlast.
Thecommandusestheaddress/line/,aregularexpressionthatisasimplestring.Thesedutilityselects
eachofthelinesthatcontainsamatchforthatpattern.ThePrint(p)instructiondisplayseachofthe
selectedlines.
Thefollowingcommandusesthenoptionsothatseddisplaysonlytheselectedlines:
$sed-n'/line/p'new
Thesecondline.
Thisislinefour.
Thisislineseven.
Nextseddisplayspartofafilebasedonlinenumbers.ThePrintinstructionselectsanddisplayslines3
through6.
$sed-n'3,6p'new
Thethird.
Thisislinefour.
Five.
Thisisthesixthsentence.
ThenextcommandlineusestheQuitinstructiontocausesedtodisplayonlythebeginningofafile.In
thiscaseseddisplaysthefirstfivelinesofnewjustasahead5newcommandwould.
$sed'5q'new
Lineone.
Thesecondline.
Thethird.
Thisislinefour.
Five.
program-file
Whenyouneedtogivesedmorecomplexorlengthyinstructions,youcanuseaprogram-file.The
print3_6programperformsthesamefunctionasthecommandlineinapreviousexample.Thefoption
tellssedthatitshouldreaditsprogramfromthefilenamedonthecommandline.
$catprint3_6
3,6p
$sed-n-fprint3_6new
Thethird.
Thisislinefour.
Five.
Thisisthesixthsentence.
Append
Thenextprogramselectsline2andusesanAppendinstructiontoappendaNEWLINEandthetext
AFTER.totheselectedline.Becausethecommandlinedoesnotincludethenoption,sedcopiesallthe
linesfromtheinputfilenew.
$catappend_demo
2a\
AFTER.
$sed-fappend_demonew
Lineone.
Thesecondline.
AFTER.
Thethird.
Thisislinefour.
Five.
Thisisthesixthsentence.
Thisislineseven.
Eighthandlast.
Insert
Theinsert_demoprogramselectsallthelinescontainingthestringThisandinsertsaNEWLINEandthe
textBEFORE.beforetheselectedlines.
$catinsert_demo
/This/i\
BEFORE.
$sed-finsert_demonew
Lineone.
Thesecondline.
Thethird.
BEFORE.
Thisislinefour.
Five.
BEFORE.
Thisisthesixthsentence.
BEFORE.
Thisislineseven.
Eighthandlast.
Change
ThenextexampledemonstratesaChangeinstructionwithanaddressrange.Whenyouspecifyarangeof
linesforaChangeinstruction,itdoesnotchangeeachlinewithintherangebutratherchangestheblockof
linestoasingleoccurrenceofthenewtext.
$catchange_demo
2,4c\
SEDWILLINSERTTHESE\
THREELINESINPLACE\
OFTHESELECTEDLINES.
$sed-fchange_demonew
Lineone.
SEDWILLINSERTTHESE
THREELINESINPLACE
OFTHESELECTEDLINES.
Five.
Thisisthesixthsentence.
Thisislineseven.
Eighthandlast.
Substitute
ThenextexampledemonstratesaSubstituteinstruction.Thesedutilityselectsalllinesbecausethe
instructionhasnoaddress.Oneachlinesubs_demoreplacesthefirstoccurrenceoflinewithsentence.
Thepflagdisplayseachlinewhereasubstitutionoccurs.Thecommandlinecallssedwiththenoption,
soseddisplaysonlythelinesthattheprogramexplicitlyrequestsittodisplay.
$catsubs_demo
s/line/sentence/p
$sed-n-fsubs_demonew
Thesecondsentence.
Thisissentencefour.
Thisissentenceseven.
Thenextexampleissimilartotheprecedingoneexceptthatawflagandfilename(temp)attheendofthe
Substituteinstructioncausesedtocreatethefilenamedtemp.Thecommandlinedoesnotincludethen
option,soitdisplaysalllinesinadditiontowritingthechangedlinestotemp.Thecatutilitydisplays
thecontentsofthefiletemp.ThewordLine(startingwithanuppercaseL)isnotchanged.
$catwrite_demo1
s/line/sentence/wtemp
$sed-fwrite_demo1new
Lineone.
Thesecondsentence.
Thethird.
Thisissentencefour.
Five.
Thisisthesixthsentence.
Thisissentenceseven.
Eighthandlast.
$cattemp
Thesecondsentence.
Thisissentencefour.
Thisissentenceseven.
ThefollowingbashscriptchangesalloccurrencesofREPORTtoreport,FILEtofile,andPROCESS
toprocessinagroupoffiles.Becauseitisashellscriptandnotasedprogramfile,youmusthaveread
andexecutepermissiontothesubfiletoexecuteitasacommand(page263).Theforstructure(page
451)loopsthroughthelistoffilessuppliedonthecommandline.Asitprocesseseachfile,thescript
displayseachfilenamebeforeprocessingthefilewithsed.Thisprogramusesmultilineembeddedsed
commands.BecausetheNEWLINEsbetweenthecommandsarequoted(placedbetweensinglequotation
marks),sedacceptsmultiplecommandsonasingle,extendedcommandline(withinashellscript).Each
Substituteinstructionincludesag(global)flagtotakecareofthecasewhereastringoccursmorethan
onetimeonaline.
$catsub
forfile
do
echo$file
mv$file$$.subhld
sed's/REPORT/report/g
s/FILE/file/g
s/PROCESS/process/g'$$.subhld>$file
done
rm$$.subhld
$subfile1file2file3
file1
file2
file3
Inthenextexample,aWriteinstructioncopiespartofafiletoanotherfile(temp2).Thelinenumbers2
and4,separatedbyacomma,selecttherangeoflinessedistocopy.Thisprogramdoesnotalterthe
lines.
$catwrite_demo2
2,4wtemp2
$sed-n-fwrite_demo2new
$cattemp2
Thesecondline.
Thethird.
Thisislinefour.
Theprogramwrite_demo3isverysimilartowrite_demo2butprecedestheWriteinstructionwiththe
NOToperator(!),causingsedtowritetothefilethoselinesnotselectedbytheaddress.
$catwrite_demo3
2,4!wtemp3
$sed-n-fwrite_demo3new
$cattemp3
Lineone.
Five.
Thisisthesixthsentence.
Thisislineseven.
Eighthandlast.
ThefollowingexampledemonstratestheNextinstruction.Whenitprocessestheselectedline(line3),
sedimmediatelystartsprocessingthenextlinewithoutdisplayingline3.
$catnext_demo1
3n
p
$sed-n-fnext_demo1new
Lineone.
Thesecondline.
Thisislinefour.
Five.
Thisisthesixthsentence.
Thisislineseven.
Eighthandlast.
Thenextexampleusesatextualaddress.Thesixthlinecontainsthestringthe,sotheNextinstruction
causessednottodisplayit.
$catnext_demo2
/the/n
p
$sed-n-fnext_demo2new
Lineone.
Thesecondline.
Thethird.
Thisislinefour.
Five.
Thisislineseven.
Eighthandlast.
Thenextsetofexamplesusesthefilecompound.intodemonstratehowsedinstructionsworktogether.
$catcompound.in
1.Thewordsonthispage...
2.Thewordsonthispage...
3.Thewordsonthispage...
4.Thewordsonthispage...
Thefollowingexamplesubstitutesthestringwordswithtextonlines1,2,and3andthestringtextwith
TEXTonlines2,3,and4.Theexamplealsoselectsanddeletesline3.Theresultistextonline1,
TEXTonline2,noline3,andwordsonline4.Thesedutilitymadetwosubstitutionsonlines2and3:
textforwordsandTEXTfortext.Thenseddeletedline3.
$catcompound
1,3s/words/text/
2,4s/text/TEXT/
3d
$sed-fcompoundcompound.in
1.Thetextonthispage...
2.TheTEXTonthispage...
4.Thewordsonthispage...
Theorderingofinstructionswithinasedprogramiscritical.BothSubstituteinstructionsareappliedto
thesecondlineinthefollowingexample,asinthepreviousexample,buttheorderinwhichthe
substitutionsoccurchangestheresult.
$catcompound2
2,4s/text/TEXT/
1,3s/words/text/
3d
$sed-fcompound2compound.in
1.Thetextonthispage...
2.Thetextonthispage...
4.Thewordsonthispage...
Nextcompound3appendstwolinestoline2.Thesedutilitydisplaysallthelinesfromthefileonce
becausenonoptionappearsonthecommandline.ThePrintinstructionattheendoftheprogramfile
displaysline3anadditionaltime.
$catcompound3
2a\
Thisisline2a.\
Thisisline2b.
3p
$sed-fcompound3compound.in
1.Thewordsonthispage...
2.Thewordsonthispage...
Thisisline2a.
Thisisline2b.
3.Thewordsonthispage...
3.Thewordsonthispage...
4.Thewordsonthispage...
Thenextexampleshowsthatsedalwaysdisplaysappendedtext.Hereline2isdeletedbuttheAppend
instructionstilldisplaysthetwolinesthatwereappendedtoit.Appendedlinesaredisplayedevenifyou
usethenoptiononthecommandline.
$catcompound4
2a\
Thisisline2a.\
Thisisline2b.
2d
$sed-fcompound4compound.in
1.Thewordsonthispage...
Thisisline2a.
Thisisline2b.
3.Thewordsonthispage...
4.Thewordsonthispage...
Thenextexampleusesregularexpressionsintheaddresses.Theregularexpressioninthefollowing
instruction(^.)matchesonecharacteratthebeginningofeverylinethatisnotempty.Thereplacement
string(betweenthesecondandthirdslashes)containsabackslashescapesequencethatrepresentsaTAB
character(\t)followedbyanampersand(&).Theampersandtakesonthevalueofwhatevertheregular
expressionmatched.
$sed's/^./\t&/'new
Lineone.
Thesecondline.
Thethird.
...
Thistypeofsubstitutionisusefulforindentingafiletocreatealeftmargin.SeeAppendixAformore
informationonregularexpressions.
Youcanalsousethesimplerforms/^/\t/toaddTABstothebeginningsoflines.However,inadditionto
placingTABsatthebeginningoflineswithtextonthem,thisinstructionplacesaTABatthebeginningof
everyemptylinesomethingtheprecedingcommanddoesnotdo.
Youmaywanttoputtheprecedingsedinstructionintoashellscriptsothatyoudonothavetoremember
it(andretypeit)eachtimeyouwanttoindentafile.Thechmodutilitygivesyoureadandexecute
permissiontotheindfile.
$catind
sed's/^./\t&/'$*
$chmodu+rxind
$indnew
Lineone.
Thesecondline.
Thethird.
...
Stand-alonescript
Whenyouruntheprecedingshellscript,itcreatestwoprocesses:Itcallsashell,whichinturncallssed.
Youcaneliminatetheoverheadassociatedwiththeshellprocessbyputtingtheline#!/bin/sedf(page
265)atthestartofthescript,whichrunsthesedutilitydirectly.Youneedreadandexecutepermissionto
thefileholdingthescript.
$catind2
#!/bin/sed-f
s/^./\t&/
Inthefollowingsedprogram,theregularexpression(twoSPACEsfollowedby*$)matchesoneormore
SPACEsattheendofaline.ThisprogramremovestrailingSPACEsattheendsoflines,whichisuseful
forcleaningupfilesthatyoucreatedusingvim.
$catcleanup
sed's/*$//'$*
Thecleanup2scriptrunsthesamesedcommandascleanupbutstandsalone:Itcallsseddirectlywith
nointermediateshell.
$catcleanup2
#!/bin/sed-f
s/*$//
Holdspace
ThenextsedprogrammakesuseoftheHoldspacetoexchangepairsoflinesinafile.
$cats1
h#CopyPatternspace(linejustread)toHoldspace.
n#ReadthenextlineofinputintoPatternspace.
p#OutputPatternspace.
g#CopyHoldspacetoPatternspace.
p#OutputPatternspace(whichnowholdsthepreviousline).
$sed-nfs1new
Thesecondline.
Lineone.
Thisislinefour.
Thethird.
Thisisthesixthsentence.
Five.
Eighthandlast.
Thisislineseven.
Thecommandsinthes1programprocesspairsofinputlines.Thisprogramreadsalineandstoresit;
readsanotherlineanddisplaysit;andthenretrievesthestoredlineanddisplaysit.Afterprocessinga
pairoflinestheprogramstartsoverwiththenextpairoflines.
Thenextsedprogramaddsablanklineaftereachlineintheinputfile(i.e.,itdouble-spacesafile).
$sed'G'new
Lineone.
Thesecondline.
Thethird.
Thisislinefour.
$
TheGinstructionappendsaNEWLINEandthecontentsoftheHoldspacetothePatternspace.Unless
youputsomethingintheHoldspace,itisempty.ThustheGinstructioncopiesaNEWLINEtoeachline
ofinputbeforeseddisplaystheline(s)fromthePatternspace.
Thes2sedprogramreversestheorderofthelinesinafilejustasthetacutilitydoes.
$cats2
2,$G#Onallbutthefirstline,appendaNEWLINEandthe
#contentsoftheHoldspacetothePatternspace.
h#CopythePatternspacetotheHoldspace.
$!d#Deleteallexceptthelastline.
$sed-fs2new
Eighthandlast.
Thisislineseven.
Thisisthesixthsentence.
Five.
Thisislinefour.
Thethird.
Thesecondline.
Lineone.
Thisprogramincludesthreecommands:2,$G,h,and$!d.Tounderstandthisscriptitisimportantto
understandhowtheaddressofthelastcommandworks:The$istheaddressofthelastlineofinputand
the!negatestheaddress.Theresultisanaddressthatselectsallexceptthelastlineofinput.Inthesame
fashionyoucouldreplacethefirstcommandwith1!G:Selectallexceptthefirstlineforprocessing;the
resultswouldbethesame.
Hereiswhathappensass2processesthenewfile:
Thesedutilityreadsthefirstlineofinput(Lineone.)intothePatternspace.
1.
1. The2,$GdoesnotprocessthefirstlineofinputbecauseofitsaddresstheGinstructionstarts
processingatthesecondline.
2. ThehcopiesLineone.fromthePatternspacetotheHoldspace.
3. The$!ddeletesthecontentsofthePatternspace.BecausethereisnothinginthePatternspace,
seddoesnotdisplayanything.
2.
Thesedutilityreadsthesecondlineofinput(Thesecondline.)intothePatternspace.
1. The2,$GaddswhatisintheHoldspace(Lineone.)tothePatternspace.ThePatternspace
nowhasThesecondline.NEWLINELineone.
2. ThehcopieswhatisinthePatternspacetotheHoldspace.
3. The$!ddeletesthesecondlineofinput.Becauseitisdeleted,seddoesnotdisplayit.
3.
Thesedutilityreadsthethirdlineofinput(Thethird.)intothePatternspace.
1. The2,$GaddswhatisintheHoldspace(Thesecondline.NEWLINELineone.)tothePattern
space.ThePatternspacenowhasThethird.NEWLINEThesecondline.NEWLINELineone.
2. ThehcopieswhatisinthePatternspacetotheHoldspace.
3. The$!ddeletesthecontentsofthePatternspace.BecausethereisnothinginthePatternspace,
seddoesnotdisplayanything.
...
8.
Thesedutilityreadstheeighth(last)lineofinputintothePatternspace.
1. The2,$GaddswhatisintheHoldspacetothePatternspace.ThePatternspacenowhasallthe
linesfromnewinreverseorder.
2. ThehcopieswhatisinthePatternspacetotheHoldspace.Thisstepisnotnecessaryforthe
lastlineofinputbutdoesnotaltertheprogram'soutput.
3. The$!ddoesnotprocessthelastlineofinput.Becauseofitsaddressthedinstructiondoesnot
deletethelastline.
4. ThesedutilitydisplaysthecontentsofthePatternspace.
ChapterSummary
Thesed(streameditor)utilityisabatch(noninteractive)editor.Ittakesitsinputfromfilesyouspecify
onthecommandlineorfromstandardinput.Unlessyouredirecttheoutputfromsed,itgoestostandard
output.
Asedprogramconsistsofoneormorelineswiththefollowingsyntax:
[address[,address]]instruction[argument-list]
Theaddressesareoptional.Ifyouomittheaddress,sedprocessesalllinesofinput.Theinstructionis
theeditinginstructionthatmodifiesthetext.Theaddressesselecttheline(s)theinstructionpartofthe
commandoperateson.Thenumberandkindsofargumentsintheargument-listdependonthe
instruction.
Inadditiontobasicinstructions,sedincludessomepowerfuladvancedinstructions.Onesetofthese
instructionsallowssedprogramstostoredatatemporarilyinabuffercalledtheHoldspace.Other
instructionsprovideunconditionalandconditionalbranchinginsedprograms.

Exercises
1: Writeasedcommandthatcopiesafiletostandardoutput,removingalllinesthatbeginwiththewordToday.
2: WriteasedcommandthatcopiesonlythoselinesofafilethatbeginwiththewordTodaytostandardoutput.
3: Writeasedcommandthatcopiesafiletostandardoutput,removingallblanklines(lineswithnocharactersonthem).
4: Writeasedprogramnamedinsthatcopiesafiletostandardoutput,changingalloccurrencesofcattodogandprecedingeach
modifiedlinewithalinethatsaysfollowinglineismodified.
5: Writeasedprogramnameddivthatcopiesafiletostandardoutput,copiesthefirstfivelinestoafilenamedfirst,andcopiestherest
ofthefiletoafilenamedlast.
6:
Writeasedcommandthatcopiesafiletostandardoutput,replacingasingleSPACEasthefirstcharacteronalinewitha0(zero)only
iftheSPACEisimmediatelyfollowedbyanumber(09).Forexample:
abc abc
abc abc
85c 085c
55b 55b
000 0000
7: Howcanyouusesedtotriple-space(i.e.,addtwoblanklinesaftereachlinein)afile?
CommandReference
Thefollowingtableslisttheutilitiescoveredinthispartofthebookgroupedbyfunctionand
alphabeticallywithinfunction.Althoughmostofthesearetrueutilities(programsthatareseparatefrom
theshells),somearebuiltintotheshells(shellbuiltins).Thesampleutilityonpage588showstheformat
ofthedescriptionofeachutilityinthispartofthebook.

UtilitiesThatDisplayandManipulateFiles
aspell Checksafileforspellingerrorspage589
bzip2 Compressesordecompressesfilespage596
cat Joinsanddisplaysfilespage599
cmp Comparestwofilespage610
comm Comparessortedfilespage612
cp Copiesfilespage616
cpio Createsanarchiveorrestoresfilesfromanarchivepage619
cut Selectscharactersorfieldsfrominputlinespage627
dd Convertsandcopiesafilepage633
diff Displaysthedifferencesbetweentwofilespage638
find Findsfilesbasedoncriteriapage655
fmt Formatstextverysimplypage664
gawk Searchesforandprocessespatternsinafilepage527
grep Searchesforapatterninfilespage683
gzip Compressesordecompressesfilespage688
head Displaysthebeginningofafilepage691
less Displaystextfiles,onescreenatatimepage697
ln Makesalinktoafilepage702
lpr Sendsfilestoprinterspage705
ls Displaysinformationaboutoneormorefilespage708
man Displaysdocumentationforcommandspage721

mkdir Createsadirectorypage724
mv Renamesormovesafilepage732
od Dumpsthecontentsofafilepage737
paste Joinscorrespondinglinesfromfilespage742
pr Paginatesfilesforprintingpage744
rm Removesafile(deletesalink)page753
rmdir Removesadirectorypage755
sed Editsafile(notinteractively)page563
sort Sortsand/ormergesfilespage762
split Dividesafileintosectionspage771
strings Displaysstringsofprintablecharacterspage777
tail Displaysthelastpart(tail)ofafilepage783
tar Storesorretrievesfilesto/fromanarchivefilepage786
touch Changesafile'saccessand/ormodificationtimepage801
uniq Displaysuniquelinespage812
wc Displaysthenumberoflines,words,andbytespage816

NetworkUtilities
ftp Transfersfilesoveranetworkpage671
rcp Copiesoneormorefilestoorfromaremotesystempage750
rlogin Logsinonaremotesystempage752
rsh Executescommandsonaremotesystempage756
scp Securelycopiesoneormorefilestoorfromaremotesystempage758
ssh Securelyexecutescommandsonaremotesystempage773
telnet Connectstoaremotesystemoveranetworkpage792

UtilitiesThatDisplayandAlterStatus
cd Changestoanotherworkingdirectorypage601
chgrp Changesthegroupassociatedwithafilepage603
chmod Changestheaccessmode(permissions)ofafilepage604
chown Changestheownerofafileand/orthegroupthefileisassociatedwithpage608
date Displaysorsetsthesystemtimeanddatepage630
df Displaysdiskspaceusagepage636
du Displaysinformationondiskusagebyfilepage644
file Displaystheclassificationofafilepage653
finger Displaysinformationaboutuserspage661
kill TerminatesaprocessbyPIDpage693
killall Terminatesaprocessbynamepage695
nice Changesthepriorityofacommandpage734
nohup Runsacommandthatkeepsrunningafteryoulogoutpage736
ps Displaysprocessstatuspage746
sleep Createsaprocessthatsleepsforaspecifiedintervalpage760
stty Displaysorsetsterminalparameterspage778
top Dynamicallydisplaysprocessstatuspage798
umask Establishesthefile-creationpermissionsmaskpage810
wDisplaysinformationaboutsystemuserspage814
which ShowswhereinPATHacommandislocatedpage817
who Displaysinformationaboutlogged-inuserspage819

MiscellaneousUtilities
at Executescommandsataspecifiedtimepage593
cal Displaysacalendarpage598
crontab Maintainscrontabfilespage624
echo Displaysamessagepage647
expr Evaluatesanexpressionpage649
fsck Checksandrepairsafilesystempage666
mkfs Createsafilesystemonadevicepage725
Mtools UsesDOS-stylecommandsonfilesanddirectoriespage728
tee Copiesstandardinputtostandardoutputandoneormorefilespage791
test Evaluatesanexpressionpage794
TR Replacesspecifiedcharacterspage804
tty Displaystheterminalpathnamepage807
tune2fs Changesparametersonanext2orext3filesystempage808
xargs Convertsstandardinputintocommandlinespage821

StandardMultiplicativeSuffixes
SeveralutilitiesallowyoutousethesuffixeslistedinTableV-1followingbytecounts.Youcanprecede
amultiplicativesuffixwithanumberthatisamultiplier.Forexample,5Kmeans5x210.Theabsenceofa
multiplierindicatesthatthemultiplicativesuffixistobemultipliedby1.Theutilitiesthatallowthese
suffixesaremarkedassuch.
TableV-1.Multiplicativesuffixes
Suffix Multiplicativevalue Suffix Multiplicativevalue
KB 1,000(103)PB 1015
K1,024(210)P250
MB 1,000,000(106)EB 1018
M1,048,576(220)E260
GB 1,000,000,000(109)ZB 1021
G1,073,741,824(230)Z270
TB 1012 YB 1024
T240 Y280

CommonOptions
SeveralGNUutilitiessharetheoptionslistedinTableV-2.Theutilitiesthatusetheseoptionsaremarked
assuch.
TableV-2.Commoncommandlineoptions
Option Effect
Asinglehyphenappearinginplaceofafilenameindicatesthattheutility
willacceptstandardinputinplaceofthefile.
Adoublehyphenmarkstheendoftheoptionsonacommandline.You
canfollowthisoptionwithanargumentthatbeginswithahyphen.
Withoutthisoptiontheutilityassumesthatanargumentthatbeginswitha
hyphenisanoption.
help
Displaysahelpmessagefortheutility.Someofthesemessagesarequite
long;youcanpipetheoutputthroughlesstodisplayitonescreenata
time.Forexample,youcouldgivethecommandlshelp|less.
Alternativelyyoucanpipetheoutputthroughgrepifyouarelookingfor
specificinformation.Forexample,youcouldgivethefollowingcommand
togetinformationonthedoptiontols:lshelp|grepd.Seethe
precedingentryinthistableforinformationonthedoublehyphen.
version Displaysversioninformationfortheutility.
ThesampleUtility
Thefollowingdescriptionofthesampleutilityshowstheformatthatisusedtodescribetheutilitiesin
thispartofthebook.Thesedescriptionsaresimilartothemanpagedescriptions(pages30and721);
however,mostusersfindthedescriptionsinthisbookeasiertoreadandunderstand.Thesedescriptions
emphasizethemostusefulfeaturesoftheutilitiesandoftenleaveoutthemoreobscurefeatures.For
informationaboutthelesscommonlyusedfeatures,refertothemanandinfopagesorcalltheutility
withthehelpoption,whichworkswithmanyutilities.
sample:Verybriefdescriptionofwhattheutilitydoes
sample[options]arguments
Followingthesyntaxlineisadescriptionoftheutility.Thesyntaxlineshowshowtoruntheutilityfrom
thecommandline.Optionsandargumentsenclosedinbrackets([])arenotrequired.Typewordsthat
appearinthisitalictypefaceasis.Wordsthatyoumustsubstitutewhenyoutypeappearinthisbold
italictypeface.Wordslistedasargumentstoacommandidentifysinglearguments(forexample,source-
file)orgroupsofsimilararguments(forexample,directory-list).
Arguments
Thissectiondescribestheargumentsthatyoucanusewhenyouruntheutility.Theargumentitself,as
shownintheprecedingsyntaxline,isprintedinthisbolditalictypeface.
Options
Thissectionlistssomeoftheoptionsyoucanusewiththecommand.Unlessotherwisespecified,you
mustprecedeoptionswithoneortwohyphens.Mostcommandsacceptasinglehyphenbeforemultiple
options(page109).Optionsinthissectionareorderedalphabeticallybyshort(single-hyphen)options.If
anoptionhasonlyalongversion(twohyphens),itisorderedbyitslongoption.Followingaresome
sampleoptions:
make-dirs dThisoptionhasalongandashortversion.Youcanuse
eitheroption;theyareequivalent.
delimiter=dchar
ddchar
Thisoptionincludesanargument.Theargumentissetinabolditalictypefacein
boththeheadingandthedescription.Yousubstituteanotherword(filename,stringof
characters,orothervalue)foranyargumentsyouseeinthistypeface.Type
charactersthatareinboldtype(suchasthedelimiterandd)asis,letterforletter.
t
(tableofcontents)Thisisanexampleofasimpleoptionprecededbyasingle
hyphenandnotfollowedwithanyarguments.Ithasnolongversion.Thetableof
contentsappearinginparenthesesatthebeginningofthedescriptionisacue,
suggestiveofwhattheoptionletterstandsfor.
Discussion
Thisoptionalsectioncontainsadiscussionabouthowtousetheutilityandanyquirksitmayhave.
Notes
Thissectioncontainsmiscellaneousnotessomeimportantandothersmerelyinteresting.
Examples
Thissectioncontainsexamplesofhowtousetheutility.Thissectionistutorialandismorecasualthan
theprecedingsectionsofthedescription.
aspell:Checksafileforspellingerrors
aspellcheck[options]filename
aspelllist[options]<filename
aspellconfig
aspellhelp
Theaspellutilitychecksthespellingofwordsinadocumentagainstastandarddictionary.Youcanuse
aspellinteractively:Itdisplayseachmisspelledwordincontext,togetherwithamenuthatgivesyou
thechoiceofacceptingthewordasis,choosingoneofaspell'ssuggestedreplacementsfortheword,
insertingthewordintoyourpersonaldictionary,orreplacingthewordwithoneyouenter.Youcanalso
useaspellinbatchmodesothatitreadsfromstandardinputandwritestostandardoutput.
tip:aspellisnotlikeotherutilitiesregardingitsinput
Unlikemanyotherutilities,aspelldoesnotacceptinputfromstandardinputwhenyou
donotspecifyafilenameonthecommandline.Instead,theactionspecifieswhere
aspellgetsitsinput.
Action
Youmustchooseoneandonlyoneactionwhenyourunaspell.
check c
Runsaspellasaninteractivespellingchecker.Inputcomesfrom
asinglefilenamedonthecommandline.Referto"Discussion"on
page590.
config
Displaysaspell'sconfiguration,bothdefaultandcurrentvalues.
Sendtheoutputthroughapipetolessforeasierviewing,oruse
greptofindtheoptionyouarelookingfor(forexample,aspell
config|grepbackup).
help ?Displaysanextensivepageofhelp.Sendtheoutputthroughapipe
tolessforeasierviewing.
list lRunsaspellinbatchmode(noninteractively)withinputcoming
fromstandardinputandoutputgoingtostandardoutput.
Arguments
Thefilenameisthenameofthefileyouwanttocheck.Theaspellutilityacceptsthisargumentonly
whenyouusethecheck(c)action.Withthelist(l)action,inputmustcomefromstandardinput.
Options
Theaspellutilityhasmanyoptions.Afewofthemorecommonlyusedonesarelistedinthissection;
seethemanualforacompletelist.Defaultvaluesofmanyoptionsaredeterminedwhenaspellis
compiled(seetheconfigaction).
Youcanspecifyoptionsonthecommandline,invalueoftheASPELL_CONFshellvariable,orinyour
personalconfigurationfile(~/.aspell.conf).Superusercancreateaglobalconfigurationfile
(/etc/aspell.conf).Putoneoptionperlineinaconfigurationfile;separateoptionswithasemicolon(;)in
ASPELL_CONF.OptionsonthecommandlineoverridethoseinASPELL_CONF,whichoverride
thoseinyourpersonalconfigurationfile,whichoverridethoseintheglobalconfigurationfile.
Therearetwotypesofoptionsinthefollowinglist:Booleanandvalue.TheBooleanoptionsturna
featureon(enablethefeature)oroff(disablethefeature).PrecedeaBooleanoptionwithdonttoturnit
off.Forexample,ignore-caseturnstheignore-casefeatureonanddont-ignore-caseturnsitoff.
Valueoptionsassignavaluetoafeature.Followtheoptionwithanequalsignandavalueforexample,
ignore=4.
ForalloptionsinaconfigurationfileorintheASPELL_CONFvariable,droptheleadinghyphens
(ignore-caseordont-ignore-case).
caution:aspelloptionsandleadinghyphens
Thewayyouspecifyoptionsdiffersdependingonwhetheryouarespecifyingthemonthe
commandline,usingtheASPELL_CONFshellvariable,orinaconfigurationfile.
Onthecommandlineprefixlongoptionswithtwohyphens(forexample,ignore-caseor
dont-ignore-case).InASPELL_CONFandconfigurationfiles,droptheleadinghyphens
(forexample,ignore-caseordont-ignore-case).
dont-backup Doesnotcreateabackupfilenamedfilename.bak(defaultisbackup
whenactionischeck).
ignore=nIgnoreswordswithnorfewercharacters(defaultis1).
ignore-case Ignoresthecaseoflettersinwordsbeingchecked(defaultisdont-
ignore-case).
lang=cc Specifiesthetwo-letterlanguagecode(cc).Thelanguagecodedefaults
tothevalueofLC_MESSAGES(page291).
mode=mod
Specifiesafiltertouse.Selectmodfromurl(default),none,sgml,and
others.Themodesworkasfollows:url:skipsURLs,hostnames,and
emailaddresses;none:turnsoffallfilters;sgml:skipsSGML,HTML,
XHTML,andXMLcommands.
Removesaccentmarksfromallthewordsinthedictionarybefore

strip-accents checkingwords(defaultisdont-strip-accents).
Discussion
Theaspellutilityhastwobasicmodesofoperation:batchandinteractive.Youspecifybatchmodeby
usingthelistorlaction.Inbatchmodeaspelltakesthedocumentyouwanttocheckforspellingerrors
asstandardinputandsendsthelistofpotentiallymisspelledwordstostandardoutput.
Youspecifyinteractivemodebyusingthecheckorcaction.Ininteractivemodeaspelldisplaysa
screenwiththepotentiallymisspelledwordincontexthighlightedinthemiddleandamenuofchoicesat
thebottom.See"Examples"foranillustation.Themenuincludesvariouscommands(TableV-3)aswell
assomesuggestionsofsimilar,correctlyspelledwords.Youeitherenteroneofthenumbersfromthe
menutoselectasuggestedwordtoreplacethewordinquestionorenteralettertogiveacommand.
TableV-3.Commands
Command Action
SPACE Takesnoactionandgoesontonextthemisspelledword.
nReplacesthemisspelledwordwithsuggestedwordnumbern.
aAddsthe"misspelled"wordtoyourpersonaldictionary.
bAbortsaspell;doesnotsavechanges.
iorI(letter"i") Ignoresthemisspelledword.I(uppercase"I")ignoresalloccurrences
ofthisword;iignoresthisoccurrenceonlyandisthesameasSPACE.
l(lowercase"l") Shiftsthe"misspelled"wordtolowercaseandaddsittoyourpersonal
dictionary.
rorR
Replacesthemisspelledwordwiththewordthatyouenteratthe
bottomofthescreen.Rreplacesalloccurrencesofthisword;r
replacesthisoccurrenceonly.
xSavesthefileascorrectedsofarandexitsfromaspell.
Notes
Formoreinformationrefertothe/usr/share/doc/aspelldirectorywithmanualsintheman-htmlandman-
textsubdirectoriesandtotheaspellhomepagelocatedataspell.sourceforge.net.
Theaspellutilityisnotafoolproofwayoffindingspellingerrors.Italsodoesnotcheckformisused,
properlyspelledwords(suchasredinsteadofread).
Spellingfromemacs
Youcanmakeiteasytouseaspellfromemacsbyaddingthefollowinglinetoyour~/.emacsfile.
Thislinecausesemacs'ispellfunctionstocallaspell:
(setq-defaultispell-program-name"aspell")
Spellingfromvim
Similarly,youcanmakeiteasytouseaspellfromvimbyaddingthefollowinglinetoyour~/.vimrc
file:
map^T:w!<CR>:!aspellcheck%<CR>:e!%<CR>
Whenyouenterthislinein~/.vimrcusingvim,enterthe^TasCONTROL-VCONTROL-T(page159).
Withthislinein~/.vimrc,CONTROL-Tbringsupaspelltospellcheckthefileyouareeditingwith
vim.
Examples
Thefollowingexamplesuseaspelltocorrectthespellinginthememo.txtfile:
$catmemo.txt
Here'sadocumentfortehaspellutilitey
tocheck.Itobvioslyneedsproofing
quietbadly.
Thefirstexampleusesaspellwiththecheckactionandnooptions.Theappearanceofthescreenfor
thefirstmisspelledword,teh,isshown.Atthebottomofthescreenisthemenuofcommandsand
suggestedwords.Thenumberedwordseachdifferslightlyfromthemisspelledword:
$aspellcheckmemo.txt
Here'sadocumentfortehaspellutilitey
tocheck.Itobvioslyneedsproofing
quietbadly.
============================================================
1)the6)th
2)Te7)tea
3)tech8)tee
4)Th9)Ted
5)eh0)tel
i)IgnoreI)Ignoreall
r)ReplaceR)Replaceall
a)Addl)AddLower
b)Abortx)Exit
============================================================
?
Enteroneofthemenuchoicesinresponsetotheprecedingdisplay;aspellwilldoyourbiddingand
movethehighlighttothenextmisspelledword(unlessyouchoosetoabortorexit).
Thenextexampleusesthelistactiontodisplayalistofmisspelledwords.Thewordquietisnotinthe
listitisnotproperlyusedbutisproperlyspelled.
$aspelllist<memo.txt
teh
aspell
utilitey
obviosly
Thelastexamplealsousestheusesthelistaction.Itshowsaquickwaytocheckthespellingofaword
ortwowithasinglecommand.Theusergivestheaspelllistcommandandthenentersseperate
temperatureintoaspell'sstandardinput(thekeyboard).AftertheuserentersRETURNand
CONTROL-D(tomarktheendoffile),aspellwritesthemisspelledwordtostandardoutput(the
screen):
$aspelllist
seperatetemperatureRETURN
CONTROL-D
seperate
at:Executescommandsataspecifiedtime
at[options]time[date|+increment]
atq
atrmjob-list
batch[options][time]
Theatandbatchutilitiesexecutecommandsataspecifiedtime.Theyacceptcommandsfromstandard
inputor,withthefoption,fromafile.Commandsareexecutedinthesameenvironmentastheator
batchcommand.Unlessredirected,standardoutputandstandarderrorfromcommandsareemailedto
theuserwhoranatorbatch.Ajobisthegroupofcommandsthatisexecutedbyonecalltoat.The
batchutilitydiffersfromatinthatitschedulesjobssothattheyrunwhentheCPUloadonthesystem
islow.
Theatqutilitydisplaysalistofatjobsyouhavequeued;atrmcancelspendingatjobs.
Arguments
Thetimeisthetimeofdaythatatrunsthejob.Youcanspecifythetimeasaone-,two-,orfour-digit
number.One-andtwo-digitnumbersspecifyanhour,andfour-digitnumbersspecifyanhourandminute.
Youcanalsogivethetimeintheformhh:mm.Theatutilityassumesa24-hourclockunlessyouplace
amorpmimmediatelyafterthenumber,inwhichcaseitusesa12-hourclock.Youcanalsospecifytime
asnow,midnight,noon,orteatime(4:00PM).
Thedateisthedayoftheweekordayofthemonthonwhichyouwantattoexecutethejob.Whenyou
donotspecifyaday,atexecutesthejobtodayifthehouryouspecifyintimeisgreaterthanthecurrent
hour.Ifthehourislessthanthecurrenthour,atexecutesthejobtomorrow.
Youspecifyadayoftheweekbyspellingitoutorabbreviatingittothreeletters.Youcanalsousethe
wordstodayandtomorrow.Usethenameofamonthfollowedbythenumberofthedayinthemonthto
specifyadate.Youcanfollowthemonthanddaynumberwithayear.
Theincrementisanumberfollowedbyoneofthefollowing(pluralorsingularisallowed):minutes,
hours,days,orweeks.Theatutilityaddstheincrementtotime.Youcannotspecifyanincrementfora
date.
Whenusingatrm,job-listisalistofoneormoreatjobnumbers.Youcanlistjobnumbersbyrunning
atwiththeloptionorbyusingatq.
Options
Thelanddoptionsarenotforusewhenyouinitiateajobwithat.Youcanusethemonlytodetermine
thestatusofajobortocancelajob.
cjob-list (cat)Displaystheenvironmentandcommandsspecifiedbyjob-list.
djob-list
(delete)Cancelsjobsthatyoupreviouslysubmittedwithat.Thejob-list
argumentisalistofoneormoreatjobnumberstocancel.Ifyoudonot
rememberthejobnumber,usetheloptionorrunatqtolistyourjobsand
theirnumbers.Usingthisoptionwithatisthesameasrunningatrm.
ffile
(file)Specifiesthatcommandscomefromfileinsteadofstandardinput.
Thisoptionisusefulforlonglistsofcommandsorcommandsthatare
executedrepeatedly.
l(list)Displaysalistofyouratjobs.Usingthisoptionwithatisthesame
asrunningatq.
m
(mail)Sendsyouemailafterajobisrun,evenwhennothingissentto
standardoutputorstandarderror.Whenajobgeneratesoutput,atalways
emailsittoyou,regardlessofthisoption.
Notes
Theshellsavestheenvironmentvariablesandtheworkingdirectoryatthetimeyousubmitanatjobso
thattheyareavailablewhenatexecutescommands.
/etc/at.allowand/etc/at.deny
Therootusercanalwaysuseat.The/etc/at.allowand/etc/at.denyfiles,whichshouldberead0able
andwritablebyrootonly(mode600),controlwhichordinary,localuserscanuseat.When
/etc/at.denyexistsandisempty,alluserscanuseat.When/etc/at.denydoesnotexist,onlyuserslisted
in/etc/at.allowcanuseat.Userslistedin/etc/at.denycannotuseatunlesstheyarealsolistedin
/etc/at.allow.
Jobsyousubmitusingatarerunbytheatdaemon(atd).Thisdaemonstoresjobsin/var/spool/atand
outputin/var/spool/at/spool,bothofwhichshouldbesettomode700andownedbytheusernamed
daemon.
Examples
Youcanuseanyofthefollowingtechniquestopaginateandprintlong_filetomorrowat2:00AM.The
firstexampleexecutesthecommanddirectlyfromthecommandline;thelasttwoexamplesusethe
pr_tonightfile,whichcontainsthenecessarycommand,andexecuteitusingat.
$at2am
at>prlong_file|lpr
at>CONTROL-D<EOT>
job8at2005-08-1702:00
$catpr_tonight
#!/bin/bash
prlong_file|lpr
$at-fpr_tonight2am
job9at2005-08-1702:00
$at2am<pr_tonight
job10at2005-08-1702:00
Ifyouexecutecommandsdirectlyfromthecommandline,youmustsignaltheendofthecommandsby
pressingCONTROL-Datthebeginningofaline.AfteryoupressCONTROL-D,atdisplaysalinethat
beginswithjobfollowedbythejobnumberandthetimeatwillexecutethejob.
Ifyourunatqaftertheprecedingcommands,itdisplaysalistofjobsinitsqueue:
$atq
82005-08-1702:00a
92005-08-1702:00a
102005-08-1702:00a
Thefollowingcommandremovesjobnumber9fromthequeue:
$atrm9
$atq
82005-08-1702:00a
102005-08-1702:00a
Thenextexampleexecutescmdfileat3:30PM(1530hours)oneweekfromtoday:
$at-fcmdfile1530+1week
job12at2005-08-2315:30
Nextatexecutesajobat7PMonThursday.Thisjobusesfindtocreateanintermediatefile,redirects
theoutputsenttostandarderror,andprintsthefile.
$at7pmThursday
at>find/-name"core"-print>report.out2>report.err
at>lprreport.out
at>CONTROL-D<EOT>
job13at2005-08-1819:00
Thefinalexampleshowssomeoftheoutputgeneratedbythecoptionwhenatisqueriedaboutthe
precedingjob.Mostofthelinesshowtheenvironment;onlythelastfewlinesexecutethecommands:
$at-c13
#!/bin/sh
#atrunuid=500gid=500
#mailmark0
umask2
PATH=/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:.;
exportPATH
PWD=/home/mark/book.examples/99/cp;exportPWD
EXINIT=set\ai\aw;exportEXINIT
LANG=C;exportLANG
PS1=\\\$\;exportPS1
...
cd/home/mark/book\.examples/99/cp||{
echo'Executiondirectoryinaccessible'>&2
exit1
}
find/-name"core"-print>report.out2>report.err
lprreport.out
bzip2:Compressesordecompressesfiles
bzip2[options][file-list]
bunzip2[options][file-list]
bzcat[options][file-list]
bzip2recover[file]
Thebzip2utilitycompressesfiles;bunzip2restoresfilescompressedwithbzip2;bzcatdisplays
filescompressedwithbzip2.
Arguments
Thefile-listisalistofoneormorefiles(nodirectories)thataretobecompressedordecompressed.If
file-listisemptyorifthespecialoptionispresent,bzip2readsfromstandardinput.Thestdoutoption
causesbzip2towritetostandardoutput.
Options
Acceptsthecommonoptionsdescribedonpage587.
stdout cWritestheresultsofcompressionordecompressiontostandard
output.
decompress dDecompressesafilecompressedwithbzip2.Thisoptionwithbzip2
isequivalenttothebunzip2command.
fastorbest n
Setstheblocksizewhencompressingafile.Thenisadigitfrom1to
9,where1(fast)generatesablocksizeof100kilobytesand9(best)
generatesablocksizeof900kilobytes.Thedefaultlevelis9.The
optionsfastandbestareprovidedforcompatibilitywithgzipanddo
notnecessarilyyieldthefastestorbestcompression.
force f
Forcescompressionevenifafilealreadyexists,hasmultiplelinks,or
comesdirectlyfromaterminal.Theoptionhasasimilareffectwith
bunzip2.
keep kDoesnotdeleteinputfileswhilecompressingordecompressingthem.
quiet qSuppresseswarningmessages;doesdisplaycriticalmessages.
test tVerifiestheintegrityofacompressedfile.Displaysnothingifthefileis
OK.
verbose v
Foreachfilebeingcompresseddisplaysthenameofthefile,the
compressionratio,thepercentageofspacesaved,andthesizesofthe
decompressedandcompressedfiles.
Discussion
Thebzip2andbunzip2utilitiesworksimilarlytogzipandgunzip;seethediscussionofgzip
(page689)formoreinformation.Normallybzip2doesnotoverwriteafile;youmustuseforceto
overwriteafileduringcompressionordecompression.
Notes
Thebzip2homepageissources.redhat.com/bzip2.
Thebzip2utilitydoesabetterjobofcompressingfilesthangzip.
Usethebzip2modifierwithtar(page788)tocompressarchivefileswithbzip2.
bzcatfile-list
Workslikecatexceptthatitusesbunzip2todecompressfile-listasitcopiesfilestostandardoutput.
bzip2recover
Attemptstorecoveradamagedfilethatwascompressedwithbzip2.
Examples
Inthefollowingexample,bzip2compressesafileandgivestheresultingfilethesamenamewitha.bz2
filenameextension.Thevoptiondisplaysstatisticsaboutthecompression.
$ls-l
total728
-rw-r--r--1samsam737414Feb2019:05bigfile
$bzip2-vbigfile
bigfile:3.926:1,2.037bits/byte,74.53%saved,737414in,187806
out
$ls-l
total188
-rw-r--r--1samsam187806Feb2019:05bigfile.bz2
Nexttouchcreatesafilewiththesamenameastheoriginalfile;bunzip2refusestooverwritethefile
intheprocessofdecompressingbigfile.bz2.Theforceoptionenablesbunzip2tooverwritethefile.
$touchbigfile
$bunzip2bigfile.bz2
bunzip2:Outputfilebigfilealreadyexists.
$bunzip2--forcebigfile.bz2
$ls-l
total728
-rw-r--r--1samsam737414Feb2019:05bigfile
cal:Displaysacalendar
cal[options][[month]year]
Thecalutilitydisplaysacalendarforamonthorayear.
Arguments
Theargumentsspecifythemonthandyearforwhichcaldisplaysacalendar.Themonthisadecimal
integerfrom1to12andtheyearisadecimalinteger.Withoutanyarguments,caldisplaysacalendarfor
thecurrentmonth.Whenyouspecifyasingleargument,itistakentobetheyear.
Options
j(Julian)DisplaysaJuliancalendaracalendarthatnumbersthedaysconsecutively
fromJanuary1(1)throughDecember31(365or366).
m(Monday)MakesMondaythefirstdayoftheweek.Withoutthisoption,Sundayis
thefirstdayoftheweek.
y(year)Displaysacalendarforthecurrentyear.
3(threemonths)Displaystheprevious,current,andnextmonths.
Notes
Donotabbreviatetheyear.Theyear05isnotthesameas2005.
Examples
ThefollowingcommanddisplaysacalendarforAugust2007:
$cal82007
August2007
SuMoTuWeThFrSa
1234
567891011
12131415161718
19202122232425
262728293031
NextisaJuliancalendarfor1949withMondayasthefirstdayoftheweek:
$cal-jm1949
1949
JanuaryFebruary
MonTueWedThuFriSatSunMonTueWedThuFriSatSun
12323334353637
345678938394041424344
1011121314151645464748495051
1718192021222352535455565758
2425262728293059
31...
cat:Joinsanddisplaysfiles
cat[options][file-list]
Thecatutilitycopiesfilestostandardoutput.Youcanusecattodisplaythecontentsofoneormore
textfilesonthescreen.
Arguments
Thefile-listisalistofthepathnamesofoneormorefilesthatcatprocesses.Ifyoudonotspecifyan
argumentorifyouspecifyahyphen()inplaceofafilename,catreadsfromstandardinput.
Options
Acceptsthecommonoptionsdescribedonpage587.
show-all ASameasvET.
number-nonblank
bNumbersalllinesthatarenotblankastheyarewrittentostandard
output.
e(end)SameasvE.
show-ends EMarkstheendsoflineswithdollarsigns.
number n(number)Numbersalllinesastheyarewrittentostandardoutput.
squeeze-blank sRemovesextrablanklinessotherearenevertwoormoreblank
linesinarow.
t(tab)SameasvT.
show-tabs TMarkseachTABwith^I.
show-nonprinting
v
DisplaysCONTROLcharacterswiththecaretnotation(^M)anddisplayscharacters
thathavethehighbitset(METAcharacters)withtheM-notation.Thisoptiondoesnot
convertTABsandLINEFEEDs.Useshow-tabsifyouwanttodisplayTABsas^I.
LINEFEEDscannotbedisplayedasanythingbutthemselves;otherwise,thelinewould
betoolong.
Notes
Seepage115foradiscussionofcat,standardinput,andstandardoutput.
Usetheodutility(page737)todisplaythecontentsofafilethatdoesnotcontaintext(forexample,an
executableprogramfile).
Usethetacutilitytodisplaylinesofatextfileinreverseorder.Seethetacinfopageformore
information.
Thenamecatisderivedfromoneofthefunctionsofthisutility,catenate,whichmeanstojointogether
sequentially,orendtoend.
caution:Setnoclobbertoavoidoverwritingafile
Despitecat'swarningmessage,theshelldestroystheinputfile(letter)beforeinvoking
catinthefollowingexample:
$catmemoletter>letter
cat:letter:inputfileisoutputfile
Youcanpreventoverwritingafileinthissituationbysettingthenoclobbervariable(pages
119and367).
Examples
Thefollowingcommanddisplaysthecontentsofthememotextfileontheterminal:
$catmemo
...
Thenextexamplecatenatesthreetextfilesandredirectstheoutputtotheallfile:
$catpage1lettermemo>all
Youcanusecattocreateshorttextfileswithoutusinganeditor.Enterthefollowingcommandline,type
(orpaste)thetextyouwantinthefile,andpressCONTROL-Donalinebyitself:
$cat>new_file
...
(text)
...
CONTROL-D
Inthiscasecattakesinputfromstandardinput(thekeyboard)andtheshellredirectsstandardoutput(a
copyoftheinput)tothefileyouspecify.TheCONTROL-DsignalstheEOF(endoffile)andcausescat
toreturncontroltotheshell(page116).
Inthenextexample,apipesendstheoutputfromwhotostandardinputofcat.Theshellredirectscat's
outputtothefilenamedoutputthat,afterthecommandshavefinishedexecuting,containsthecontentsof
theheaderfile,theoutputofwho,andfooter.Thehyphenonthecommandlinecausescattoread
standardinputafterreadingheaderandbeforereadingfooter.
$who|catheader-footer>output
cd:Changestoanotherworkingdirectory
cd[options][directory]
Thecdbuiltinmakesdirectorytheworkingdirectory.
Arguments
Thedirectoryisthepathnameofthedirectoryyouwanttobethenewworkingdirectory.Withoutan
argument,cdmakesyourhomedirectorytheworkingdirectory.Usingahypheninplaceofdirectory
changestothepreviousworkingdirectory.
Notes
Thecdcommandisabashandtcshbuiltin.
Seepage82foradiscussionofcd.
Withoutanargument,cdmakesyourhomedirectorytheworkingdirectory;itusesthevalueofthe
HOME(bash;page283)orhome(tcsh,page362)variableforthispurpose.
Withanargumentofahyphen,cdmakesthepreviousworkingdirectorytheworkingdirectory.Itusesthe
valueoftheOLDPWD(bash)orowd(tcsh)variableforthispurpose.
TheCDPATH(bash;page289)orcdpath(tcsh;page362)variablecontainsacolon-separatedlistof
directoriesthatcdsearches.Withinthelistanulldirectoryname(::)oraperiod(:.:)representsthe
workingdirectory.IfCDPATHorcdpathisnotset,cdsearchesonlytheworkingdirectoryfor
directory.Ifthisvariableissetanddirectoryisnotanabsolutepathname(doesnotbeginwithaslash),
cdsearchesthedirectoriesinthelist;ifthesearchfails,cdsearchestheworkingdirectory.Seepage
289foradiscussionofCDPATH.
Examples
ThefollowingcdcommandmakesAlex'shomedirectoryhisworkingdirectory.Thepwdbuiltinverifies
thechange:
$pwd
/home/alex/literature
$cd
$pwd
/home/alex
Thenextcommandmakesthe/home/alex/literaturedirectorytheworkingdirectory:
$cd/home/alex/literature
$pwd
/home/alex/literature
Nextthecdutilitymakesasubdirectoryoftheworkingdirectorythenewworkingdirectory:
$cdmemos
$pwd
/home/alex/literature/memos
Finallycdusesthe..referencetotheparentoftheworkingdirectorytomaketheparentthenewworking
directory:
$cd..
$pwd
/home/alex/literature
chgrp:Changesthegroupassociatedwithafile
chgrp[options]groupfile-list
chgrp[options]reference=rfilefile-list
Thechgrputilitychangesthegroupassociatedwithoneormorefiles.
Arguments
ThegroupisthenameornumericgroupIDofthenewgroup.Thefile-listisalistofthepathnamesofthe
fileswhosegroupassociationistobechanged.Therfileisthepathnameofafilewhosegroupisto
becomethenewgroupassociatedwithfile-list.
Options
changes cDisplaysamessageforeachfilewhosegroupischanged.
dereference ChangesthegroupIDsofthefilessymboliclinkspointto,notthe
symboliclinksthemselves.Thedefaultisno-dereference.
quietorsilent fPreventsthedisplayofwarningmessagesaboutfileswhose
permissionspreventyoufromchangingtheirgroupIDs.
no-dereference
hChangesthegroupIDsofsymboliclinks,notthefilesthatthe
linkspointto(default).
recursive RRecursivelydescendsadirectoryspecifiedinfile-listandchanges
thegroupIDonallfilesinthedirectoryhierarchy.
reference=rfile
Changesthegroupofthefilesinfile-listtothatofrfile.
verbose vDisplaysforeachfileamessagesayingwhetheritsgroupwas
retainedorchanged.
Notes
Onlytheownerofafileorrootcanchangethegroupassociationofafile.Also,unlessyouareroot,you
mustbelongtothespecifiedgrouptochangethegroupIDofafiletothatgroup.
Seepage608forinformationonhowchowncanchangethegroupassociatedwith,aswellastheowner
of,afile.
Examples
Thefollowingcommandchangesthegroupthatthemanualsfileisassociatedwith;thenewgroupis
pubs.
$chgrppubsmanuals
chmod:Changestheaccessmode(permissions)ofafile
chmod[options]whooperatorpermissionfile-list(symbolic)
chmod[options]modefile-list(absolute)
chmod[options]reference=rfilefile-list(referential)
Thechmodutilitychangesthewaysinwhichafilecanbeaccessedbytheownerofthefile,thegroupto
whichthefilebelongs,and/orallotherusers.OnlytheownerofafileorSuperusercanchangetheaccess
mode,orpermissions,ofafile.Youcanspecifythenewaccessmodeabsolutely,symbolically,or
referentially.
Arguments
Argumentsspecifywhichfilesaretohavetheirmodeschangedinwhatways.
Symbolic
Youcanspecifymultiplesetsofsymbolicmodes(whooperatorpermission)byseparatingeachsetfrom
thenextwithacomma.
Thechmodutilitychangestheaccesspermissionfortheclassofusersspecifiedbywho.Theclassof

usersisdesignatedbyoneormoreofthelettersspecifiedinthewhocolumnofTableV-4.
TableV-4.Symbolicmodeuserclassspecification
who Userclass Meaning
uUser Ownerofthefile
gGroup Grouptowhichtheownerbelongs
oOther Allotherusers
aAll Canbeusedinplaceofugo
TableV-5liststhesymbolicmodeoperators.
TableV-5.Symbolicmodeoperators
operator Meaning
+Addspermissionforthespecifieduserclass
Removespermissionforthespecifieduserclass
=Setspermissionforthespecifieduserclassresetsallotherpermissionsforthatuser
class
TheaccesspermissionisspecifiedbyoneormoreoftheletterslistedinTableV-6.
TableV-6.Symbolicmodepermissions
permission Meaning
rSetsreadpermission
wSetswritepermission
xSetsexecutepermission
s
SetsuserIDorgroupID(dependingonthewhoargument)tothatofthe
ownerofthefilewhilethefileisbeingexecuted(Formoreinformationseepage
94.)

tSetsthestickybit(OnlySuperusercansetthestickybit,anditcanbeused
onlywithu;seepage903.)
XMakesthefileexecutableonlyifitisadirectoryorifanotheruserclasshas
executepermission
uSetsspecifiedpermissionstothoseoftheowner
gSetsspecifiedpermissionstothoseofthegroup
oSetsspecifiedpermissionstothoseofothers
Absolute
Youcanuseanoctalnumbertospecifytheaccessmode.ConstructthenumberbyORingtheappropriate
valuesfromTableV-7.ToORtwooctalnumbersfromthistable,justaddthem.(RefertoTableV-8for
examples.)
TableV-7.Absolutemodespecifications
mode Meaning
4000 SetsuserIDwhentheprogramisexecuted(page94)
2000 SetsgroupIDwhentheprogramisexecuted(page94)
1000 Stickybit(page903)
0400 Ownercanreadthefile
0200 Ownercanwritetothefile
0100 Ownercanexecutethefile
0040 Groupcanreadthefile
0020 Groupcanwritetothefile
0010 Groupcanexecutethefile
0004 Otherscanreadthefile
0002 Otherscanwritetothefile

0001 Otherscanexecutethefile
TableV-8.Examplesofabsolutemodespecifications
Mode Meaning
0777 Owner,group,andotherscanread,write,andexecutefile
0755 Ownercanread,write,andexecutefile;groupandotherscanreadand
executefile
0711 Ownercanread,write,andexecutefile;groupandotherscanexecutefile
0644 Ownercanreadandwritefile;groupandotherscanreadfile
0640 Ownercanreadandwritefile,groupcanreadfile,andotherscannotaccess
file
TableV-8listssometypicalmodes.
Options
changes cDisplaysamessagegivingthenewpermissionsforeachfile
whosemodeischanged.
quietorsilent f
Preventsthedisplayofwarningmessagesaboutfileswhose
permissionspreventchmodfromchangingthepermissionsofthe
file.
recursive RRecursivelydescendsadirectoryspecifiedinfile-listandchanges
thepermissionsonallfilesinthedirectoryhierarchy.
reference=rfile
Changesthepermissionsofthefilesinfile-listtothatofrfile.
verbose vDisplaysforeachfileamessagesayingthatitspermissionswere
changed(eveniftheywerenotchanged)andspecifyingthe
permissions.Usechangestodisplaymessagesonlywhen
permissionsareactuallychanged.
Notes
Whenyouareusingsymbolicarguments,youcanomitthepermissionfromthecommandlineonlywhen
theoperatoris=.Thisomissiontakesawayallpermissions.Seethesecondexampleinthenextsection.
Examples
Thefollowingexamplesshowhowtousethechmodutilitytochangethepermissionsofthefilenamed
temp.Theinitialaccessmodeoftempisshownbyls(see"Discussion"onpage710forinformation
aboutthelsdisplay):
$ls-ltemp
-rw-rw-r--1alexpubs57Jul1216:47temp
Whenyoudonotfollowanequalsignwithapermission,chmodremovesallpermissionsforthe
specifieduserclass.Thefollowingcommandremovesallaccesspermissionsforthegroupandallother
userssothatonlytheownerhasaccesstothefile:
$chmodgo=temp
$ls-ltemp
-rw-------1alexpubs57Jul1216:47temp
Thenextcommandchangestheaccessmodesforallusers(owner,group,andothers)toreadandwrite.
Nowanyonecanreadfromorwritetothefile.
$chmoda=rwtemp
$ls-ltemp
-rw-rw-rw-1alexpubs57Jul1216:47temp
Usinganabsoluteargument,a=rwbecomes666.Thenextcommandperformsthesamefunctionasthe
previousone:
$chmod666temp
Thenextcommandremoveswriteaccesspermissionforotherusers.Asaresultmembersofthepubs
groupcanstillreadfromandwritetothefile,butotheruserscanonlyreadfromthefile:
$chmodo-wtemp
$ls-ltemp
-rw-rw-r--1alexpubs57Jul1216:47temp
Thefollowingcommandyieldsthesameresult,usinganabsoluteargument:
$chmod664temp
Thenextcommandaddsexecuteaccesspermissionforallusers:
$chmoda+xtemp
$ls-ltemp
-rwxrwxr-x1alexpubs57Jul1216:47temp

Iftempisashellscriptorotherexecutablefile,alluserscannowexecuteit.(Youneedreadandexecute
accesstoexecuteashellscriptbutonlyexecuteaccesstoexecuteabinaryfile.)Theabsolutecommand
thatyieldsthesameresultis
$chmod775temp
Thefinalcommandusessymbolicargumentstoachievethesameresultastheprecedingone.Itsets
permissionstoread,write,andexecutefortheowner,andtoreadandwriteforthegroupandotherusers.
Acommaseparatesthesetsofsymbolicmodes.
$chmodu=rwx,go=rwtemp
chown:Changestheownerofafileand/orthegroupthefileis
associatedwith
chown[options]ownerfile-list
chown[options]owner:groupfile-list
chown[options]owner:file-list
chown[options]:groupfile-list
chown[options]reference=rfilefile-list
Thechownutilitychangestheownerofafileand/orthegroupthefileisassociatedwith.Onlyrootcan
changetheownerofafile.Onlyrootortheownerofafilewhobelongstothenewgroupcanchangethe
groupafileisassociatedwith.
Arguments
TheowneristheusernameornumericuserIDofthenewowner.Thefile-listisalistofthepathnamesof
thefileswhoseownershipand/orgroupassociationyouwanttochange.Thegroupisthegroupnameor
numericgroupIDofthenewgroupthatthefileisassociatedwith.TableV-9showsthewaysyoucan
specifythenewownerand/orgroup.
TableV-9.Specifyingthenewownerand/orgroup

Argument Meaning
owner Thenewowneroffile-list;thegroupisnotchanged
owner:group Thenewownerandnewgroupassociationoffile-list
owner: Thenewowneroffile-list;thegroupassociationischangedtothatofthenew
owner'slogingroup
:group Thenewgroupassociatedwithfile-list;theownerisnotchanged
Options
Acceptsthecommonoptionsdescribedonpage587.
changes cDisplaysamessageforeachfilewhoseownership/groupis
changed.
dereference Changestheownership/groupofthefilessymboliclinkspointto,
notthesymboliclinksthemselves.Thedefaultisno-dereference.
quietorsilent fPreventschownfromdisplayingerrormessageswhenitisunable
tochangetheownership/groupofafile.
no-dereference
hChangestheownership/groupofsymboliclinks,notthefilesthat
thelinkspointto(default).
recursive R
Whenyouincludedirectoriesinthefile-list,thisoptiondescends
thedirectoryhierarchy,settingthespecifiedownership/groupfor
allfilesencountered.
reference=rfile
Changestheownershipandgroupassociationofthefilesinthe
file-listtothatofrfile.
verbose vDisplaysforeachfileamessagesayingwhetherits
ownership/groupwasretainedorchanged.
Notes
Thechownutilityclearssetuidandsetgidbitswhenitchangestheownerofafile.
Examples
Thefollowingcommandchangestheownerofthechapter1fileinthemanualsdirectory.Thenewowner
isJenny:
#chownjennymanuals/chapter1
ThefollowingcommandmakesAlextheownerof,andAlex'slogingroupthegroupassociatedwith,all
filesinthe/home/alex/literaturedirectoryandinallitssubdirectories:
#chown--recursivealex:/home/alex/literature
Thenextcommandchangestheownershipofthefilesinliteraturetoalexandthegroupassociatedwith
thesefilestopubs:
#chownalex:pubs/home/alex/literature/*
Thefinalexamplechangesthegroupassociationofthefilesinmanualstopubswithoutalteringtheir
ownership.Theownerofthefiles,whoisexecutingthiscommand,mustbelongtothepubsgroup.
$chown:pubsmanuals/*
cmp:Comparestwofiles
cmp[options]file1[file2[skip1[skip2]]]
Thecmputilitydisplaysthedifferencesbetweentwofilesonabyte-by-bytebasis.Ifthefilesarethe
same,cmpissilent.Ifthefilesdiffer,cmpdisplaysthebyteandlinenumberofthefirstdifference.
Arguments
Thefile1andfile2arepathnamesofthefilesthatcmpcompares.Iffile2isomitted,cmpusesstandard
inputinstead.Usingahyphen()inplaceoffile1orfile2causescmptoreadstandardinputinsteadofthat
file.
Theskip1andskip2aredecimalnumbersindicatingthenumberofbytestoskipineachfilebefore
beginningthecomparison.
Options
printbytes b
Displaysmoreinformation,includingfilenames,byteandline
number,aswellasoctalandASCIIvaluesofthefirstdiffering
byte.
ignoreinitial=n
in
Skipsthefirstnbytesinbothfilesbeforebeginningthecomparison.
verbose l
(lowercase"l")Insteadofstoppingatthefirstbytethatdiffers,
continuescomparingthetwofilesanddisplaysboththelocation
andthevalueofeachbytethatdiffers.Locationsaredisplayedas
decimalbytecountoffsetsfromthebeginningofthefiles;byte
valuesaredisplayedinoctal.Thecomparisonterminateswhenan
EOFisencounteredoneitherfile.
silentorquite sSuppressesoutputfromcmp;onlysetstheexitstatus(see
"Notes").
Notes
Byteandlinenumberingstartat1.
Thecmputilitydoesnotdisplayamessageifthefilesareidentical;itonlysetstheexitstatus.Thisutility
returnsanexitstatusof0ifthefilesarethesameand1iftheyaredifferent.Anexitstatusgreaterthan1
meansanerroroccurred.
Whenyouuseskip1(andskip2),theoffsetvaluescmpdisplaysarebasedonthebytewherethe
comparisonbegan.Youcanusethestandardmultiplicativesuffixesafterskip1andskip2;seeTableV-1
onpage586.
Unlikediff(page638),cmpworkswithbinaryaswellasASCIIfiles.
Examples
Theexamplesusethefilesaandbshownbelow.Thesefileshavetwodifferences.Thefirstdifferenceis
thatthewordlazyinfileaisreplacedbylasyinfileb.Theseconddifferenceismoresubtle:ATAB
characterappearsjustbeforetheNEWLINEcharacterinfileb.
$cata
Thequickbrownfoxjumpedoverthelazydog.
$catb
Thequickbrownfoxjumpedoverthelasydog.TAB
Thefirstexampleusescmpwithoutanyoptionstocomparethetwofiles.Thecmputilityreportsthatthe
filesaredifferentandidentifiestheoffsetfromthestartofthefileswherethefirstdifferenceisfound:
$cmpab
abdiffer:char39,line1
Youcandisplaythevaluesofthebytesatthatlocationbyaddingtheprintcharsoption:
$cmp--print-bytesab
abdiffer:char39,line1is172z163s
Theloptiondisplaysallbytesthatdifferbetweenthetwofiles.Becausethisoptioncreatesalotofoutput
ifthefileshavemanydifferences,youmaywanttoredirecttheoutputtoafile.Thefollowingexample
showsthetwodifferencesbetweenfilesaandb.Theboptiondisplaysthevaluesforthebytesaswell.
WherefileahasaCONTROLJ(NEWLINE),filebhasaCONTROLI(TAB).Themessagesayingthatit
hasreachedtheendoffileonfileaindicatesthatfilebislongerthanfilea.
$cmp-lbab
39172z163s
4612^J11^I
cmp:EOFona
Inthenextexample,theignoreinitialoptionisusedtoskipoverthefirstdifferenceinthefiles.Thecmp
utilitynowreportsontheseconddifference.Thedifferenceisputatcharacter7,whichisthe46th
characterintheoriginalfileb(7characterspasttheignored39characters).
$cmp--ignore-initial=39ab
abdiffer:char7,line1
Youcanuseskip1andskip2inplaceoftheignoreinitialoptionusedintheprecedingexample:
$cmpab3939
abdiffer:char7,line1
comm:Comparessortedfiles
comm[options]file1file2
Thecommutilitydisplaysaline-by-linecomparisonoftwosortedfiles.Thefirstofthethreecolumnsit
displaysliststhelinesfoundonlyinfile1,thesecondcolumnliststhelinesfoundonlyinfile2,andthe
thirdliststhelinescommontobothfiles.
Arguments
Thefile1andfile2arepathnamesofthefilesthatcommcompares.Usingahyphen()inplaceoffile1or
file2causescommtoreadstandardinputinsteadofthatfile.
Options
Youcancombinetheoptions.
1Doesnotdisplaycolumn1(doesnotdisplaylinesfoundonlyinfile1).
2Doesnotdisplaycolumn2(doesnotdisplaylinesfoundonlyinfile2).
3Doesnotdisplaycolumn3(doesnotdisplaylinesfoundinbothfiles).
Notes
Ifthefileshavenotbeensorted,commwillnotworkproperly.
LinesinthesecondcolumnareprecededbyoneTAB,andthoseinthethirdcolumnareprecededbytwo
TABs.
Theexitstatusindicateswhethercommcompletednormally(0)orabnormally(not0).
Examples
Thefollowingexamplesusetwofiles,candd,intheworkingdirectory.Aswithallinputtocomm,the
fileshavealreadybeensorted:
$catc
bbbbb
ccccc
ddddd
eeeee
fffff
$catd
aaaaa
ddddd
eeeee
ggggg
hhhhh
Refertosortonpage762forinformationonsortingfiles.
Thefollowingexamplecallscommwithoutanyoptions,soitdisplaysthreecolumns.Thefirstcolumn
liststhoselinesfoundonlyinfilec,thesecondcolumnliststhosefoundind,andthethirdliststhelines
foundinbothcandd:
$commcd
aaaaa
bbbbb
ccccc
ddddd
eeeee
fffff
ggggg
hhhhh
Thenextexampleshowstheuseofoptionstopreventcommfromdisplayingcolumns1and2.Theresult
iscolumn3,alistofthelinescommontofilescandd:
$comm-12cd
ddddd
eeeee
configure:Configuressourcecodeautomatically
./configureoptions
TheconfigurescriptispartoftheGNUConfigureandBuildSystem.Softwaredeveloperswho
supplysourcecodefortheirproductsfacetheproblemofmakingiteasyforrelativelynaiveusersto
buildandinstalltheirsoftwarepackageonawidevarietyofmachinearchitectures,operatingsystems,
andsystemsoftware.Towardthisendmanysoftwaredeveloperssupplyashellscriptnamed
configurewiththeirsourcecode.
Whenyourunconfigure,itdeterminesthecapabilitiesofthelocalsystem.Thedatacollectedby
configureisusedtobuildthemakefileswithwhichmake(page715)buildstheexecutablesand
libraries.Youcanadjustthebehaviorofconfigurebyspecifyingcommandlineoptionsand
environmentvariables.
Options
disable-feature
Worksinthesamemannerasenable-featureexceptthatitdisablessupportforfeature.
enable-feature
Replacefeaturewiththenameofafeaturethatcanbesupportedbythe
softwarebeingconfigured.Forexample,configuringtheZShellsource
codewiththecommandconfigureenable-zsh-memconfiguresthe
sourcecodetousethespecialmemoryallocationroutinesprovidedwith
zshinsteadofusingthesystemmemoryallocationroutines.Checkthe
READMEfilesuppliedwiththesoftwaredistributiontoseethechoices
availableforfeature.
help
Displaysadetailedlistofalloptionsavailableforusewithconfigure.
Thecontentsofthislistdependsonthesoftwaredistributionbeing
configured.
prefix=directory
Bydefaultconfigurebuildsmakefilesthatinstallsoftwareinthe
/usr/localdirectory(whenyougivethecommandmakeinstall).To
installintoadifferentdirectory,replacedirectorywiththepathnameof
thedirectoryyouwanttoinstallthesoftwarein.
with-package
Replacepackagewiththenameofanoptionalpackagethatcanbe
includedwiththesoftwareyouareconfiguring.Forexample,ifyou
configurethesourcecodefortheWindowsemulatorwinewiththe
commandconfigurewith-dll,thesourcecodeisconfiguredtobuilda
sharedlibraryofWindowsemulationsupport.ChecktheREADMEfile
suppliedwiththesoftwaredistributiontoseethechoicesavailablefor
package.Also,configurehelpusuallydisplaysthechoicesavailablefor
package.
Discussion
TheGNUConfigureandBuildSystemallowssoftwaredeveloperstodistributesoftwarethatcan
configureitselftobebuiltonavarietyofsystems.Thissystembuildsashellscriptnamedconfigure,
whichpreparesthesoftwaredistributiontobebuiltandinstalledonalocalsystem.Theconfigure
scriptsearchesthelocalsystemtofindthevariousdependenciesforthesoftwaredistributionand
constructstheappropriatemakefiles.Onceyouhaverunconfigure,youcanbuildthesoftwarewitha
makecommandandinstallthesoftwarewithamakeinstallcommand.
TheconfigurescriptdetermineswhichCcompilertouse(usuallygcc)andspecifiesasetofflagsto
passtothatcompiler.YoucansettheenvironmentvariablesCCandCFLAGStooverridethesevalues
withyourownchoices.(Seethe"Examples"section.)
Notes
EachpackagethatusestheGNUautoconfigurationutilityprovidesitsowncustomcopyofconfigure,
whichthesoftwaredevelopercreatedusingtheGNUautoconfutility.ReadtheREADMEand
INSTALLfilesthatareprovidedwiththepackageyouareinstallingtoobtaindetailedinformationabout
theavailableoptions.
Theconfigurescriptsareself-containedandruncorrectlyonawidevarietyofsystems.Youdonot
needanyspecialsystemresourcestouseconfigure.
Examples
Thesimplestwaytocallconfigureistocdtothebasedirectoryforthesoftwaredistributionyou
wanttoconfigureandthenrunthefollowingcommand:
$./configure
The./isprependedtothecommandnametoensurethatyouarerunningtheconfigurescriptthatwas
suppliedwiththesoftwaredistribution.TocauseconfiguretobuildmakefilesthatpasstheflagsWall
andO2togcc,usethefollowingcommandfrombash:
$CFLAGS="-Wall-O2"./configure
Ifyouareusingtcsh,usethefollowingcommand:
tcsh$envCFLAGS="-Wall-O2"./configure
cp:Copiesfiles
cp[options]source-filedestination-file
cp[options]source-file-listdestination-directory
Thecputilitycopiesoneormorefiles.Itcaneithermakeacopyofasinglefile(firstformat)oritcan
copyoneormorefilestoadirectory(secondformat).Withtherecursiveoption,cpcancopy
directories.
Arguments
Thesource-fileisthepathnameofthefilethatcpmakesacopyof.Thedestination-fileisthepathname
thatcpassignstotheresultingcopyofthefile.
Thesource-file-listisalistofoneormorepathnamesoffilesthatcpmakescopiesof.Thedestination-
directoryisthepathnameofthedirectoryinwhichcpplacesthecopiedfiles.Withthisformat,cpgives
eachofthecopiedfilesthesamesimplefilenameasitssource-file.
Therecursiveoptionenablescptocopydirectoriesrecursivelyfromthesource-file-listintothe
destination-directory.
Options
Acceptsthecommonoptionsdescribedonpage587.
archive aAttemptstopreserveasmanyattributesofsource-fileaspossible.Same
asdpPR.
backup b
Ifcopyingafilewouldremoveoroverwriteanexistingfile,thisoption
makesabackupcopyofthefilethatwouldbeoverwritten.Thebackup
copyhasthesamenameasthedestination-filewithatilde(~)appended
toit.Whenyouusebothbackupandforce,cpmakesabackupcopy
whenyoutrytocopyafileoveritself.
d
Copiessymboliclinks,notthefilesthatlinkspointto.Alsopreserveshard
linksindestination-filesthatexistbetweencorrespondingsource-files.
Thisoptionisequivalenttono-dereferenceandpreserve=links.
force f
Whenthedestination-fileexistsandcannotbeopenedforwriting,this
optioncausescptotrytoremovedestination-filebeforecopyingsource-
file.Thisoptionisusefulwhentheusercopyingafiledoesnothavewrite
permissiontoanexistingdestination-filebuthaswritepermissiontothe
directorycontainingthedestination-file.Seealsobackup.
interactive i
Promptsyouwhenevercpwouldoverwriteafile.Ifyourespondwitha
stringthatstartswithyorY,cpcontinues.Ifyouenteranythingelse,cp
doesnotcopythefile.
dereference LCopiesthefilethatasymboliclinkpointsto.Seeno-dereference.
preserve pCreatesadestination-filewiththesameowner,group,permissions,
accessdate,andmodificationdateasthesource-file.
no-dereference
P
Copiessymboliclinks,notthefilesthatthelinkspointto.Without
theR,r,orrecursiveoption,thedefaultbehavioristodereference
links(copythefilesthatlinkspointto,notthelinks).Withoneof
theseoptions,cpdoesnotdereferencesymboliclinks(itcopiesthe
links,notthefilesthatthelinkspointto).
parents Copiesarelativepathnametoadirectory,creatingdirectoriesas
needed.(See"Examples.")
preserve=links
Whenrecursivelycopyingdirectories,attemptstopreservehard
linksindestination-filesthatexistbetweencorrespondingsource-
files.
recursive Rorr
Recursivelycopiesdirectoryhierarchiesincludingordinaryfiles.
Theno-dereferenceoptionisimplied.
update uCopiesonlywhenthedestination-filedoesnotexistorwhenitis
olderthanthesource-file.
verbose vDisplaysthenameofeachfileascpcopiesit.
Notes
Ifthedestination-fileexistsbeforeyouexecutecp,cpoverwritesthefile,destroyingthecontentsbut
leavingtheaccessprivileges,owner,andgroupassociatedwiththefileastheywere.
Ifthedestination-filedoesnotexist,cpusestheaccessprivilegesofthesource-file.Theuserwho
copiesthefilebecomestheownerofthedestination-fileandtheuser'sgroupbecomesthegroup
associatedwiththedestination-file.
Withthepoption,cpattemptstosettheowner,group,permissions,accessdate,andmodificationdateto
matchthoseofthesource-file.
Unlikeln(page702),thedestination-filethatcpcreatesisindependentofitssource-file.
Examples
Thefirstcommandmakesacopyofthefileletterintheworkingdirectory.Thenameofthecopyis
letter.sav.
$cpletterletter.sav
Thenextcommandcopiesallfileswithfilenamesendingin.cintothearchivesdirectory,whichisa
subdirectoryoftheworkingdirectory.Eachcopiedfileretainsitssimplefilenamebuthasanewabsolute
pathname.Becauseofthepreserveoption,thecopiedfilesinarchiveshavethesameowner,group,
permissions,accessdate,andmodificationdateasthesourcefiles.
$cp--preserve*.carchives
Thenextexamplecopiesmemofrom/home/jennytotheworkingdirectory:
$cp/home/jenny/memo.
Thenextexampleusestheparentsoptiontocopythefilememo/thursday/maxtothedirdirectoryas
dir/memo/thursday/max.Thefindutilityshowsthenewlycreateddirectoryhierarchy.
$cp--parentsmemo/thursday/maxdir
$finddir
dir
dir/memo
dir/memo/thursday
dir/memo/thursday/max
Thefollowingcommandcopiesthefilesnamedmemoandletterintoanotherdirectory.Thecopieshave
thesamesimplefilenamesasthesourcefiles(memoandletter)buthavedifferentabsolutepathnames.
Theabsolutepathnamesofthecopiedfilesare/home/jenny/memoand/home/jenny/letter.
$cpmemoletter/home/jenny
Thefinalcommanddemonstratesoneuseoftheforceoption.Alexownstheworkingdirectoryandtries
unsuccessfullytocopyoneontoafile(me)thathedoesnothavewritepermissionfor.Becausehehas
writepermissiontothedirectorythatholdsme,Alexcanremovethefilebutnotwritetoit.Theforce
optionunlinks,orremoves,meandthencopiesonetothenewfilenamedme.
$ls-ld
drwxrwxr-x2alexalex4096Oct2122:55.
$ls-l
-rw-r--r--1rootroot3555Oct2122:54me
-rw-rw-r--1alexalex1222Oct2122:55one
$cponeme
cp:cannotcreateregularfile'me':Permissiondenied
$cp--forceoneme
$ls-l
-rw-r--r--1alexalex1222Oct2122:58me
-rw-rw-r--1alexalex1222Oct2122:55one
IfAlexhadusedthebackupoptioninadditiontoforce,cpwouldhavecreatedabackupofmenamed
me~.Referto"DirectoryAccessPermissions"onpage94formoreinformation.
cpio:Createsanarchiveorrestoresfilesfromanarchive
cpiocreate[options]
cpioextract[options][patterns]
cpiopass-through[options]directory
Thecpioutilityhasthreemodesofoperation:Createmodeplacesmultiplefilesintoasinglearchive
file,extractmoderestoresfilesfromanarchive,andpass-throughmodecopiesadirectoryhierarchyto
anotherlocation.Thearchivefileusedbycpiomaybesavedondisk,tape,otherremovablemedia,ora
remotesystem.
Createmodereadsalistofordinaryordirectoryfilenamesfromstandardinputandwritestheresulting
archivefiletostandardoutput.Youcanusethismodetocreateanarchive.Extractmodereadsthename
ofanarchivefromstandardinputandextractsfilesfromthatarchive.Youcandecidetorestoreallthe
filesfromthearchiveoronlythosewhosenamesmatchspecificpatterns.Pass-throughmodereads
ordinaryordirectoryfilenamesfromstandardinputandcopiesthefilestoanotherlocationonthedisk.
Arguments
Bydefaultcpioinextractmodeextractsallfilesfoundinthearchive.Youcanchoosetoextractfiles
selectivelybysupplyingoneormorepatterns.Ifthenameofafileinthearchivematchesoneofthe
patterns,thatfileisextracted;otherwise,itisignored.Thecpiopatternsaresimilartoshellwildcards
(page127)exceptthatpatternsmatchslashes(/)andaleadingperiod(.)inafilename.
Inpass-throughmodeyoumustgivethenameofthetargetdirectoryasanargumenttocpio.
Options
MajorOptions
Threeoptionsdeterminethemodeinwhichcpiooperates.Youmustincludeexactlyoneoftheseoptions
wheneveryouusecpio.
extract i
Readsthearchivefromstandardinputandextractsfiles.
Withoutanypatternsonthecommandline,cpio
extractsallthefilesfromthearchive.Withpatterns
specified,cpioextractsonlyfileswithnamesthe
patternsmatch.Thefollowingexampleextractsfromthe
SCSItapeat/dev/st0onlythosefileswhosenamesend
in.c:
$cpio-i\*.c</dev/st0
Thebackslashpreventstheshellfromexpandingthe*
beforeitpassestheargumenttocpio.
create o
Constructsanarchivefromthefilesnamedonstandard
input.Thesefilesmaybeordinaryordirectoryfiles,and
eachmustappearonaseparateline.Thearchiveis
writtentostandardoutputasitisbuilt.Thefindutility
frequentlygeneratesthefilenamesthatcpiouses.The
followingcommandbuildsanarchiveoftheentirelocal
systemandwritesittotheSCSItapeat/dev/st0:
$find/-depth-print|cpio-o
>/dev/st0
Thedepthoptioncausesfindtosearchforfilesina
depth-firstsearch,reducingthelikelihoodofpermissions
problemswhenyourestorethefilesfromthearchive.
Seethediscussionofthisoptiononpage622.
Copiesfilesfromoneplaceonthesystemtoanother.
Insteadofconstructinganarchivefilecontainingthe
filesnamedonstandardinput,cpiocopiesthemintothe
directory(thelastargumentgiventocpio).Theeffect
pass-through p
isthesameasifyouhadcreatedanarchivewithcopy-
outmodeandthenextractedthefileswithcopy-inmode,
butusingpass-throughmodeavoidscreatinganarchive.
Thefollowingexamplecopiesthefilesintheworking
directoryandallsubdirectoriesinto/home/alex/code:
$find.-depth-print|cpio-pdm
~alex/code
OtherOptions
Theremainingoptionsalterthebehaviorofcpio.Theseoptionsworkwithoneormoreofthepreceding
majoroptions.
resetaccesstime
a
Resetstheaccesstimesofsourcefilesaftercopying
themsothattheyhavethesameaccesstimeafter
copyingastheydidbefore.
B(block)Setstheblocksizeto5,120bytesinsteadof
thedefault512bytes.
blocksize=n
Setstheblocksizeusedforinputandoutputton512-
byteblocks.
c
(compatible)WritesheaderinformationinASCIIso
thatolder(incompatible)cpioutilitiesonother
systemscanreadthefile.Thisoptionisrarelyneeded.
makedirectories
d
Createsdirectoriesasneededwhencopyingfiles.Forexample,youneedthis
optionwhenyouareextractingfilesfromanarchivewithafilelistgeneratedby
findwiththedepthoption.Thisoptioncanbeusedonlywiththeextractand
passthroughoptions.
patternfile=filename
Efilename
Readspatternsfromfilename,onepatternperline.
Youcanspecifyadditionalpatternsonthecommand
line.
nonmatching f
Reversesthesenseofthetestdoneonpatternswhen
extractingfilesfromanarchive.Filesareextracted
fromthearchiveonlyiftheydonotmatchanyofthe
patterns.
file=archive Farchive
Usesarchiveasthenameofthearchivefile.Inextract
mode,readsfromarchiveinsteadofstandardinput.In
createmode,writestoarchiveinsteadofstandard
output.Youcanusethisoptiontoaccessadeviceon
anothersystemonanetwork;seethefileoptionto
tar(page787)formoreinformation.
help Displaysalistofoptions.
link lWhenpossible,linksfilesinsteadofcopyingthem.
dereference LCopiesthefilesthatsymboliclinkspointto,notthe
symboliclinksthemselves.
preservemodificationtime
m
Preservesthemodificationtimesoffilesthatareextractedfromanarchive.
Withoutthisoptionthefilesshowthetimetheywereextracted.Withthis
optionthecreatedfilesshowthetimetheyhadwhentheywerecopiedintothe
archive.
no-absolute-filenames
Inextractmode,createsallfilenamesrelativetothe
workingdirectoryevenfilesthatwerearchivedwith
absolutepathnames.
rename r
Allowsyoutorenamefilesascpiocopiesthem.When
cpiopromptsyouwiththenameofafile,yourespond
withthenewname.Thefileisthencopiedwiththenew
name.IfyoupressRETURNinstead,cpiodoesnot
copythefile.
list t
(tableofcontents)Displaysatableofcontentsofthe
archive.Thisoptionworksonlywiththeextractoption,
althoughnofilesareactuallyextractedfromthearchive.
Withtheverboseoption,itdisplaysadetailedtableof
contentsinaformatsimilartothatusedbylsl.
unconditional u
Overwritesexistingfilesregardlessoftheirmodification
times.Withoutthisoptioncpiowillnotoverwritea
morerecentlymodifiedfilewithanolderone;itsimply
displaysawarningmessage.
verbose v
Listsfilesastheyareprocessed.Withthelistoption,it
displaysadetailedtableofcontentsinaformatsimilarto
thatusedbylsl.
Discussion
GNUcpioversion2.5displayserroneoustruncatinginodenumbererrormessages;youcansafely
ignorethesemessages.
Withouttheunconditionaloption,cpiowillnotoverwriteamorerecentlymodifiedfilewithanolder
file.
Youcanusebothordinaryanddirectoryfilenamesasinputwhenyoucreateanarchive.Ifthenameofan
ordinaryfileappearsintheinputlistbeforethenameofitsparentdirectory,theordinaryfileappears
beforeitsparentdirectoryinthearchiveaswell.Thisordercanleadtoanavoidableerror:Whenyou
extractfilesfromthearchive,thechildhasnowheretogointhefilestructureifitsparenthasnotyetbeen
extracted.
Makingsurethatfilesappearaftertheirparentdirectoriesinthearchiveisnotalwaysasolution.One
problemoccursifthepreservemodificationtimeoptionisusedwhenextractingfiles.Becausethe
modificationtimeofaparentdirectoryisupdatedwheneverafileiscreatedwithinit,theoriginal
modificationtimeoftheparentdirectoryislostwhenthefirstfileiswrittentoit.
Thesolutiontothispotentialproblemistoensurethatallfilesappearbeforetheirparentdirectories
whencreatinganarchiveandtocreatedirectoriesasneededwhenextractingfilesfromanarchive.When
youusethistechnique,directoriesareextractedonlyafterallfileshavebeenwrittentothemandtheir
modificationtimesarepreserved.
Withthedepthoption,thefindutilitygeneratesalistoffileswithallchildrenappearinginthelist
beforetheirparentdirectories.Ifyouusethislisttocreateanarchive,thefilesareintheproperorder.
(Refertothefirstexampleinthenextsection.)Whenextractingfilesfromanarchive,the
makedirectoriesoptioncausescpiotocreateparentdirectoriesasneededandthe
preservemodificationtimeoptiondoesjustwhatitsnamesays.Usingthiscombinationofutilitiesand
optionspreservesdirectorymodificationtimesthroughacreate/extractsequence.
Thisstrategyalsosolvesanotherpotentialproblem.Sometimesaparentdirectorymaynothave
permissionssetsothatyoucanextractfilesintoit.Whencpioautomaticallycreatesthedirectorywith
makedirectories,youcanbeassuredofwritepermissiontothedirectory.Whenthedirectoryisextracted
fromthearchive(afterallthefilesarewrittenintothedirectory),itisextractedwithitsoriginal
permissions.
Examples
ThefirstexamplecreatesanarchiveofthefilesinJenny'shomedirectory,writingthearchivetoatape
drivesupportedbytheftapedriver:
$find/home/jenny-depth-print|cpio-oB>/dev/ftape
Thefindutilityproducesthefilenamesthatcpiousestobuildthearchive.Thedepthoptioncausesall
entriesinadirectorytobelistedbeforelistingthedirectorynameitself,makingitpossibleforcpioto
preservetheoriginalmodificationtimesofdirectories(seethepreceding"Discussion.")Usethemake-
directoriesandthepreserve-modification-timewhenyouextractfilesfromthisarchive(seethe
followingexamples).TheBoptionblocksthetapeat5,120bytesperblock.
Tocheckthecontentsofthearchivefileanddisplayadetailedlistingofthefilesitcontains,use
$cpio-itv</dev/ftape
ThefollowingcommandrestoresthefilesthatformerlywereinthememosubdirectoryofJenny'shome
directory:
$cpio-idm/home/jenny/memo/\*</dev/ftape
Thed(make-directories)optionensuresthatanysubdirectoriesthatwereinthememodirectoryarere-
createdasneeded.Them(preserve-modification-time)optionpreservesthemodificationtimesoffiles
anddirectories.Theasteriskintheregularexpressionisescapedtokeeptheshellfromexpandingit.
Thenextcommandisthesameastheprecedingcommandexceptthatitusestheno-absolute-filenames
optiontore-createthememodirectoryintheworkingdirectory,whichisnamedmemocopy.Thepattern
doesnotstartwiththeslashthatrepresentstherootdirectoryallowingcpiotocreatethefileswith
relativepathnames.
$pwd
/home/jenny/memocopy
$cpio-idm--no-absolute-filenameshome/jenny/memo/\*</dev/ftape
Thefinalexampleusesthefoptiontorestoreallthefilesinthearchiveexceptthosethatwereformerlyin
thememosubdirectory:
$cpio-ivmdf/home/jenny/memo/\*</dev/ftape
Thevoptionliststheextractedfilesascpioprocessesthearchive,verifyingthattheexpectedfilesare
extracted.
crontab:Maintainscrontabfiles
crontab[uuser-name]filename
crontab[uuser-name]option
Acrontabfileassociatesperiodictimes(suchas14:00onWednesdays)withcommands.Thecron
utilityexecuteseachcommandatthespecifiedtime.Whenyouareworkingasyourself,thecrontab
utilityinstalls,removes,lists,andeditsyourcrontabfile.Superusercanworkwithanyuser'scrontabfile.
Arguments
Thefirstformatcopiesthecontentsoffilename(whichcontainscrontabcommands)intothecrontabfile
oftheuserwhorunsthecommand.Whentheuserdoesnothaveacrontabfile,thisprocesscreatesanew
one;whentheuserhasacrontabfile,thisprocessoverwritesthefile.Whenyoureplacefilenamewitha
hyphen(),crontabreadscommandsfromstandardinput.
Thesecondformatlists,removes,oreditsthecrontabfile,dependingonwhichoptionyouspecify.
Options
Chooseonlyoneofthee,l,orroptions.Superusercanuseuwithoneoftheseoptions.
e
(edit)RunsthetexteditorspecifiedbytheVISUALorEDITORshellvariableonthe
crontabfile,enablingyoutoadd,change,ordeleteentries.Installsthemodifiedcrontab
filewhenyouexitfromtheeditor.
l(list)Displaysthecontentsofthecrontabfile.
r(remove)Deletesthecrontabfile.
uusername
(user)Worksonusername'scrontabfile.OnlySuperusercanusethisoptionand
Superusershouldalwaysusethisoption.
Notes
Thissectioncoverstheversionsofcron,crond,crontab,andcrontabfilesthatwerewrittenbyPaul
VixiehencethetermVixiecron.TheseversionsdifferfromanearlierversionofVixiecronaswellas
fromtheclassicSVR3syntax.ThisversionisPOSIXcompliant.
Usercrontabfilesarekeptinthe/var/spool/crondirectory,eachnamedwiththeusernameoftheuserthat
itbelongsto,ownedbyroot,andassociatedwiththeuser'sprimarygroup.
Thesystemutilitynamedcronreadsthecrontabfilesandrunsthecommands.Ifacommandlineina
crontabfiledoesnotredirectitsoutput,outputsenttostandardoutputandstandarderroraremailedtothe
userunlessyousettheMAILTOvariablewithinthecrontabfiletoadifferentusername.
Tomakethesystemadministrator'sjobeasier,thedirectoriesnamed/etc/cron.hourly,/etc/cron.daily,
/etc/cron.weekly,and/etc/cron.monthlyholdcrontabfilesthatarerunbyrun-parts,whichinturn
arerunbythe/etc/crontabfile.Eachofthesedirectoriescontainsfilesthatexecutesystemtasksatthe
intervalnamedbythedirectory.Superusercanaddfilestothesedirectoriesinsteadofaddinglinesto
root'scrontabfile.Atypical/etc/crontabfilelookslikethis:
$cat/etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
#run-parts
01****rootrun-parts/etc/cron.hourly
024***rootrun-parts/etc/cron.daily
224**0rootrun-parts/etc/cron.weekly
4241**rootrun-parts/etc/cron.monthly
Eachentryinacrontabfilebeginswithfivefieldsthatspecifywhenthecommandistorun(minute,hour,
dayofthemonth,month,anddayoftheweek).Thecronutilityinterpretsanasteriskappearinginplace
ofanumberasawildcardrepresentingallpossiblevalues.Intheday-of-the-weekfield,youcanuse
either7or0torepresentSunday.
Itisagoodpracticetostartcronjobsavariablenumberofminutesbeforeorafterthehour,halfhour,or
quarterhour.Whenyoustartthematthesetimes,itbecomeslesslikelythatmanyprocesseswillstartat
thesametime,potentiallyoverloadingthesystem.
Whencronstarts(usuallywhenthesystemisbooted),itreadsallofthecrontabfilesintomemory.The
cronutilitymostlysleepsbutwakesuponceaminute,reviewsallcrontabentriesithasstoredin
memory,andrunswhicheveronesareduetoberunatthattime.
/etc/cron.allow/etc/cron.deny
Superuserdetermineswhichuserscanruncrontabbycreating,editing,andremovingthe
/etc/cron.allowand/etc/cron.denyfiles.Whenyoucreateacron.denyfilewithnoentriesandno
cron.allowfileexists,everyonecanusecrontab.Whenthecron.allowfileexists,onlyuserslistedin
thatfilecanusecrontab,regardlessofthepresenceandcontentsofcron.deny.Otherwise,youcanlist
inthecron.allowfilethoseuserswhoshouldbeabletousecrontabandincron.denythosewho
shouldnotbeabletouseit.(Listingauserincron.denyisnotnecessarybecause,ifacron.allowfile
existsandtheuserisnotlistedinit,theuserwillnotbeabletousecrontabanyway.)
Examples
ThefollowingexampleusescrontabltolistthecontentsofJenny'scrontabfile(/var/spool/cron/jenny).
AllthescriptsthatJennyrunsareinher~/bindirectory.ThefirstlinesetstheMAILTOvariabletoalex
sothatAlexgetstheoutputfromcommandsrunfromJenny'scrontabfilethatisnotredirected.The
sat.jobscriptrunseverySaturday(day6)at2:05AM,twice.weekrunsat12:02AMonSundayand
Thursday(days0and4),andtwice.dayrunstwiceaday,everyday,at10AMand4PM.
$whoami
jenny
$crontab-l
MAILTO=alex
0502**6$HOME/bin/sat.job
0002**0,4$HOME/bin/twice.week
0510,16***$HOME/bin/twice.day
Toaddanentrytoyourcrontabfile,runthecrontabutilitywiththee(edit)option.SomeLinux
systemsuseaversionofcrontabthatdoesnotsupporttheeoption.Ifthelocalsystemrunssucha
version,youneedtomakeacopyofyourexistingcrontabfile,editit,andthenresubmitit,asinthe
examplethatfollows.Thel(list)optiondisplaysacopyofyourcrontabfile.
$crontab-l>newcron
$vimnewcron
...
$crontabnewcron
cut:Selectscharactersorfieldsfrominputlines
cut[options][file-list]
Thecututilityselectscharactersorfieldsfromlinesofinputandwritesthemtostandardoutput.
Characterandfieldnumberingstartwith1.
Arguments
Thefile-listisalistofordinaryfiles.Ifyoudonotspecifyanargumentorifyouspecifyahyphen()in
placeofafilename,cutreadsfromstandardinput.
Options
Acceptsthecommonoptionsdescribedonpage587.
characters=clist
cclist
Selectsthecharactersgivenbythecolumnnumbersin
clist.Thevalueofclistisoneormorecomma-separated
columnnumbersorcolumnranges.Arangeisspecified
bytwocolumnnumbersseparatedbyahyphen.Arange
ofnmeanscolumns1throughn;nmeanscolumnsn
throughtheendoftheline.
delimiter=dchar
ddchar
Specifiesdcharastheinputfielddelimiter.Alsospecifies
dcharastheoutputfielddelimiterunlessyouusethe
output-delimiteroption.ThedefaultdelimiterisaTAB
character.Quotecharactersasnecessarytoprotectthem
fromshellexpansion.
fields=flist fflist
Selectsthefieldsspecifiedinflist.Thevalueofflistis
oneormorecomma-separatedfieldnumbersorfield
ranges.Arangeisspecifiedbytwofieldnumbers
separatedbyahyphen.Arangeofnmeansfields1
throughn;nmeansfieldsnthroughthelastfield.The
fielddelimiterisaTABcharacterunlessyouusethe
delimiteroptiontochangeit.
output-delimiter=ochar
Specifiesocharastheoutputfielddelimiter.Thedefault
delimiteristheTABcharacter.Youcanspecifya
differentdelimiterbyusingthedelimiteroption.Quote
charactersasnecessarytoprotectthemfromshell
expansion.
Notes
Althoughlimitedinfunctionality,cutiseasytolearnanduseandisagoodchoicewhencolumnsand
fieldscanbeselectedwithoutusingpatternmatching.Sometimescutisusedwithpaste(page742).
Examples
Forthenexttwoexamples,assumethatanlslcommandproducesthefollowingoutput:
$ls-l
total2944
-rwxr-xr-x1zachpubs259Feb100:12countout
-rw-rw-r--1zachpubs9453Feb423:17headers
-rw-rw-r--1zachpubs1474828Jan1414:15memo
-rw-rw-r--1zachpubs1474828Jan1414:33memos_save
-rw-rw-r--1zachpubs7134Feb423:18tmp1
-rw-rw-r--1zachpubs4770Feb423:26tmp2
-rw-rw-r--1zachpubs13580Nov708:01typescript
Thefollowingcommandoutputsthepermissionsofthefilesintheworkingdirectory.Thecututilitywith
thecoptionselectscharacters2through10fromeachinputline.Thecharactersinthisrangearewritten
tostandardoutput.
$ls-l|cut-c2-10
otal2944
rwxr-xr-x
rw-rw-r--
rw-rw-r--
rw-rw-r--
rw-rw-r--
rw-rw-r--
rw-rw-r--
Thenextcommandoutputsthesizeandnameofeachfileintheworkingdirectory.Thistimethefoption
selectsthefifthandninthfieldsfromtheinputlines.ThedoptiontellscuttouseSPACEs,notTABs,as
delimiters.TheTRutility(page804)withthesoptionchangessequencesofmorethanoneSPACE
characterintoasingleSPACE;otherwise,cutcountstheextraSPACEcharactersasseparatefields.
$ls-l|tr-s''''|cut-f5,9-d''
259countout
9453headers
1474828memo
1474828memos_save
7134tmp1
4770tmp2
13580typescript
Thelastexampledisplaysalistoffullnamesasstoredinthefifthfieldofthe/etc/passwdfile.Thed
optionspecifiesthatthecoloncharacterbeusedasthefielddelimiter.
$cat/etc/passwd
root:x:0:0:Root:/:/bin/sh
jenny:x:401:50:JennyChen:/home/jenny:/bin/zsh
alex:x:402:50:AlexWatson:/home/alex:/bin/bash
scott:x:504:500:ScottAdams:/home/scott:/bin/tcsh
hls:x:505:500:HelenSimpson:/home/hls:/bin/bash
$cut-d:-f5/etc/passwd
Root
JennyChen
AlexWatson
ScottAdams
HelenSimpson

date:Displaysorsetsthesystemtimeanddate
date[options][+format]
date[options][newdate]
Thedateutilitydisplaysthetimeanddateknowntothesystem.Superusercanusedatetochangethe
systemclock.
Arguments
The+formatargumentspecifiestheformatfortheoutputofdate.Theformatstringconsistingoffield
descriptorsandtextfollowsaplussign(+).Thefielddescriptorsareprecededbypercentsigns,andeach
oneisreplacedbyitsvalueintheoutput.TableV-10listssomeofthefielddescriptors.
TableV-10.Selectedfielddescriptors
Descriptor Meaning
%a AbbreviatedweekdaySuntoSat
%A UnabbreviatedweekdaySundaytoSaturday
%b AbbreviatedmonthJantoDec
%B UnabbreviatedmonthJanuarytoDecember
%c Dateandtimeindefaultformatusedbydate
%d Dayofthemonth01to31
%D Dateinmm/dd/yyformat
%H Hour00to23
%I Hour00to12
%j Juliandate(dayoftheyear001to366)
%m Monthoftheyear01to12

%M Minutes00to59
%n NEWLINEcharacter
%P AMorPM
%r TimeinAM/PMnotation
%s NumberofsecondssincethebeginningofJanuary1,1970
%S Seconds00to60(the60accommodatesleapseconds)
%t TABcharacter
%T TimeinHH:MM:SSformat
%w Dayoftheweek0to6(0=Sunday)
%y Lasttwodigitsoftheyear00to99
%Y Yearinfour-digitformat(forexample,2005)
%Z Timezone(forexample,PDT)
Bydefaultdatezerofillsnumericfields.Placeanunderscore(_)immediatelyfollowingthepercent
sign(%)foraspecificfieldtocausedatetoblankfillthefieldandwithahyphen()tocausedatenot
tofillthefieldthatis,toleftjustifythefield.
Thedateutilityassumesthat,inaformatstring,anycharacterthatisnotapercentsign,anunderscoreor
ahyphenfollowingthepercentsign,orafielddescriptorisordinarytextandcopiesittostandardoutput.
Youcanuseordinarytexttoaddpunctuationtothedateandtoaddlabels(forexample,youcanputthe
wordDATE:infrontofthedate).Surroundtheformatargumentwithsinglequotationmarksifitcontains
SPACEsorothercharactersthathaveaspecialmeaningtotheshell.
Settingthedate
WhenSuperuserspecifiesnewdate,thesystemchangesthesystemclocktoreflectthenewdate.The
newdateargumenthastheformat
nnddhhmm[[cc]yy][.ss]
wherennisthenumberofthemonth(0112),ddisthedayofthemonth(0131),hhisthehourbasedona
24-hourclock(0023),andmmistheminutes(0059).Whenyouchangethedate,youmustspecifyatleast
thesefields.
Theoptionalccspecifiesthefirsttwodigitsoftheyear(thevalueofthecenturyminus1),andyy
specifiesthelasttwodigitsoftheyear.Youcanspecifyyyorccyyfollowingmm.Whenyoudonot
specifyayear,dateassumesthattheyearhasnotchanged.
Youcanspecifythenumberofsecondspastthestartoftheminutewith.ss.
Options
Acceptsthecommonoptionsdescribedonpage587.
reference=file rFile
Displaysthemodificationdateandtimeoffileinplace
ofthecurrentdateandtime.
utcoruniversal u
DisplaysorsetsthetimeanddateusingUniversal
CoordinatedTime(UTC,page908;alsocalled
GreenwichMeanTime[GMT]).
Notes
Ifyousetupalocaledatabase,dateusesthatdatabasetosubstitutetermsappropriatetoyourlocale
(page885).
Examples
Thefirstexampleshowshowtosetthedatefor2:07:30PMonAugust19withoutchangingtheyear:
#date08191407.30
SatAug1914:07:30PDT2005
Thenextexampleshowstheformatargument,whichcausesdatetodisplaythedateinacommonly
usedformat:
$date'+Todayis%h%d,%Y'
TodayisAug19,2005
dd:Convertsandcopiesafile
dd[arguments]
Thedd(device-to-devicecopy)utilityconvertsandcopiesafile.Theprimaryuseofddistocopyfiles
toandfromsuchdevicesastapeandfloppydrives.Oftenddcanhandlethetransferofinformationtoand
fromotheroperatingsystemswhenothermethodsfail.Arichsetofargumentsgivesyouprecisecontrol
overthecharacteristicsofthetransfer.
Arguments
Acceptsthecommonoptionsdescribedonpage587.
Bydefaultddcopiesstandardinputtostandardoutput.
bs=n(blocksize)Readsandwritesnbytesatatime.Thisargumentoverrides
theibsandobsarguments.
cbs=n(conversionblocksize)Whenperformingdataconversionduringthe
copy,convertsnbytesatatime.
Conv=type[,type…]
Byapplyingconversiontypesintheordergivenonthecommandline,
convertsthedatathatisbeingcopied.Thetypesmustbeseparatedby
commaswithnoSPACEs.ThetypesofconversionsareshowninTable
V-11.
Restrictstonumblocksthenumberofblocksofinputthatddcopies.

count=numblocks Thesizeofeachblockisthenumberofbytesspecifiedbytheibs
argument.
ibs=n(inputblocksize)Readsnbytesatatime.
if=filename (inputfile)Readsfromfilenameinsteadoffromstandardinput.You
canuseadevicenameforfilenametoreadfromthatdevice.
obs=n(outputblocksize)Writesnbytesatatime.
of=filename (outputfile)Writestofilenameinsteadoftostandardoutput.Youcan
useadevicenameforfilenametowritetothatdevice.
seek=numblocks Skipsnumblocksblocksofoutputbeforewritinganyoutput.Thesizeof
eachblockisthenumberofbytesspecifiedbytheobsargument.
skip=numblocks Skipsnumblocksblocksofinputbeforestartingtocopy.Thesizeof
eachblockisthenumberofbytesspecifiedbytheibsargument.
TableV-11.Conversiontypes
type Meaning
ascii ConvertsEBCDIC-encodedcharacterstoASCII,allowingyoutoreadtapes
writtenonIBMmainframeandsimilarcomputers.
block
Eachtimealineofinputisread(thatis,asequenceofcharactersterminated
withaNEWLINEcharacter),outputsablockoftextwithouttheNEWLINE.
Eachoutputblockhasthesizegivenbytheobsorbsargumentandis
createdbyaddingtrailingSPACEcharacterstothetextuntilitistheproper
size.
ebcdic ConvertsASCII-encodedcharacterstoEBCDIC,allowingyoutowritetapes
foruseonIBMmainframeandsimilarcomputers.
unblock Performstheoppositeoftheblockconversion.
lcase Convertsuppercaseletterstolowercasewhilecopyingdata.
noerror
Ifareaderroroccurs,ddnormallyterminates.Thisconversionallowsddto
continueprocessingdata.Thisconversionisusefulwhenyouaretryingto
recoverdatafrombadmedia.
notrunc Doesnottruncatetheoutputfilebeforewritingtoit.
ucase Convertslowercaseletterstouppercasewhilecopyingdata.
Notes
Youcanusethestandardmultiplicativesuffixestomakeiteasiertospecifylargeblocksizes.SeeTable
V-1onpage586.
Examples
Youcanuseddtocreateafilefilledwithpseudo-randombytes.
$ddif=/dev/urandomof=randfile2bs=1count=100
Theprecedingcommandreadsfromthe/dev/urandomfile(aninterfacetothekernel'srandomnumber
generator)andwritestothefilenamedrandfile.Theblocksizeis1andthecountis100sorandfileis
100byteslong.Forbytesthataremorerandom,youcanreadfrom/dev/random.Seetheurandomand
randommanpagesformoreinformation.
Wipingafile
Youcanuseasimilartechniquetowipedatafromafilebeforedeletingit,makingitalmostimpossibleto
recoverdatafromadeletedfile.Youmightwanttowipeafileforsecurityreasons.Wipeafileseveral
timesforaddedsecurity.
Inthefollowingexample,lsshowsthesizeofthefilenamedsecret;dd,withablocksizeof1anda
countcorrespondingtothenumberofbytesinsecret,thenwipesthefile.Theconv=notruncargument
ensuresthatddwritesoverthedatainthefileandnotanotherplaceonthedisk.
$ls-lsecret
-rw-rw-r--1maxmax2494Feb600:56secret
$ddif=/dev/urandomof=secretbs=1count=2494conv=notrunc
2494+0recordsin
2494+0recordsout
$rmsecret
Copyingadiskette
Youcanuseddtomakeanexactcopyofafloppydiskette.Firstcopythecontentsofthediskettetoafile
ontheharddriveandthencopythefilefromtheharddisktoaformatteddiskette.Thistechniqueworks
regardlessofwhatisonthefloppydiskette.ThenextexamplecopiesaDOS-formatteddiskette.The
mount,ls,umountsequencesatthebeginningandendoftheexampleverifythattheoriginaldiskette
andthecopyholdthesamefiles.Youcanusethefloppy.copyfiletomakemultiplecopiesofthediskette.
#mount-tmsdos/dev/fd0H1440/mnt
#ls/mnt
abprint.datbti.inisetup.inssupfiles.zwbt.z
adbook.zsetup.exesetup.pkgtelephon.z
#umount/mnt
#ddif=/dev/fd0ibs=512>floppy.copy
2880+0recordsin
2880+0recordsout
#ls-lfloppy.copy
-rw-rw-r--1alexspeedy1474560Oct1105:43floppy.copy
#ddif=floppy.copybs=512of=/dev/fd0
2880+0recordsin
2880+0recordsout
#mount-tmsdos/dev/fd0H1440/mnt
#ls/mnt
abprint.datbti.inisetup.inssupfiles.zwbt.z
adbook.zsetup.exesetup.pkgtelephon.z
#umount/mnt
df:Displaysdiskspaceusage
df[options][filesystem-list]
Thedf(diskfree)utilityreportsonthetotalspaceandthefreespaceoneachmounteddevice.
Arguments
Whenyoucalldfwithoutanargument,itreportsonthefreespaceoneachofthecurrentlymounted
devices.
Thefilesystem-listisanoptionallistofoneormorepathnamesthatspecifythefilesystemsyouwantthe
reporttocover.Youcanrefertoamountedfilesystembyitsdevicepathnameorbythepathnameofthe
directoryitismountedon.
Options
all aReportsonfilesystemswithasizeof0blocks,suchas/dev/proc.
Normallydfdoesnotreportonthesefilesystems.
block-size=sz Bsz
Theszspecifiestheunitsthatthereportuses(thedefaultis1-
kilobyteblocks).Forexample,block-size=Mdisplayssizesin
1,048,576-byteunitswhileblock-size=MBdisplayssizesin
1,000,000-byteunits.SeeTableV-1onpage586foracompletelist
ofmultiplicativesuffixes.Seealsothehuman-readableoption.
human-readable
h
DisplayssizesinK(kilobyte),M(megabyte),andG(gigabyte)
blocks,asisappropriate.Usespowersof1,024;usesiforpowers
of1,000.
inodes iReportsthenumberofinodes(page880)thatareusedandfree
insteadofreportingonblocks.
kSameasblock-size=K.
local lDisplayslocalfilesystemsonly.
type=fstype tfstype
Reportsinformationonlyaboutthefilesystemsoftypefstype,such
asDOSorNFS.Repeatthisoptiontoreportonseveraltypesof
filesystems.
exclude-
type=fstype
xfstype
Reportsinformationonlyaboutthefilesystemsnotoftypefstype.
Examples
Inthefollowingexample,dfdisplaysinformationaboutallmountedfilesystemsonthelocalsystem:
$df
Filesystem1k-blocksUsedAvailableUse%Mountedon
/dev/hda1215179205326413875484%/
/dev/hda1155224846987533%/boot
/dev/hda8101192811026885025611%/free1
/dev/hda91011928306249299003%/free2
/dev/hda101130540789929941207%/free3
/dev/hda540320921988080183918852%/home
/dev/hda71011928609604640%/tmp
/dev/hda62522048824084156984834%/usr
zach:/c2096160181139228476886%/zach_c
zach:/d2096450193509716135392%/zach_d
Nextdfiscalledwiththelandhoptions,generatingahuman-readablelistoflocalfilesystems.The
sizesinthislistingaregivenintermsofmegabytesandgigabytes.TheNFSmountedfilesystems(from
zach)arenotvisible.
$df-lh
FilesystemSizeUsedAvailUse%Mountedon
/dev/hda121.4G52M1.3G4%/
/dev/hda115M4.7M9.6M33%/boot
/dev/hda8988M108M830M11%/free1
/dev/hda9988M30M908M3%/free2
/dev/hda101.1G77M971M7%/free3
/dev/hda53.8G1.9G1.8G52%/home
/dev/hda7988M60k938M0%/tmp
/dev/hda62.4G805M1.5G34%/usr
Thenextexampledisplaysinformationaboutthe/free2partitioninmegabyteunits:
$df-BM/free2
Filesystem1M-blocksUsedAvailableUse%Mountedon
/dev/hda9988309083%/free2
ThefinalexampledisplaysinformationaboutNFSfilesystemsinhuman-readableterms:
$df-htnfs
FilesystemSizeUsedAvailUse%Mountedon
zach:/c2.0G1.7G278M86%/zach_c
zach:/d2.0G1.8G157M92%/zach_d
diff:Displaysthedifferencesbetweentwofiles
diff[options]file1file2
diff[options]file1directory
diff[options]directoryfile2
diff[options]directory1directory2
Thediffutilitydisplaysline-by-linedifferencesbetweentwofiles.Bydefaultdiffdisplaysthe
differencesasinstructionsyoucanusetoeditoneofthefilestomakeitthesameastheother.
Arguments
Thefile1andfile2arepathnamesofordinaryfilesthatdiffworkson.Whenthedirectoryargumentis
usedinplaceoffile2,difflooksforafileindirectorywiththesamenameasfile1.Itworkssimilarly
whendirectoryreplacesfile1.Whenyouspecifytwodirectoryarguments,diffcomparesthefilesin
directory1withthefilesthathavethesamesimplefilenamesindirectory2.
Options
Acceptsthecommonoptionsdescribedonpage587,withoneexception:Whenoneoftheargumentsisa
directoryandtheotherisanordinaryfile,youcannotcomparetostandardinput.
ignorespace-change
bIgnoreswhitespace(SPACEsandTABs)attheendsoflinesand
considersotherstringsofwhitespacetobeequal.
ignoreblanklines
BIgnoresdifferencesthatinvolveonlyblanklines.
context[=lines]C[lines]
Displaysthesectionsofthetwofilesthatdiffer,includinglines
lines(thedefaultis3)aroundeachlinethatdifferstoshowthe
context.Eachlineinfile1thatismissingfromfile2isprecededby
;eachextralineinfile2isprecededby+;andlinesthathave
differentversionsinthetwofilesaremarkedwith!.Whenlines
thatdifferarewithinlineslinesofeachother,theyaregrouped
togetherintheoutput.
ed e
Createsandsendstostandardoutputascriptfortheededitor,
whichwilleditfile1tomakeitthesameasfile2.Youmustaddw
(write)andq(quit)instructionstotheendofthescriptifyouplan
toredirectinputtoedfromthescript.Whenyouuseed,diff
displaysthechangesinreverseorder:Changestotheendofthefile
arelistedbeforechangestothetop,preventingearlychangesfrom
affectinglaterchangeswhenthescriptisusedasinputtoed.For
example,ifalinenearthetopweredeleted,subsequentline
numbersinthescriptwouldbewrong.
ignore-case iIgnoresdifferencesincasewhencomparingfiles.
new-file N
Whencomparingdirectories,whenafileispresentinoneofthe
directoriesonly,considersittobepresentandemptyintheother
directory.
show-c-function
pShowswhichCfunctioneachchangeaffects.
brief qDoesnotdisplaythedifferencesbetweenlinesinthefiles.Instead,
diffreportsonlythatthefilesdiffer.
recursive rWhenusingdifftocomparethefilesintwodirectories,causes
thecomparisonstoextendthroughsubdirectoriesaswell.
unified[=lines]ULines
Usestheeasier-to-readunifiedoutputformat.Seethediscussionof
diffonpage51formoredetailandanexample.Thelinesisthe
numberoflinesofcontext;thedefaultisthree.
ignore-all-space
w(whitespace)Ignoreswhitespacewhencomparinglines.
width=columns
Wcolumns
Setsthewidthofthecolumnsthatdiffusestodisplaytheoutput
tocolumns.Thisoptionisusefulwiththeside-by-sideoption.The
sdiffutilityusesalowercasewtoperformthesamefunction:w
columns.
side-by-side y
Displaysoutputinaside-by-sideformat.Thisoptiongeneratesthe
sameoutputassdiff.Usethewidth=columnsoptionwiththis
option.
Notes
Thesdiffutilityissimilartodiffbutitsoutputmaybeeasiertoread.Thediffside-by-sideoption
producesthesameoutputassdiff.Seethe"Examples"sectionandrefertothediffandsdiffman
andinfopagesformoreinformation.
Youcanusethediff3utilitytocomparethreefiles.

Discussion
Whenyouusediffwithoutanyoptions,itproducesaseriesoflinescontainingAdd(a),Delete(d),and
Change(c)instructions.Eachoftheselinesisfollowedbythelinesfromthefilethatyouneedtoadd,
delete,orchangetomakethefilesthesame.Alessthansymbol(<)precedeslinesfromfile1.Agreater
thansymbol(>)precedeslinesfromfile2.ThediffoutputappearsintheformatshowninTableV-12.
Apairoflinenumbersseparatedbyacommarepresentsarangeoflines;asinglelinenumberrepresents
asingleline.
TableV-12.diffoutput
Instruction Meaning(tochangefile1tofile2)
line1aline2,line3
>linesfromfile2 Appendlinesline2throughline3fromfile2afterline1infile1.
line1,line2dline3
<linesfromfile1 Deleteline1throughline2fromfile1.
line1,line2c
line3,line4
<linesfromfile1
>linesfromfile2
Changeline1throughline2infile1toline3throughline4from
file2.
Thediffutilityassumesthatyouwillconvertfile1tofile2.Thelinenumberstotheleftofeachofthea,
c,ordinstructionsalwayspertaintofile1;thelinenumberstotherightoftheinstructionsapplytofile2.
Toconvertfile2tofile1,rundiffagain,reversingtheorderofthearguments.
Examples
Thefirstexampleshowshowdiffdisplaysthedifferencesbetweentwoshort,similarfiles:
$catm
aaaaa
bbbbb
ccccc
$catn
aaaaa
ccccc
$diffmn
2d1
<bbbbb
Thedifferencebetweenfilesmandnisthatthesecondlineoffilem(bbbbb)ismissingfromfilen.The
firstlinethatdiffdisplays(2d1)indicatesthatyouneedtodeletethesecondlinefromfile1(m)to
makeitthesameasfile2(n).Thenextlinediffdisplaysstartswithalessthansymbol(<),indicating
thatthislineoftextisfromfile1.Inthisexample,youdonotneedthisinformationallyouneedtoknowis
thelinenumbersothatyoucandeletetheline.
Theside-by-sideoptionandthesdiffutility,bothwiththeoutputwidthsetto30columns(characters),
displaythesameoutput.Intheoutputalessthansymbolpointstotheextralineinfilem,whereas
diff/sdiffleavesablanklineinfilenwheretheextralinewouldgotomakethefilesthesame.
$diff--side-by-side--width=30mn
aaaaaaaaaa
bbbbb<
cccccccccc
$sdiff-w30mn
aaaaaaaaaa
bbbbb<
cccccccccc
Thenextexampleusesthesamemfileandanewfile,p,toshowdiffissuingana(append)instruction:
$catp
aaaaa
bbbbb
rrrrr
ccccc
$diffmp
2a3
>rrrrr
Intheprecedingexample,diffissuestheinstruction2a3toindicatethatyoumustappendalinetofile
m,afterline2,tomakeitthesameasfilep.Thesecondlinethatdiffdisplaysindicatesthatthelineis
fromfilep(thelinebeginswith>,indicatingfile2).Inthisexample,youneedtheinformationonthisline;
theappendedlinemustcontainthetextrrrrr.
Thenextexampleusesfilemagain,thistimewithfiler,toshowhowdiffindicatesalinethatneedsto
bechanged:
$catr
aaaaa
-q
ccccc
$diffmr
2c2
<bbbbb
---
>-q
Thedifferencebetweenthetwofilesisinline2:Filemcontainsbbbbb,andfilercontainsq.Thediff
utilitydisplays2c2toindicatethatyouneedtochangeline2.Afterindicatingthatachangeisneeded,
diffshowsthatyoumustchangeline2infilem(bbbbb)toline2infiler(q)tomakethefilesthe
same.Thethreehyphensindicatetheendofthetextinfilemthatneedstobechangedandthestartofthe
textinfilerthatistoreplaceit.
Comparingthesamefilesusingtheside-by-sideandwidthoptions(yandW)yieldsaneasier-to-read
result.Thepipesymbol(|)indicatesthatthelineononesidemustreplacethelineontheothersideto
makethefilesthesame:
$diff-y-W30mr
aaaaaaaaaa
bbbbb|-q
cccccccccc
Thenextexamplescomparethetwofilesqandv:
$catq$catv
MondayMonday
TuesdayWednesday
WednesdayThursday
ThursdayThursday
SaturdayFriday
SundaySaturday
Sundae
Runninginside-by-sidemodediffshowsthatTuesdayismissingfromfilev,thereisonlyone
Thursdayinfileq(therearetwoinfilev),andFridayismissingfromfileq.ThelastlineisSundayin
fileqandSundaeinfilev:diffindicatesthattheselinesaredifferent.Youcanchangefileqtobethe
sameasfilevbyremovingTuesday,addingoneThursdayandFriday,andsubstitutingSundaefromfile
vforSundayfromfileq.Alternatively,youcanchangefilevtobethesameasfileqbyaddingTuesday,
removingoneThursdayandFriday,andsubstitutingSundayfromfileqforSundaefromfilev.
$diff-y-W30qv
MondayMonday
Tuesday<
WednesdayWednesday
ThursdayThursday
>Thursday
>Friday
SaturdaySaturday
Sunday|Sundae
Contextdiff
Withthecontextoption(calledacontextdiff),diffdisplaysoutputthattellsyouhowtoturnthefirst
fileintothesecond.Thetoptwolinesidentifythefilesandshowthatqisrepresentedbyasterisks,
whereasvisrepresentedbyhyphens.Followingarowofasterisksthatindicatesthestartofahunkoftext
isarowofasteriskswiththenumbers1,6inthemiddle.Thislineindicatesthattheinstructionsinthefirst
sectiontellyouwhattoremovefromorchangeinfileqnamely,lines1through6(thatis,allthelinesof
fileq;inalongerfileitwouldmarkthefirsthunk).Thehyphenonthenextlinemeansthatyouneedto
removethelinewithTuesday.Thelinewithanexclamationpointindicatesthatyouneedtoreplacethe
linewithSundaywiththecorrespondinglinefromfilev.Therowofhyphenswiththenumbers1,7inthe
middleindicatesthatthenextsectiontellsyouwhichlinesfromfilevlines1through7youneedtoaddor
changeinfileq.YouneedtoaddasecondlinewithThursdayandalinewithFriday,andyouneedto
changeSundayinfileqtoSundae(fromfilev).
$diff--contextqv
***qMonAug2218:26:452005
---vMonAug2218:27:552005
***************
***1,6****
Monday
-Tuesday
Wednesday
Thursday
Saturday
!Sunday
---1,7----
Monday
Wednesday
Thursday
+Thursday
+Friday
Saturday
!Sundae
du:Displaysinformationondiskusagebyfile
du[options][path-list]
Thedu(diskusage)utilityreportshowmuchdiskspaceisoccupiedbyadirectory(alongwithallits
subdirectoriesandfiles)orafile.Bydefaultdudisplaysthenumberof1,024-byteblocksthatare
occupiedbythedirectoryorfile.
Arguments
Withoutanyarguments,dudisplaysinformationabouttheworkingdirectoryanditssubdirectories.The
path-listspecifiesthedirectoriesandfilesyouwantinformationon.
Options
Withoutanyoptions,dudisplaysthetotalstorageusedforeachargumentinpath-list.Fordirectoriesdu
displaysthistotalafterrecursivelylistingthetotalsforeachsubdirectory.
all aDisplaysthespaceusedbyallordinaryfilesalongwiththetotal
foreachdirectory.
block-size=sz Bsz
Theszspecifiestheunitsthereportuses.Forexample,block-
size=Mdisplayssizesin1,048,576-byteunitswhileblock-
size=MBdisplayssizesin1,000,000-byteunits.SeeTableV-1on
page586foracompletelistofmultiplicativesuffixes.Seealsothe
human-readableoption.
total cDisplaysagrandtotalattheendoftheoutput.
human-readable
h
DisplayssizesinK(kilobyte),M(megabyte),andG(gigabyte)
blocks,asappropriate.Usespowersof1,024;usesiforpowers
of1,000.
kilobytes kDisplayssizesin1-kilobyteblocks.
dereference LIncludesthesizesofthefilessymboliclinkspointto,notthe
symboliclinksthemselves.Thedefaultisno-dereference.
megabytes mDisplayssizesin1-megabyteblocks.
no-dereference PIncludesthesizesofsymboliclinks,notthefilesthatthelinks
pointto(default).
summarize sDisplaysonlythetotalsizeforeachdirectoryorfileyouspecify
onthecommandline;subdirectorytotalsarenotdisplayed.
one-file-system xReportsonlyonfilesanddirectoriesonthesamefilesystemas
thatoftheargumentbeingprocessed.
Examples
Inthefirstexample,dudisplayssizeinformationaboutsubdirectoriesintheworkingdirectory.Thelast
linecontainsthegrandtotalfortheworkingdirectoryanditssubdirectories.
$du
26./Postscript
4./RCS
47./XIcon
4./Printer/RCS
12./Printer
105.
Thetotal(105)isthenumberofblocksoccupiedbyallplainfilesanddirectoriesundertheworking
directory.Allfilesarecounted,eventhoughdudisplaysonlythesizesofdirectories.
Nextusingthesummarizeoption,dudisplaysthetotalforeachofthedirectoriesin/homebutnotfor
anysubdirectories:
#du--summarize/home/*
68/home/Desktop
1188/home/doug
100108/home/dump
62160/home/ftp
6540/home/httpd
16/home/lost+found
1862104/home/alex
176/home/max
88/home/jenny
4/home/samba
4/home/tom
Addtothepreviousexamplethetotaloptionandyougetthesamelistingwithagrandtotalattheend:
#du--summarize--total/home/*
68/home/Desktop
...
4/home/tom
2032456total
Ifyoudonothavereadpermissionforafileordirectorythatduencounters,dusendsawarningto
standarderrorandskipsthatfileordirectory.Thefollowingexampleusesthes(summarize),h(human-
readable),andc(total)options:
$du-shc/usr/*
112M/usr/X11R6
161M/usr/bin
4.0K/usr/dict
4.0K/usr/doc
4.0K/usr/etc
3.9M/usr/games
...
du:cannotchangetodirectory'/usr/lost+found':Permissiondenied
30M/usr/sbin
du:cannotchangetodirectory'/usr/share/ssl/CA':Permissiondenied
797M/usr/share
188M/usr/src
2.2Gtotal
Thefinalexampledisplays,inhuman-readableformat,thetotalsizeofallthefilestheusercanreadinthe
/usrfilesystem.Redirectingstandarderrorto/dev/nulldiscardsallwarningsaboutfilesanddirectories
thatareunreadable.
$du--human-readable--summarize/usr2>/dev/null
2.2G/usr
echo:Displaysamessage
echo[options]message
Theechoutilitycopiesitsarguments,followedbyaNEWLINE,tostandardoutput.TheBourneAgain
andTCShellseachhasanechobuiltinthatworkssimilarlytotheechoutility.
Arguments
Themessageconsistsofoneormorearguments,whichcanincludequotedstrings,ambiguousfile
references,andshellvariables.ASPACEseparateseachargumentfromthenext.Theshellrecognizes
unquotedspecialcharactersinthearguments.Forexample,theshellexpandsanasteriskintoalistof
filenamesintheworkingdirectory.
Options
Youcanconfigurethetcshechobuiltintotreatbackslashescapesequencesandthenoptionin
differentways.Refertoecho_styleinthetcshmanpage.Thetypicaltcshconfigurationrecognizes
thenoption,enablesbackslashescapesequences,andignorestheeandEoptions.

eEnablestheinterpretationofbackslashescapesequencessuchas\n.
ESuppressestheinterpretationofbackslashescapesequencessuchas\n
(bashandutilitydefault).
help
Givesashortsummaryofhowtouseecho.Thesummaryincludesalistof
thebackslashescapesequencesinterpretedbyecho.Thisoptionworksonly
withtheechoutility(/bin/echo)andnotwiththeechobuiltins.
nSuppressestheNEWLINEterminatingthemessage.
Notes
Youcanuseechotosendmessagestothescreenfromashellscript.Seepage129foradiscussionof
howtouseechotodisplayfilenamesusingwildcardcharacters.
Theechoutilityandbuiltinsprovideanescapenotationtorepresentcertainnonprintingcharactersin
message(TableV-13).Youmustusetheeoptioninorderforthesebackslashescapesequencestowork
withtheechoutilityandthebashechobuiltin.Typicallyyoudonotneedtheeoptionwiththetcsh
echobuiltin.
TableV-13.Backslashescapesequences
Sequence Meaning
\a Bell
\c SuppresstrailingNEWLINE
\n NEWLINE
\t HORIZONTALTAB
\v VERTICALTAB
\\ BACKSLASH
Examples
Followingaresomeechocommands.Thesecommandswillworkwiththeechoutility(/bin/echo)and
thebashandtcshechobuiltins,exceptforthelast,whichmaynotneedtheeoptionundertcsh.
$echo"Thiscommanddisplaysastring."
Thiscommanddisplaysastring.
$echo-n"ThisdisplayedstringisnotfollowedbyaNEWLINE."
ThisdisplayedstringisnotfollowedbyaNEWLINE.$echohi
hi
$echo-e"Thismessagecontains\vaverticaltab."
Thismessagecontains
averticaltab.
$
Thefollowingexamplescontainmessageswiththebackslashescapesequence\c.Inthefirstexample,the
shellprocessestheargumentsbeforecallingecho.Whentheshellseesthe\c,itreplacesthe\cwiththe
characterc.Thenextthreeexamplesshowhowtoquotethe\csothattheshellpassesittoecho,which
thendoesnotappendaNEWLINEtotheendofthemessage.Thefirstfourexamplesarerununderbash
andrequiretheeoption.Thefinalexamplerunsundertcsh,whichtypicallydoesnotusethisoption.
$echo-eThereisanewlineafterthis.\c
Thereisanewlineafterthis.c
$echo-e'Thereisnonewlineafterthis.\c'
Thereisnonewlineafterthis.$
$echo-e"Thereisnonewlineafterthis.\c"
Thereisnonewlineafterthis.$
$echo-eThereisnonewlineafterthis.\\c
Thereisnonewlineafterthis.$
$tcsh
tcsh$echo'Thereisnonewlineafterthis.\c'
Thereisnonewlineafterthis.$
Youcanusethenoptioninplaceofeand\c.
expr:Evaluatesanexpression
exprexpression
Theexprutilityevaluatesanexpressionandsendstheresulttostandardoutput.Itevaluatescharacter
stringsthatrepresenteithernumericornonnumericvalues.Operatorsareusedwiththestringstoform
expressions.
Arguments
Theexpressioniscomposedofstringsinterspersedwithoperators.Eachstringandoperatorconstitutea
distinctargumentthatyoumustseparatefromotherargumentswithaSPACE.Youmustquoteoperators
thathavespecialmeaningstotheshell(forexample,themultiplicationoperator,*).
Thefollowinglistofexproperatorsisgiveninorderofdecreasingprecedence.Eachoperatorwithina
groupofoperatorshasthesameprecedence.Youcanchangetheorderofevaluationbyusingparentheses.
(comparison)Comparestwostrings,startingwiththefirstcharacterineachstringand
endingwiththelastcharacterinthesecondstring.Thesecondstringisaregular
:expressionwithanimpliedcaret(^)asitsfirstcharacter.Ifthereisamatch,expr
displaysthenumberofcharactersinthesecondstring.Ifthereisnomatch,expr
displaysazero.
*(multiplication)
/(division)
%(remainder)
Workonlyonstringsthatcontainthenumerals0through9andoptionallyaleading
minussign.Convertstringstointegernumbers,performthespecifiedarithmetic
operationonnumbers,andconverttheresultbacktoastringbeforesendingitto
standardoutput.
+(addition)
(subtraction)
Functioninthesamemannerastheprecedinggroupofoperators.
<(lessthan)
<= (lessthanorequalto)
=or
== (equalto)
!= (notequalto)
>= (greaterthanorequalto)
>(greaterthan)
Relationaloperatorsworkonbothnumericandnonnumericarguments.Ifoneorbothof
theargumentsarenonnumeric,thecomparisonisnonnumeric,usingthemachine
collatingsequence(typicallyASCII).Ifbothargumentsarenumeric,thecomparisonis
numeric.Theexprutilitydisplaysa1(one)ifthecomparisonistrueanda0(zero)ifit
isfalse.
&(AND)Evaluatesbothofitsarguments.Ifneitheris0oranullstring,exprdisplaysthe
valueofthefirstargument.Otherwise,itdisplaysa0.Youmustquotethisoperator.
|
(OR)Evaluatesthefirstargument.Ifitisneither0noranullstring,exprdisplaysthe
valueofthefirstargument.Otherwise,itdisplaysthevalueofthesecondargument.You
mustquotethisoperator.
Notes
Theexprutilityreturnsanexitstatusof0(zero)iftheexpressionevaluatestootherthananullstringor
thenumber0,astatusof1iftheexpressionisnullor0,andastatusof2iftheexpressionisinvalid.
Althoughexprandthisdiscussiondistinguishbetweennumericandnonnumericarguments,allarguments
toexprarenonnumeric(characterstrings).Whenapplicable,exprattemptstoconvertanargumenttoa
number(forexample,whenusingthe+operator).Ifastringcontainscharactersotherthan0through9
withanoptionalleadingminussign,exprcannotconvertit.Specifically,ifastringcontainsaplussign
oradecimalpoint,exprconsidersittobenonnumeric.Ifbothargumentsarenumeric,thecomparisonis
numeric.Ifoneisnonnumeric,thecomparisonislexicographic.
Examples
Thefollowingexamplesshowcommandlinesthatcallexprtoevaluateconstants.Youcanalsouse
exprtoevaluatevariablesinashellscript.Thefourthcommanddisplaysanerrormessagebecauseof
theillegaldecimalpointin5.3:
$expr17+40
57
$expr10-24
-14
$expr-17+20
3
$expr5.3+4
expr:non-numericargument
Themultiplication(*),division(/),andremainder(%)operatorsprovideadditionalarithmeticpower.
Youmustquotethemultiplicationoperator(precedeitwithabackslash)sothattheshellwillnottreatit
asaspecialcharacter(anambiguousfilereference).Youcannotputquotationmarksaroundtheentire
expressionbecauseeachstringandoperatormustbeaseparateargument.
$expr5\*4
20
$expr21/7
3
$expr23%7
2
Thenexttwoexamplesshowhowparentheseschangetheorderofevaluation.Youmustquoteeach
parenthesisandsurroundthebackslash/parenthesiscombinationwithSPACEs:
$expr2\*3+4
10
$expr2\*\(3+4\)
14
Youcanuserelationaloperatorstodeterminetherelationshipbetweennumericornonnumericarguments.
Thefollowingcommandscomparetwostringstoseeiftheyareequal;exprdisplaysa0whenthe
relationshipisfalseanda1whenitistrue.
$exprfred==sam
0
$exprsam==sam
1
Inthefollowingexamples,therelationaloperators,whichmustbequoted,establishorderbetween
numericornonnumericarguments.Again,ifarelationshipistrue,exprdisplaysa1.
$exprfred\>sam
0
$exprfred\<sam
1
$expr5\<7
1
Thenextcommandcompares5withm.Whenoneoftheargumentsthatexpriscomparingwitha
relationaloperatorisnonnumeric,exprconsiderstheothertobenonnumeric.Inthiscasebecausemis
nonnumeric,exprtreats5asanonnumericargument.ThecomparisonisbetweentheASCII(onmany
systems)valuesofmand5.TheASCIIvalueofmis109andthatof5is53,soexprevaluatesthe
relationshipastrue.
$expr5\<m
1
Thenextexampleshowsthematchingoperatordeterminingthatthefourcharactersinthesecondstring
matchthefirstfourcharactersinthefirststring.Theexprutilitydisplaysthenumberofmatching
characters(4).
$exprabcdefghijkl:abcd
4
The&operatordisplaysa0ifoneorbothofitsargumentsare0oranullstring;otherwise,itdisplays
thefirstargument:
$expr''\&book
0
$exprmagazine\&book
magazine
$expr5\&0
0
$expr5\&6
5
The|operatordisplaysthefirstargumentifitisnot0oranullstring;otherwise,itdisplaysthesecond
argument:
$expr''\|book
book
$exprmagazine\|book
magazine
$expr5\|0
5
$expr0\|5
5
$expr5\|6
5
file:Displaystheclassificationofafile
file[option]file-list
Thefileutilityclassifiesfilesaccordingtotheircontents.
Arguments
Thefile-listisalistofthepathnamesofoneormorefilesthatfileclassifies.Youcanspecifyanykind
offile,includingordinary,directory,andspecialfiles,inthefile-list.
Options
files-from=file ffile
Takesthenamesoffilestobeexaminedfromfileratherthanfrom
file-listonthecommandline.Thenamesofthefilesmustbelisted
oneperlineinfile.
mime iDisplaysMIME(page887)typestrings.
help Displaysahelpmessage.
dereference LReportsonthefilesthatsymboliclinkspointto,notonthe
symboliclinksthemselves.Thedefaultisno-dereference.
uncompress z(zip)Attemptstoclassifyfileswithinacompressedfile.
Notes
Thefileutilitycanclassifymorethan5,000filetypes.Someofthemorecommonfiletypesfoundon
Linuxsystems,asdisplayedbyfile,are
archive
asciitext
cprogramtext
commandstext
corefile
cpioarchive
data
directory
ELF32-bitLSBexecutable
empty
Englishtext
executable
Thefileutilityusesamaximumofthreetestsinitsattempttoclassifyafile:filesystem,magicnumber,
andlanguagetests.Whenfileidentifiesthetypeofafile,itceasestesting.Thefilesystemtestexamines
thereturnfromastatsystemcalltoseewhetherthefileisemptyoraspecialfile.Themagicnumber
(page886)testlooksfordatainparticularfixedformatsnearthebeginningofthefile.Thelanguagetest,
ifneeded,determineswhetherthefileisatextfile,whatencodingituses,andwhatlanguageitiswritten
in.Refertothefilemanpageforamoredetaileddescriptionofhowfileworks.Theresultsof
filearenotalwayscorrect.
Examples
Someexamplesoffileidentificationfollow:
/etc/DIR_COLORS:ASCIIEnglishtext
/etc/X11:directory
/etc/aliases.db:regularfile,noreadpermission
/etc/anacrontab:ASCIItext
/etc/asound.state:ASCIItext,withverylonglines
/etc/at.deny:empty
/etc/auto.net:Bourneshellscripttextexecutable
/etc/grub.conf:symboliclinkto'../boot/grub/grub.conf'
/etc/localtime:timezonedata
/etc/named.conf:C++programtext
/etc/rpc:ASCIICprogramtext
/etc/vimrc:Composer669Modulesounddata
/usr/bin/GET:perlscripttextexecutable
/usr/bin/HtFileType:Bourneshellscripttextexecutable
/usr/bin/Maelstrom:setgidELF32-bitLSBexecutable,Intel80386,
version1(SYSV),for
GNU/Linux2.2.5,dynamicallylinked(usessharedlibs),stripped
/usr/bin/X11:symboliclinkto'../X11R6/bin'
/usr/bin/[:ELF32-bitLSBexecutable,Intel80386,version1
(SYSV),forGNU/Linux2.2
.5,dynamicallylinked(usessharedlibs),stripped
/usr/bin/at:setuidELF32-bitLSBexecutable,Intel80386,version
1(SYSV),forGNU
/Linux2.2.5,dynamicallylinked(usessharedlibs),stripped
/usr/share/templates/linkHD.desktop:UTF-8Unicodetext
/usr/share/templates/.source/Floppy.desktop:UTF-8Unicodetext
/usr/share/templates/.source/TextFile.txt:veryshortfile(no
magic)
/usr/share/autoconf/m4sugar/m4sugar.m4f:ASCIIM4macrolanguage
pre-processortext/usr
/share/pygtk/2.0/defs/bonoboui.defs:Lisp/Schemeprogramtext
/usr/share/rhpl/extramodes:C++programtext
/usr/share/apps/konquest/pics/planet1.xpm:Xpixmapimagetext
/usr/share/apps/konquest/pics/konquest-splash.png:PNGimagedata,
600x550,8-bit
colormap,non-interlaced
/usr/share/apps/konquest/konquestui.rc:exportedSGMLdocumenttext
/usr/share/apps/templates/text/scripts/demo.php:PHPscripttext
find:Findsfilesbasedoncriteria
find[directory-list][expression]
Thefindutilityselectsfilesthatarelocatedinspecifieddirectoryhierarchiesandthatmeetspecified
criteria.
Arguments
Thedirectory-listspecifiesthedirectoriesthatfindistosearch.Whenfindsearchesadirectory,it
searchesallsubdirectoriestoalllevels.Whenyoudonotspecifyadirectory-list,findsearchesthe
workingdirectory.
Theexpressioncontainscriteria,asdescribedinthe"Criteria"section.Thefindutilitytestseachofthe
filesineachofthedirectoriesinthedirectory-listtoseewhetheritmeetsthecriteriadescribedbythe
expression.Whenyoudonotspecifyanexpression,theexpressiondefaultstoprint.
ASPACEseparatingtwocriteriaisaBooleanANDoperator:Thefilemustmeetbothcriteriatobe
selected.AororoseparatingthecriteriaisaBooleanORoperator:Thefilemustmeetoneortheother
(orboth)ofthecriteriatobeselected.
Youcannegateanycriterionbyprecedingitwithanexclamationpoint.Thefindutilityevaluates
criteriafromlefttorightunlessyougroupthemusingparentheses.
Withintheexpressionyoumustquotespecialcharacterssothattheshellwillnotinterpretthembutrather
passesthemtofind.Specialcharactersthatyoumayfrequentlyusewithfindareparentheses,
brackets,questionmarks,andasterisks.
Eachelementwithintheexpressionisaseparateargument.Youmustseparateargumentsfromeachother
withSPACEs.TheremustbeaSPACEonbothsidesofeachparenthesis,exclamationpoint,criterion,or
otherelement.
Criteria
Youcanusethefollowingcriteriawithintheexpression.Asusedinthislist,±nisadecimalintegerthat
canbeexpressedas+n(morethann),n(fewerthann),orn(exactlyn).
anewerfilename
(accessednewer)Thefilebeingevaluatedmeetsthiscriterionifitwasaccessedmore
recentlythanfilename.
atime±n
(accesstime)Thefilebeingevaluatedmeetsthiscriterionifitwaslastaccessed±ndays
ago.Whenyouusethisoption,findchangestheaccesstimesofdirectoriesitsearches.
depth
Thefilebeingevaluatedalwaysmeetsthisactioncriterion.Itcausesfindtotakeactionon
entriesinadirectorybeforeitactsonthedirectoryitself.Whenyouusefindtosendfiles
tothecpioutility,thedepthcriterionenablescpiotopreservethemodificationtimesof
directorieswhenyourestorefiles(assumingthatyouusethepreservemodificationtime
optiontocpio).Seethe"Discussion"and"Examples"sectionsundercpioonpages621
and622.
execcommand\;
Thefilebeingevaluatedmeetsthisactioncriterionifthecommandreturnsa0(zero[true])
exitstatus.Youmustterminatethecommandwithaquotedsemicolon.Apairofbraces({
})withinthecommandrepresentsthenameofthefilebeingevaluated.Youcanusethe
execactioncriterionattheendofagroupofothercriteriatoexecutethecommandifthe
precedingcriteriaaremet.Refertothefollowing"Discussion"sectionformoreinformation.
Seexargsonpage821foramoreefficientwayofdoingwhatthisoptiondoes.
follow
(dereference)Whenthiscriterionisspecifiedandfindencountersasymboliclink,find
followsthelink.
groupname
Thefilebeingevaluatedmeetsthiscriterionifitisassociatedwiththegroupnamedname.
YoucanuseanumericgroupIDinplaceofname.
inumn
Thefilebeingevaluatedmeetsthiscriterionifitsinodenumberisn.
links±n
Thefilebeingevaluatedmeetsthiscriterionifithas±nlinks.
mount
Seexdev.
mtime±n
(modifytime)Thefilebeingevaluatedmeetsthiscriterionifitwaslastmodified±ndays
ago.
namefilename
Thefilebeingevaluatedmeetsthiscriterionthepatternfilenamematchesitsname.The
filenamecanincludewildcardcharacters(*,?,and[])butthesecharactersmustbe
quoted.
newerfilename
Thefilebeingevaluatedmeetsthiscriterionifitwasmodifiedmorerecentlythanfilename.
nogroup
Thefilebeingevaluatedmeetsthiscriterionifitdoesnotbelongtoagroupthatislistedin
the/etc/groupfile.
nouser
Thefilebeingevaluatedmeetsthiscriterionifitdoesnotbelongtoauserwhoislistedin
the/etc/passwdfile(thatis,theuserIDofthefiledoesnotcorrespondtoauseronthe
localsystem).
okcommand\;
Thisactioncriterionisthesameasexecbutdisplayseachcommandtobeexecuted
enclosedinanglebracketsandexecutesthecommandonlyifitreceivesaresponsethat
startswithayorYfromstandardinput.
perm[±]mode
Thefilebeingevaluatedmeetsthiscriterionifithastheaccesspermissionsgivenbymode.
Ifmodeisprecededbyaminussign(),thefileaccesspermissionsmustincludeallthebits
inmode.Ifmodeisprecededbyaplussign(+),thefileaccesspermissionsmustincludeat
leastoneofthebitsinmode.Ifnoplusorminussignprecedesmode,themodeofthefile
mustexactlymatchmode.Youmayuseeitherasymbolicoroctalrepresentationformode
(seechmodonpage604).
print
Thefilebeingevaluatedalwaysmeetsthisactioncriterion.Whenevaluationofthe
expressionreachesthiscriterion,finddisplaysthepathnameofthefileitisevaluating.If
printistheonlycriterionintheexpression,finddisplaysthenamesofallfilesinthe
directory-list.Ifthiscriterionappearswithothercriteria,finddisplaysthenameonlyifthe
precedingcriteriaaremet.Ifnoactioncriteriaappearintheexpression,printisassumed.
(Refertothefollowing"Discussion"and"Notes"sections.)
size±n[c|k]
Thefilebeingevaluatedmeetsthiscriterionifitisthesizespecifiedby±n,measuredin
512-byteblocks.Follownwiththeletterctomeasurefilesincharactersorktomeasure
filesinkilobytes.
typefiletype
Thefilebeingevaluatedmeetsthiscriterionifitsfiletypeisspecifiedbyfiletype.Selecta
filetypefromthefollowinglist:
bBlockspecialfile
cCharacterspecialfile
dDirectoryfile
fOrdinaryfile
lSymboliclink
pFIFO(namedpipe)
sSocket
username
Thefilebeingevaluatedmeetsthiscriterionifitbelongstotheuserwiththeusername
name.YoucanuseanumericuserIDinplaceofname.
xdev
Thefilebeingevaluatedalwaysmeetsthisactioncriterion.Itcausesfindnottosearch
directoriesinfilesystemsotherthantheonespecifiedbydirectory-list.Alsomount.
Discussion
Assumethatxandyarecriteria.Thefollowingcommandlinenevertestswhetherthefilemeetscriterion
yifitdoesnotmeetcriterionx.BecausethecriteriaareseparatedbyaSPACE(theBooleanAND
operator),oncefinddeterminesthatcriterionxisnotmet,thefilecannotmeetthecriteriasofind
doesnotcontinuetesting.Youcanreadtheexpressionas"(testtoseewhether)thefilemeetscriterionx
and(SPACEmeansand)criteriony."
$finddirxy
Thenextcommandlineteststhefileagainstcriterionyifcriterionxisnotmet.Thefilecanstillmeetthe
criteriasofindcontinuestheevaluation.Youcanreadtheexpressionas"(testtoseewhether)thefile
meetscriterionxorcriteriony."Ifthefilemeetscriterionx,finddoesnotevaluatecriterionyasthere
isnoneedtodoso.
$finddirx-ory
Actioncriteria
Certain"criteria"donotselectfilesbutrathercausefindtotakeaction.Theactionistriggeredwhen
findevaluatesoneoftheseactioncriteria.Therefore,thepositionofanactioncriteriononthe
commandlinenottheresultofitsevaluationdetermineswhetherfindtakestheaction.
Theprintactioncriterioncausesfindtodisplaythepathnameofthefileitistesting.Thefollowing
commandlinedisplaysthenamesofallfilesinthedirdirectory(andallitssubdirectories),regardlessof
whethertheymeetthecriterionx:
$finddir-printx
Thefollowingcommandlinedisplaysonlythenamesofthefilesinthedirdirectorythatmeetcriterionx:
$finddirx-print
Thiscommonuseofprintafterthetestingcriteriaisthedefaultactioncriterion.Thefollowingcommand
linegeneratesthesameoutputasthepreviousone:
$finddirx
Notes
Youcanusetheaoperatorbetweencriteriaforclarity.ThisoperatorisaBooleanANDoperator,justas
theSPACEis.
Examples
Thesimplestfindcommandhasnoargumentsandliststhefilesintheworkingdirectoryandall
subdirectories:
$find
...
Thefollowingcommandfindsthefilesintheworkingdirectoryandsubdirectoriesthathavefilenames
beginningwitha.Thecommandusesaperiodtodesignatetheworkingdirectory.Topreventtheshell
frominterpretingthea*asanambiguousfilereference,itisenclosedwithinquotationmarks.
$find.-name'a*'
Theprintcriterionisimplicitintheprecedingcommand.Ifyouomitthedirectory-listargument,find
searchestheworkingdirectory.Thenextcommandperformsthesamefunctionastheprecedingone
withoutexplicitlyspecifyingtheworkingdirectory:
$find-name'a*'
Thefollowingcommandsendsalistofselectedfilenamestothecpioutility,whichwritesthemtotape.
Thefirstpartofthecommandlineendswithapipesymbol,sotheshellexpectsanothercommandto
followanddisplaysasecondaryprompt(>)beforeacceptingtherestofthecommandline.Youcanread
thisfindcommandas"find,intherootdirectoryandallsubdirectories(/),ordinaryfiles(typef)that
havebeenmodifiedwithinthepastday(mtime1),withtheexceptionoffileswhosenamesaresuffixed
with.o(!name'*.o')."(Anobjectfilecarriesa.osuffixandusuallydoesnotneedtobepreserved
becauseitcanbere-createdfromthecorrespondingsourcefile.)
$find/-typef-mtime-1!-name'*.o'-print|
>cpio-oB>/dev/ftape
Thefollowingcommandfinds,displaysthefilenamesof,anddeletesthefilesintheworkingdirectory
andsubdirectoriesnamedcoreorjunk:
$find.\(-namecore-o-namejunk\)-print-execrm{}\;
...
Theparenthesesandthesemicolonfollowingexecarequotedsothattheshelldoesnottreatthemas
specialcharacters.SPACEsseparatethequotedparenthesesfromotherelementsonthecommandline.
Readthisfindcommandas"find,intheworkingdirectoryandsubdirectories(.),filesnamedcore
(namecore)or(o)junk(namejunk)[ifafilemeetsthesecriteria,continue]and(SPACE)printthe
nameofthefile(print)and(SPACE)deletethefile(execrm{})."
Thenextshellscriptusesfindinconjunctionwithgreptoidentifyfilesthatcontainaparticularstring.
Thisscriptenablesyoutolookforafilewhenyourememberitscontentsbutcannotrememberits
filename.Thefinderscriptlocatesfilesintheworkingdirectoryandsubdirectoriesthatcontainthestring
specifiedonthecommandline.Thetypefcriterionisnecessarysothatfindwillpasstogreponlythe
namesofordinaryfiles,notdirectoryfiles.
$catfinder
find.-typef-execgrep-l"$1"{}\;
$finder"ExecutiveMeeting"
./january/memo.0102
./april/memo.0415
WhencalledwiththestringExecutiveMeeting,finderlocatestwofilescontainingthatstring:
./january/memo.0102and./april/memo.0415.Theperiod(.)inthepathnamesrepresentstheworking
directory;januaryandaprilaresubdirectoriesoftheworkingdirectory.Thegreputilitywiththe
recursiveoptionperformsthesamefunctionasthefinderscript.
Thenextcommandlooksintwouserdirectoriesforfilesthatarelargerthan100blocks(size+100)and
havebeenaccessedonlymorethanfivedaysagothatis,havenotbeenaccessedwithinthepastfivedays
(atime+5).Thisfindcommandthenaskswhetheryouwanttodeletethefile(okrm{}).Youmust
respondtoeachquerywithy(foryes)orn(forno).Thermcommandworksonlyifyouhavewriteand
executeaccesspermissiontothedirectory.
$find/home/alex/home/barbara-size+100-atime+5-okrm{}\;
<rm.../home/alex/notes>?y
<rm.../home/alex/letter>?n
...
Inthenextexample,/home/alex/memosisasymboliclinktoJenny'sdirectorynamed
/home/jenny/memos.Whenyouusethefollowoptionwithfind,thesymboliclinkisfollowed,andthe
contentsofthatdirectoryaresearched.
$ls-l/home/alex
lrwxrwxrwx1alexpubs17Aug1917:07memos->
/home/jenny/memos
-rw-r--r--1alexpubs5119Aug1917:08report
$find/home/alex-print
/home/alex
/home/alex/memos
/home/alex/report
/home/alex/.profile
$find/home/alex-follow-print
/home/alex
/home/alex/memos
/home/alex/memos/memo.817
/home/alex/memos/memo.710
/home/alex/report
/home/alex/.profile
finger:Displaysinformationaboutusers
finger[options][user-list]
Thefingerutilitydisplaystheusernamesofusers,togetherwiththeirfullnames,terminaldevice
numbers,timestheyloggedin,andotherinformation.Theoptionscontrolhowmuchinformation
fingerdisplays,andtheuser-listspecifieswhichusersfingerdisplaysinformationabout.The
fingerutilitycanretrieveinformationfrombothlocalandremotesystems.
Arguments
Withoutanyarguments,fingerprovidesashort(s)reportonuserswhoareloggedinonthelocal
system.Whenyouspecifyauser-list,fingerprovidesalong(l)reportoneachuserintheuser-list.
Namesintheuser-listarenotcasesensitive.
Ifthenameincludesanatsign(@),thefingerutilityinterpretsthenamefollowingthe@asthename
ofaremotehosttocontactoverthenetwork.Ifthereisalsoanameinfrontofthe@sign,finger
providesinformationonthatparticularuserontheremotesystem.
Options
l(long)Displaysdetailedinformation(thedefaultdisplaywhenuser-listisspecified).
m
(match)Ifauser-listisspecified,displaysentriesonlyforthoseuserswhoseusername
matchesoneofthenamesinuser-list.Withoutthisoptiontheuser-listnamesmatch
usernamesandfullnames.
p
(noplan,project,orpgpkey)Doesnotdisplaythecontentsof.plan,.project,and
.pgpkeyfilesforusers.Becausethesefilesmaycontainbackslashescapesequences
thatcanchangethebehaviorofthescreen,youmaynotwishtoviewthem.Normally
thelonglistingdisplaysthecontentsofthesefilesiftheyexistintheuser'shome
directory.
s(short)Providesashortreportforeachuser(thedefaultdisplaywhenuser-listisnot
present).
Discussion
Thelongreportprovidedbythefingerutilityincludestheuser'susername,fullname,homedirectory
location,andloginshell,plusinformationaboutwhentheuserlastloggedinandhowlongithasbeen
sincetheuserlasttypedonthekeyboardandreadheremail.Afterextractingthisinformationfrom
varioussystemfiles,thefingerutilitydisplaysthecontentsofthe~/.plan,~/.project,and~/.pgpkeyin
theuser'shomedirectory.Itisuptoeachusertocreateandmaintainthesefiles,whichusuallyprovide
moreinformationabouttheuser(suchastelephonenumber,postalmailaddress,schedule,interests,and
pgpkey).
Theshortreportgeneratedbyfingerissimilartothatprovidedbythewutility;itincludestheuser's
username,hisfullname,thedevicenumberoftheuser'sterminal,theamountoftimethathaselapsed
sincetheuserlasttypedontheterminalkeyboard,thetimetheuserloggedin,andthelocationofthe
user'sterminal.Iftheuserloggedinoverthenetwork,thenameoftheremotesystemisdisplayed.
Notes
Whenyouspecifyanetworkaddress,thefingerutilityqueriesastandardnetworkservicethatrunson
theremotesystem.AlthoughthisserviceissuppliedwithmostLinuxsystems,someadministratorschoose
nottorunit(soastominimizetheloadontheirsystems,toeliminatepossiblesecurityrisks,orsimplyto
maintainprivacy).Ifyoutrytousefingertogetinformationonsomeoneatsuchasite,theresultmay
beanerrormessageornothingatall.Theremotesystemdetermineshowmuchinformationtosharewith
thelocalsystemandinwhatformat.Asaresultthereportdisplayedforanygivensystemmaydifferfrom
theexamplesshownhere.Seealso"finger:ListsUsersontheSystem"onpage64.
Afilenamed~/.nofingercausesfingertodenytheexistenceofthepersonwhosehomedirectoryit
appearsin.Forthissubterfugetowork,thefingerquerymustoriginatefromasystemotherthanthe
localhostandthefingerddaemonmustbeabletoseethe.nofingerfile(generallythehomedirectory
musthaveitsexecutebitforotherusersset).
Examples
Thefirstexampledisplaysinformationontheusersloggedinonthelocalsystem:
$finger
LoginNameTtyIdleLoginTimeOffice
OfficePhone
alexAlexWatsontty113:29Jun2521:03
hlsHelenSimpson*pts/113:29Jun2521:02(:0)
jennyJennyChenpts/2Jun2607:47
(bravo.example.com)
Theasterisk(*)infrontofthenameofHelen'sterminal(TTY)lineindicatesthatshehasblockedothers
fromsendingmessagesdirectlytoherterminal(seemesgonpage68).Alongreportdisplaysthestring
messagesoffforuserswhohavedisabledmessages.
Thenexttwoexamplescausefingertocontacttheremotesystemnamedkudosoverthenetworkfor
information:
$finger@kudos
[kudos]
LoginNameTtyIdleLoginTimeOffice
OfficePhone
alexAlexWatsontty123:15Jun2511:22
royRoyWongpts/2Jun2511:22
$fingerwatson@kudos
[kudos]
Login:alexName:AlexWatson
Directory:/home/alexShell:/bin/zsh
OnsinceSatJun2511:22(PDT)ontty1,idle23:22
LastloginSunJun2606:20(PDT)onttyp2fromspeedy
MaillastreadThuJun2308:102005(PDT)
Plan:
ForappointmentscontactJennyChen,x1963.
fmt:Formatstextverysimply
fmt[option][file-list]
Thefmtutilitydoessimpletextformattingbyattemptingtomakeallnonblanklinesnearlythesame
length.
Arguments
Thefmtutilityreadsthefilesinfile-listandsendsaformattedversionoftheircontentstostandard
output.Ifyoudonotspecifyafilenameorifyouspecifyafilenameof,fmtreadsfromstandardinput.
Options
split-only sSplitslonglinesbutdoesnotfillshortlines.
tagged-paragraph
tIndentsallbutthefirstlineofeachparagraph.
uniform-spacing
uChangestheformattedoutputsothatoneSPACEappearsbetween
wordsandtwoSPACEsappearbetweensentences.
width=nwn
Changestheoutputlinewidthtoncharacters.Withoutthisoption,
fmtkeepsoutputlinescloseto75characterswide.Youcanalso
specifythisoptionasn.
Notes
ThefmtutilityworksbymovingNEWLINEcharacters.Theindentionoflines,aswellasthespacing
betweenwords,isleftintact.
Thisutilityisoftenusedtoformattextwhileyouareusinganeditor,suchasvim.Forexample,youcan
formataparagraphwiththevimeditorincommandmodebypositioningthecursoratthetopofthe
paragraphandthenentering!}fmt60.Thiscommandreplacestheparagraphwiththeoutputgeneratedby
feedingitthroughfmt,specifyingawidthof60characters.Typeuimmediatelyifyouwanttoundothe
formatting.
Examples
Thefollowingexampleshowshowfmtattemptstomakeallthelinesthesamelength.Thew50option
givesatargetlinelengthof50characters.
$catmemo
Onefactorthatisimportanttorememberwhileadministeringthe
dietary
intakeofCharcharodoncarchariasisthatthereis,atleastfrom
thepointofviewofthesubject,
verylittle
differentiatingthepreparedmorselsbeingprofferedfromyour
digits.
Inotherwords,don'tfeedthesharks!
$fmt-w50memo
Onefactorthatisimportanttorememberwhile
administeringthedietaryintakeofCharcharodon
carchariasisthatthereis,atleastfromthe
pointofviewofthesubject,verylittle
differentiatingthepreparedmorselsbeing
profferedfromyourdigits.
Inotherwords,don'tfeedthesharks!
Thenextexampledemonstratesthesplit-onlyoption.Longlinesarebrokensothatnoneislongerthan50
characters;thisoptionpreventsfmtfromfillingshortlines.
$fmt-w50--split-onlymemo
Onefactorthatisimportanttorememberwhile
administeringthedietary
intakeofCharcharodoncarchariasisthatthere
is,atleastfrom
thepointofviewofthesubject,
verylittle
differentiatingthepreparedmorselsbeing
profferedfromyourdigits.
Inotherwords,don'tfeedthesharks!
fsck:Checksandrepairsafilesystem
fsck[options][filesystem-list]
Thefsckutilityverifiestheintegrityofafilesystemandreportsonandoptionallyrepairsproblemsit
finds.Itisafrontendforfilesystemcheckers,eachspecifictoafilesystemtype.
Arguments
WithouttheAoptionandwithnofilesystem-list,fsckchecksthefilesystemslistedinthe/etc/fstabfile
oneatatime(serially).WiththeAoptionandwithnofilesystem-list,fsckchecksallthefilesystems
listedinthe/etc/fstabfileinparallelifpossible.Seethesoptionforadiscussionofchecking
filesystemsinparallel.
Thefilesystem-listspecifiesthefilesystemstobechecked.Itcaneitherspecifythenameofthedevice
thatholdsthefilesystem(forexample,/dev/hda2)or,ifthefilesystemappearsin/etc/fstab,specifythe
mountpoint(forexample,/usr2)forthefilesystem.Thefilesystem-listcanalsospecifythelabelforthe
filesystemfrom/etc/fstab(forexample,LABEL=home).
Options
Whenyourunfsck,youcanspecifybothglobaloptionsandoptionsspecifictothefilesystemtypethat
fsckischecking(forexample,ext2,ext3,msdos,reiserfs).Globaloptionsmustprecedetype-specific
options.
GlobalOptions
A
(all)Processallthefilesystemslistedinthe/etc/fstabfile,inparallelifpossible.Seethe
soptionforadiscussionofcheckingfilesystemsinparallel.Donotspecifyafilesystem-
listwhenyouusethisoption;youcanspecifyfilesystemtypestobecheckedwiththet
option.Usethisoptionwiththea,p,ornoptionsothatfsckdoesnotattemptto
processfilesystemsinparallelinteractively(inwhichcaseyouwouldhavenowayof
respondingtoitsmultipleprompts).
N
(no)Assumesanoresponsetoanyquestionsthatarisewhileprocessingafilesystem.
Thisoptiongeneratesthemessagesyouwouldnormallyseebutcausesfscktotakeno
action.
R(root-skip)WiththeAoptiondoesnotchecktherootfilesystem.Usefulwhenthe
systemboots,becausetherootfilesystemmaybemountedwithread-writeaccess.
s
(serial)Causesfscktoprocessfilesystemsoneatatime.Withoutthisoption,fsck
processesmultiplefilesystemsthatresideonseparatephysicaldiskdrivesinparallel.
Parallelprocessingenablesfscktoprocessmultiplefilesystemsmorequickly.This
optionisrequiredifyouwanttoprocessfilesystemsinteractively.Seethea,p,orn
optiontoturnoffinteractiveprocessing.
tfstype
(filesystemtype)Acomma-separatedlistthatspecifiesthefilesystemtype(s)to
process.WiththeAoptionfsckprocessesallthefilesystemsin/etc/fstabthatareof
typefstype.Commonfilesystemtypesareext2,ext3,msdos,andreiserfs.Youdonot
typicallycheckremoteNFSfilesystems.
T(title)Causesfscknottodisplayitstitle.
V(verbose)Displaysmoreoutput,includingfilesystemtype-specificcommands.
FilesystemType-SpecificOptions
Thefollowingcommandliststhefilesystemcheckingutilitiesavailableonthelocalsystem.Fileswiththe
sameinodenumbersarelinked(page99).
$ls-i/sbin/*fsck*
63801/sbin/dosfsck63856/sbin/fsck.cramfs63801/sbin/fsck.msdos
63763/sbin/e2fsck63763/sbin/fsck.ext263801/sbin/fsck.vfat
63780/sbin/fsck63763/sbin/fsck.ext3
Reviewthemanpageorgivethepathnameofthefilesystemcheckingutilitytodeterminewhichoptions
theutilityaccepts:
$/sbin/fsck.ext3
Usage:/sbin/fsck.ext3[-panyrcdfvstDFSV][-bsuperblock][-B
blocksize]
[-Iinode_buffer_blocks][-Pprocess_inode_size]
[-l|-Lbad_blocks_file][-Cfd][-jext-journal]
[-Eextended-options]device
Emergencyhelp:
-pAutomaticrepair(noquestions)
-nMakenochangestothefilesystem
-yAssume"yes"toallquestions
-cCheckforbadblocksandaddthemtothe
badblocklist
-fForcecheckingeveniffilesystemismarked
clean
...
Thefollowingoptionsapplytomanyfilesystemtypes,includingext2andext3:
a(automatic)Sameasthepoption;keptforbackwardcompatibility.
f
(force)Forcesfscktocheckfilesystemseveniftheyareclean.Acleanfilesystemis
onethatwasjustsuccessfullycheckedwithfsckorwassuccessfullyunmountedand
hasnotbeenmountedsince.Cleanfilesystemsareskippedbyfsck,greatlyspeeding
upsystembootingundernormalconditions.Forinformationonsettingupperiodic,
automaticfilesystemcheckingonext2andext3filesystems,seetune2fsonpage
808.
p
(preen)Attemptstorepairallminorinconsistenciesitfindswhenprocessinga
filesystem.Ifanyproblemsarenotrepaired,fsckterminateswithanonzeroexit
status.Thisoptionrunsfsckinbatchmodesothatitdoesnotaskwhethertocorrect
eachproblemitfinds.ThepoptioniscommonlyusedwiththeAoptionwhen
checkingfilesystemswhilebootingLinux.
r(interactive)Askswhethertocorrectorignoreeachproblemthatisfound.Formany
filesystemtypes,thisbehavioristhedefault.
y
(yes)Assumesayesresponsetoanyquestionsthatfsckaskswhileprocessinga
filesystem.Usethisoptionwithcautionasitgivesfsckfreereigntodowhatitthinks
isbesttocleanupafilesystem.
Notes
Whenafilesystemisconsistent,fsckdisplaysareportsuchasthefollowing:
#/sbin/fsck-f/dev/hda1
fsck1.35(28-Feb-2004)
e2fsck1.35(28-Feb-2004)
Pass1:Checkinginodes,blocks,andsizes
Pass2:Checkingdirectorystructure
Pass3:Checkingdirectoryconnectivity
Pass4:Checkingreferencecounts
Pass5:Checkinggroupsummaryinformation
/boot:71/26104files(15.5%non-contiguous),37257/104391blocks
Interactivemode
Youcanrunfsckeitherinteractivelyorinbatchmode.Formanyfilesystems,unlessyouuseoneofthe
a,p,y,ornoptions,fsckrunsininteractivemode.Ininteractivemode,iffsckfindsaproblemwitha
filesystem,itreportstheproblemandallowsyoutochoosewhethertorepairorignoreit.Ifyourepaira
problemyoumaylosesomedata;however,thatisoftenthemostreasonablealternative.
Althoughitistechnicallyfeasibletorepairfilesthataredamagedandthatfscksaysyoushouldremove,
thisactionisusuallynotpractical.Thebestinsuranceagainstsignificantlossofdataisfrequentbackups.
Orderofchecking
Thefsckutilitylooksatthesixthcolumninthe/etc/fstabfiletodetermineif,andinwhatorder,it
shouldcheckfilesystems.A0(zero)inthispositionindicatesthatthefilesystemshouldnotbechecked.A
1(one)indicatesthatitshouldbecheckedfirstandisusuallyreservedfortherootfilesystem.A2
indicatesthatthefilesystemshouldbecheckedafterthosemarkedwitha1.
fsckisafrontend
Similartomkfs(page725),fsckisafrontendthatcallsotherutilitiestohandlevarioustypesof
filesystems.Forexample,fsckcallse2fscktocheckthewidelyusedext2andext3filesystems.
(Refertothee2fsckmanpageformoreinformation.)Otherutilitiesthatfsckcallsaretypically
namedfsck.type,wheretypeisthefilesystemtype.Bysplittingfsckinthismanner,filesystem
developerscanprovideprogramstochecktheirfilesystemswithoutaffectingthedevelopmentofother
filesystemsorchanginghowsystemadministratorsusefsck.
Boottime
Runfsckonfilesystemsthatareunmountedormountedreadonly.WhenLinuxisbooting,theroot
filesystemisfirstmountedreadonlytoallowittobeprocessedbyfsck.Iffsckfindsnoproblemswith
therootfilesystem,itisthenremounted(usingtheremountoptiontothemountutility)read-writeand
fsckistypicallyrunwiththeA,R,andpoptions.
lost+found
Whenitencountersafilethathaslostitslinktoitsfilename,fsckaskswhethertoreconnectit.Ifyou
choosetoreconnectit,thefileisputinadirectorynamedlost+foundintherootdirectoryofthe
filesystemthatthefilewasfoundin.Thereconnectedfileisgivenitsinodenumberasaname.Forfsck
torestorefilesinthisway,alost+founddirectorymustbeintherootdirectoryofeachfilesystem.For
example,ifasystemusesthe/,/usr,and/tmpfilesystems,youshouldhavethesethreelost+found
directories:/lost+found,/usr/lost+found,and/tmp/lost+found.Eachofthelost+founddirectoriesmust
haveunusedentriesthatfsckcanusetostoretheinodenumbersforfilesthathavelosttheirlinks.When
youcreateanext2andext3filesystemusingmkfs(page725),alost+founddirectorywiththerequired
unusedentriesiscreatedautomatically.Alternatively,youcanusethemklost+foundutilitytocreate
thisdirectoryinext2andext3filesystemsifneeded.Onothertypesoffilesystemsyoucancreatethe
unusedentriesbyaddingmanyfilestothedirectoryandthenremovingthem.Tryusingtouch(page801)
tocreate500entriesinthelost+founddirectoryandthenusingrmtodeletethem.
Messages

TableV-14listsfsck'scommonmessages.Ingeneralfscksuggeststhemostlogicalwayofdealing
withaprobleminthefilestructure.Unlessyouhaveinformationthatsuggestsanotherresponse,respond
tothepromptswithyes.Usethesystembackuptapesordiskstorestoredatathatislostasaresultofthis
process.
TableV-14.Commonfsckmessages
Phase(message) Whatfsckchecks
Phase1-Checkinodes,blocks,
andsizes Checksinodeinformation.
Phase2-Checkdirectory
structures
Looksfordirectoriesthatpointtobadinodesthatfsckfound
inPhase1.
Phase3-Checkdirectory
connectivity
Looksforunreferenceddirectoriesandanonexistentorfull
lost+founddirectory.
Phase4-Checkreference
counts
Checksforunreferencedfiles,anonexistentorfull
lost+founddirectory,badlinkcounts,badblocks,duplicated
blocks,andincorrectinodecounts.
Phase5-Checkgroupsummary
information
Checkswhetherthefreelistandotherfilesystemstructures
areOK.Ifanyproblemsarefoundwiththefreelist,Phase6
isrun.
Phase6-Salvagefreelist IfPhase5foundanyproblemswiththefreelist,Phase6fixes
them.
Cleanup
Onceithasrepairedthefilesystem,fsckinformsyouaboutthestatusofthefilesystem.Thefsckutility
displaysthefollowingmessageafteritrepairsafilesystem:
*****FileSystemWasModified*****
Onext2andext3filesystems,fsckdisplaysthefollowingmessagewhenithasfinishedcheckinga
filesystem:
filesys:used/maximumfiles(percentnon-contiguous),used/maximum
blocks
Thismessagetellsyouhowmanyfilesanddiskblocksareinuseaswellashowmanyfilesanddisk
blocksthefilesystemcanhold.Thepercentnon-contiguoustellsyouhowfragmentedthediskis.
ftp:Transfersfilesoveranetwork
ftp[options][remote-system]
TheftputilityisauserinterfacetothestandardFileTransferProtocol(FTP),whichtransfersfiles
betweensystemsthatcancommunicateoveranetwork.ToestablishanFTPconnection,youmusthavean
account(personal,guest,oranonymous)ontheremotesystem.
security:UseFTPonlytodownloadpublicinformation
FTPisnotasecureprotocol.Theftputilitysendsyourpasswordoverthenetworkas
cleartext,whichisnotasecurepractice.Youcanusescp(page758)formanyFTP
functionsotherthanallowinganonymoususerstodownloadinformation.Becausescpuses
anencryptedconnection,userpasswordsanddatacannotbesniffed.
Arguments
Theremote-systemisthenameornetworkaddressoftheserver,runninganftpddaemon,thatyouwant
toexchangefileswith.
Options
i(interactive)Turnsoffpromptsduringfiletransferswithmgetandmput.Seealso
prompt.
n(noautomaticlogin)Disablesautomaticlogins.
v(verbose)Tellsyoumoreabouthowftpisworking.Displaysresponsesfromthe
remote-systemandreportstransfertimesandspeeds.
Discussion
Theftputilityisinteractive.Afteryoustartit,ftppromptsyoutoentercommandstosetparameters
andtransferfiles.Youcanuseanumberofcommandsinresponsetotheftp>prompt;followingaresome
ofthemorecommonones.
![command]
Escapesto(spawns)ashellonthelocalsystem
(useCONTROL-Dorexittoreturntoftp
whenyouarefinishedusingthelocalshell).
Followtheexclamationpointwithacommand
toexecutethatcommandonly;ftpreturnsyou
totheftp>promptwhenthecommand
completesexecuting.Becausetheshellthatftp
spawnswiththiscommandisachildofthe
shellthatisrunningftp,nochangesyoumake
inthisshellarepreservedwhenyoureturnto
ftp.Specifically,whenyouwanttocopyfiles
toalocaldirectoryotherthanthedirectorythat
youstartedftpfrom,youneedtousetheftp
lcdcommandtochangethelocalworking
directory:Issuingacdcommandinthe
spawnedshellwillnotmakethechangeyou
desire.See"lcd(localcd)"onpage676foran
example.
ascii
SetsthefiletransfertypetoASCII.Allowsyou
totransfertextfilesfromsystemsthatendlines
withaRETURN/LINEFEEDcombinationand
automaticallystripofftheRETURN.Thistype
oftransferisusefulwhentheremotecomputer
isaDOSorMSWindowsmachine.Thecr
commandmustbeONforasciitowork.
binary
Setsthefiletransfertypetobinary.Allowsyou
totransferfilesthatcontainnon-ASCII
(unprintable)characterscorrectly.Thisoption
alsoworksforASCIIfilesthatdonotrequire
changestotheendsoflines.
bye Closestheconnectiontoaremotesystemand
terminatesftp.Sameasquit.
cdremote-directory
Changestotheworkingdirectorynamed
remote-directoryontheremotesystem.
close Closestheconnectionwiththeremotesystem
withoutexitingfromftp.
cr TogglesRETURNstrippingwhenyouretrieve
filesinASCIImode.Seeascii.
dir[directory[file]]
Displaysalistingofthedirectorynamed
directoryfromtheremotesystem.Whenyou
donotspecifydirectory,theworkingdirectory
isdisplayed.Whenyouspecifyfile,thelisting
issavedonthelocalsysteminafilenamedfile.
getremote-file[local-file]
Copiesremote-filetothelocalsystemunderthe
namelocal-file.Withoutlocal-file,ftpuses
remote-fileasthefilenameonthelocalsystem.
Theremote-fileandlocal-filenamescanbe
pathnames.
glob
Togglesfilenameexpansionformgetandmput
commandsanddisplaysthecurrentstate
(GlobbingonorGlobbingoff).
help Displaysalistofcommandsrecognizedbythe
ftputilityonthelocalsystem.
lcd[local_directory]
(localchangedirectory)Changestheworking
directoryonthelocalsystemtolocal_directory.
Withoutanargumentchangestheworking
directoryonthelocalsystemtoyourhome
directory(justascddoeswithoutan
argument).
ls[directory[file]]
Similartodirbutproducesamoreconcise
listingonsomeremotecomputers.Whenyou
specifyfile,thelistingissavedonthelocal
systeminafilenamedfile.
mgetremote-file-list
(multipleget)Unlikethegetcommand,the
mgetcommandallowsyoutoretrievemultiple
filesfromtheremotesystem.Youcannamethe
remotefilesliterallyorusewildcards(seeglob).
Seealsoprompt.
mputlocal-file-list
(multipleput)Themputcommandallowsyou
tocopymultiplefilesfromthelocalsystemto
theremotesystem.Youcannamethelocalfiles
literallyorusewildcards(seeglob).Seealso
prompt.
open
Interactivelyspecifiesthenameoftheremote
system.Thiscommandisusefulifyoudidnot
specifyaremotesystemonthecommandline
oriftheattempttoconnecttothesystemfailed.
passive
Togglesbetweenactive(PORTthedefault)and
passive(PASV)transfermodesanddisplaysthe
transfermode.See"Passiveversusactive
connections"under"Notes."
prompt
Whenusingmgetormputtoreceiveorsend
multiplefiles,ftpasksforverification(by
default)beforetransferringeachfile.This
commandtogglesthatbehavioranddisplaysthe
currentstate(Interactivemodeoffor
Interactivemodeon).
putlocal-file[remote-file]
Copieslocal-filetotheremotesystemunder
thenameremote-file.Withoutremote-file,ftp
useslocal-fileasthefilenameontheremote
system.Theremote-fileandlocal-filenames
canbepathnames.
pwd
Causesftptodisplaythepathnameofthe
remoteworkingdirectory.Use!pwdtodisplay
thenameofthelocalworkingdirectory.
quit Quitstheftpsession.Sameasbye.
user[username]
Iftheftputilitydidnotlogyouin
automatically,youcanspecifyyouraccount
nameasusername.Withoutusername,ftp
promptsyouforyourusername.
Notes
ALinuxsystemrunningftpcanexchangefileswithanyofthemanyoperatingsystemsthatsupportthe
FTPprotocol.ManysitesofferarchivesoffreeinformationonanFTPserver,althoughmanyoftheseare
merelyalternativestoaneasier-to-accessWebsite(forexample,ftp://ftp.ibiblio.org/pub/Linuxand
http://www.ibiblio.org/pub/Linux).MostbrowserscanconnecttoanddownloadfilesfromFTPservers.
Theftputilitymakesnoassumptionsaboutfilesystemnamingorstructurebecauseyoucanuseftpto
exchangefileswithnon-UNIX/Linuxsystems(whosefilenameconventionsmaybedifferent).
AnonymousFTP
Manysystemsmostnotablythosefromwhichyoucandownloadfreesoftwareallowyoutologinas
anonymous.Mostsystemsthatsupportanonymousloginsacceptthenameftpasaneasier-to-spelland
quicker-to-entersynonymforanonymous.Ananonymoususerisusuallyrestrictedtoaportionofa
filesystemsetasidetoholdfilesthataretobesharedwithremoteusers.Whenyouloginasan
anonymoususer,theserverpromptsyoutoenterapassword.Althoughanypasswordmaybeaccepted,by
conventionyouareexpectedtosupplyyouremailaddress.Manysystemsthatpermitanonymousaccess
storeinterestingfilesinthepubdirectory.
Passiveversusactiveconnections
AclientcanaskanFTPservertoestablisheitheraPASV(passivethedefault)oraPORT(active)
connectionfordatatransfer.Someserversarelimitedtoonetypeofconnection.Thedifferencebetweena
passiveandanactiveFTPconnectionliesinwhethertheclientorserverinitiatesthedataconnection.In
passivemode,theclientinitiatesthedataconnectiontotheserver(onport20bydefault);inactivemode,
theserverinitiatesthedataconnection(thereisnodefaultport).Neithertypeofconnectionisinherently
moresecure.PassiveconnectionsaremorecommonbecauseaclientbehindaNAT(page889)firewall
canconnecttoapassiveserverandbecauseitissimplertoprogramascalablepassiveserver.
Automaticlogin
Youcanstoreserver-specificFTPusernameandpasswordinformationsothatyoudonothavetoenterit
eachtimeyouvisitanFTPsite.Eachlineofthe~/.netrcfileidentifiesaserver.Whenyouconnecttoan
FTPserver,ftpreads~/.netrctodeterminewhetheryouhaveanautomaticloginsetupforthatserver.
Theformatofalinein~/.netrcis
machineserverloginusernamepasswordpasswd
whereserveristhenameoftheserver,usernameisyourusername,andpasswdisyourpasswordon
server.Replacemachinewithdefaultonthelastlineofthefiletospecifyausernameandpasswordfor
systemsnotlistedin~/.netrc.Thedefaultlineisusefulforlogginginonanonymousservers.Asample
~/.netrcfilefollows:
$cat~/.netrc
machinebravologinalexpasswordmypassword
defaultloginanonymouspasswordalex@example.com
Protecttheaccountinformationin.netrcbymakingitreadablebyonlytheuserwhosehomedirectoryit
appearsin.Refertothenetrcmanpageformoreinformation.
Examples
FollowingaretwoftpsessionswhereinAlextransfersfilesfromandtoanFTPservernamedbravo.
WhenAlexgivesthecommandftpbravo,thelocalftpclientconnectstotheserver,whichasksfora
usernameandpassword.Becauseheisloggedinonhislocalsystemasalex,ftpsuggeststhathelogin
onbravoasalex.Tologinasalex,hecouldjustpressRETURN.Hisusernameonbravoiswatson,
however,sohetypeswatsoninresponsetotheName(bravo:alex):prompt.Alexrespondstothe
Password:promptwithhisnormalsystempassword,andtheFTPservergreetshimandinformshimthat
itisUsingbinarymodetotransferfiles.Withftpinbinarymode,AlexcantransferASCIIandbinary
files.
Connectandlogin
$ftpbravo
Connectedtobravo.
220(vsFTPd1.2.0)
530PleaseloginwithUSERandPASS.
530PleaseloginwithUSERandPASS.
KERBEROS_V4rejectedasanauthenticationtype
Name(bravo:alex):watson
331Pleasespecifythepassword.
Password:
230Loginsuccessful.
RemotesystemtypeisUNIX.
Usingbinarymodetotransferfiles.
ftp>
Afterloggingin,Alexusestheftplscommandtodisplaythecontentsofhisremoteworkingdirectory,
whichishishomedirectoryonbravo.Thenhecdstothememosdirectoryanddisplaysthefilesthere.
lsandcd
ftp>ls
227EnteringPassiveMode(192,168,0,6,79,105)
150Herecomesthedirectorylisting.
drwxr-xr-x25005004096Oct1023:52expenses
drwxr-xr-x25005004096Oct1023:59memos
drwxrwxr-x225005004096Oct1023:32tech
226DirectorysendOK.
ftp>cdmemos
250Directorysuccessfullychanged.
ftp>ls
227EnteringPassiveMode(192,168,0,6,114,210)
150Herecomesthedirectorylisting.
-rw-r--r--15005004770Oct1023:58memo.0514
-rw-r--r--15005007134Oct1023:58memo.0628
-rw-r--r--15005009453Oct1023:58memo.0905
-rw-r--r--15005003466Oct1023:59memo.0921
-rw-r--r--15005001945Oct1023:59memo.1102
226DirectorysendOK.
NextAlexusestheftpgetcommandtocopymemo.1102fromtheservertothelocalsystem.Binary
modeensuresthathewillgetagoodcopyofthefileregardlessofwhetheritisbinaryorASCII.The
serverconfirmsthatthefilewascopiedsuccessfullyandnotesthesizeofthefileandthetimeittookto
copy.Alexthencopiesthelocalfilememo.1114totheremotesystem.Thefileiscopiedintohisremote
workingdirectory,memos.
getandput
ftp>getmemo.1102
local:memo.1102remote:memo.1102
227EnteringPassiveMode(192,168,0,6,194,214)
150OpeningBINARYmodedataconnectionformemo.1102(1945bytes).
226FilesendOK.
1945bytesreceivedin7.1e-05secs(2.7e+04Kbytes/sec)
ftp>putmemo.1114
local:memo.1114remote:memo.1114
227EnteringPassiveMode(192,168,0,6,174,97)
150Oktosenddata.
226FilereceiveOK.
1945bytessentin2.8e-05secs(6.8e+04Kbytes/sec)
AfterawhileAlexdecideshewantstocopyallthefilesinthememodirectoryonbravotoanew
directoryonhislocalsystem.Hegivesanlscommandtomakesureheisgoingtocopytherightfiles,but
ftphastimedout.Insteadofexitingfromftpandgivinganotherftpcommandfromtheshell,Alex
givesftpanopenbravocommandtoreconnecttotheserver.Afterloggingin,heusestheftpcd
commandtochangedirectoriestomemosontheserver.
Timeoutandopen
ftp>ls
421Timeout.
Passivemoderefused.
ftp>openbravo
Connectedtobravo(192.168.0.6).
220(vsFTPd1.1.3)
...
ftp>cdmemos
250Directorysuccessfullychanged.
lcd(localcd)
Atthispoint,Alexrealizeshehasnotcreatedthenewdirectorytoholdthefileshewantstodownload.
Givinganftpmkdircommandwouldcreateanewdirectoryontheserver,butAlexwantsanew
directoryonthelocalsystem.Heusesanexclamationpoint(!)followedbyamkdirmemos.hold
commandtoinvokeashellandrunmkdironthelocalsystem,creatingadirectorynamedmemos.holdin
hisworkingdirectoryonthelocalsystem.(Youcandisplaythenameofyourworkingdirectoryonthe
localsystemwith!pwd.)Next,becausehewantstocopyfilesfromtheservertothememos.hold
directoryonhislocalsystem,hehastochangehisworkingdirectoryonthelocalsystem.Givingthe
command!cdmemos.holdwillnotaccomplishwhatAlexwantstodobecausetheexclamationpoint
spawnsanewshellonthelocalsystemandthecdcommandwouldbeeffectiveonlyinthenewshell,
whichisnottheshellthatftpisrunningunder.Forthissituation,ftpprovidesthelcd(localcd)
command,whichchangestheworkingdirectoryforftpandreportsonthenewlocalworkingdirectory.
ftp>!mkdirmemos.hold
ftp>lcdmemos.hold
Localdirectorynow/home/alex/memos.hold
Alexusestheftpmget(multipleget)commandfollowedbytheasterisk(*)wildcardtocopyallthe
filesfromtheremotememosdirectorytothememos.holddirectoryonthelocalsystem.Whenftp
promptshimforthefirstfile,herealizesthatheforgottoturnoffprompts,respondswithn,andpresses
CONTROL-Ctostopcopyingfilesinresponsetothesecondprompt.Theservercheckswhetherhewants
tocontinuewithhismgetcommand.
NextAlexgivestheftppromptcommand,whichtogglesthepromptaction(turnsitoffifitisonand
turnsitonifitisoff).Nowwhenhegivesanmget*command,ftpcopiesallthefileswithout
promptinghim.
Aftergettingthefileshewants,Alexgivesaquitcommandtoclosetheconnectionwiththeserver,exit
fromftp,andreturntothelocalshellprompt.
mgetandprompt
ftp>mget*
mgetmemo.0514?n
mgetmemo.0628?CONTROL-C
Continuewithmget?n
ftp>prompt
Interactivemodeoff.
ftp>mget*
local:memo.0514remote:memo.0514
227EnteringPassiveMode(192,168,0,6,53,55)
150OpeningBINARYmodedataconnectionformemo.0514(4770bytes).
226FilesendOK.
4770bytesreceivedin8.8e-05secs(5.3e+04Kbytes/sec)
local:memo.0628remote:memo.0628
227EnteringPassiveMode(192,168,0,6,65,102)
150OpeningBINARYmodedataconnectionformemo.0628(7134bytes).
226FilesendOK.
...
150OpeningBINARYmodedataconnectionformemo.1114(1945bytes).
226FilesendOK.
1945bytesreceivedin3.9e-05secs(4.9e+04Kbytes/sec)
ftp>quit
221Goodbye.
gcc:CompilesCandC++programs
gcc[options]file-list[larg]
g++[options]file-list[larg]
TheLinuxoperatingsystemusestheGNUCcompiler,gcc,topreprocess,compile,assemble,andlinkC
languagesourcefiles.Thesamecompilerwithadifferentfrontend,g++,processesC++sourcecode.
Thegccandg++compilerscanalsoassembleandlinkassemblylanguagesourcefiles,linkobjectfiles
only,orbuildobjectfilesforuseinsharedlibraries.

Thesecompilerstakeinputfromfilesyouspecifyonthecommandline.Unlessyouusetheooption,they
storetheexecutableprogramina.out.
Thegccandg++compilersarepartofGCC,theGNUCompilerCollection,whichincludesfrontends
forC,C++,ObjectiveC,Fortran,Java,andAdaaswellaslibrariesfortheselanguages.Goto
gcc.gnu.orgformoreinformation.
tip:gccandg++
Althoughthissectionspecifiesthegcccompiler,mostofitappliestog++aswell.
Arguments
Thefile-listisalistofthepathnamesofthefilesthatgccistoprocess.
Options
WithoutanyoptionsgccacceptsClanguagesourcefiles,assemblylanguagefiles,objectfiles,andother
filesdescribedinTableV-15onpage681.Thegccutilitypreprocesses,compiles,assembles,andlinks
thesefilesasappropriate,producinganexecutablefilenameda.out.Ifgccisusedtocreateobjectfiles
withoutlinkingthemtoproduceanexecutablefile,eachobjectfileisnamedbyaddingtheextension.oto
thebasenameofthecorrespondingsourcefile.Ifgccisusedtocreateanexecutablefile,itdeletesthe
objectfilesafterlinking.
TableV-15.Filenameextensions
Extension Typeoffile
.aLibraryofobjectmodules
.cClanguagesourcefile
.C,.cc,or.cxx C++languagesourcefile
.iPreprocessedClanguagesourcefile
.ii PreprocessedC++languagesourcefile
.oObjectfile
.sAssemblylanguagesourcefile

.SAssemblylanguagesourcefilethatneedspreprocessing
Someofthemostcommonlyusedoptionsarelistedhere.Whencertainfilenameextensionsareassociated
withanoption,youcanassumethattheextensionisaddedtothebasenameofthesourcefile.
c(compile)Suppressesthelinkingstepofcompilation.Compilesand/orassemblessource
codefilesandleavestheobjectcodeinfileswiththeextension.o.
Dname[=value]
Usually#definepreprocessordirectivesaregiveninheader,orinclude,files.Youcanuse
thisoptiontodefinesymbolicnamesonthecommandlineinstead.Forexample,DLinux
isequivalenttohavingtheline#defineLinuxinanincludefile,andDMACH=i586isthe
sameas#defineMACHi586.
E
(everything)Onsourcecodefiles,suppressesallstepsofcompilationexcept
preprocessingandwritestheresulttostandardoutput.Byconventiontheextension.iis
usedforpreprocessedCsourceand.iiforpreprocessedC++source.
fpic
Causesgcctoproduceposition-independentcode,whichissuitableforinstallingintoa
sharedlibrary.
fwritable-strings
BydefaulttheGNUCcompilerplacesstringconstantsintoprotectedmemory,wherethey
cannotbechanged.Some(usuallyolder)programsassumethatyoucanmodifystring
constants.Thisoptionchangesthebehaviorofgccsostringconstantscanbemodified.
g
(gdb)Embedsdiagnosticinformationintheobjectfiles.Thisinformationisusedby
symbolicdebuggers,suchasgdb(page412).Althoughitisnecessaryonlyifyoulater
useadebugger,itisagoodpracticetoincludethisoptionasamatterofcourse.
Idirectory
Looksforincludefilesindirectorybeforelookinginthestandardlocations.Givethis
optionmultipletimestolookinmorethanonedirectory.
larg
(lowercase"l")Searchesthedirectories/liband/usr/libforalibraryfilenamedlibarg.a.
Ifthefileisfound,gccthensearchesthislibraryforanyrequiredfunctions.Replacearg
withthenameofthelibraryyouwanttosearch.Forexample,thelmoptionnormallylinks
thestandardmathlibrarylibm.a.Thepositionofthisoptionissignificant:Itgenerally
needstogoattheendofthecommandlinebutcanberepeatedmultipletimestosearch
differentlibraries.Librariesaresearchedintheorderinwhichtheyappearonthe
commandline.Thelinkerusesthelibraryonlytoresolveundefinedsymbolsfrommodules
thatprecedethelibraryoptiononthecommandline.Youcanaddotherlibrarypathsto
searchforlibarg.ausingtheLoption.
Ldirectory
Addsdirectorytothelistofdirectoriestosearchforlibrariesgivenwiththeloption.
DirectoriesthatareaddedtothelistwithLaresearchedbeforelookinginthestandard
locationsforlibraries.
ofile
(output)Namestheexecutableprogramthatresultsfromlinkingfileinsteadofa.out.
On
(optimize)Attemptstoimprove(optimize)theobjectcodeproducedbythecompiler.The
valueofnmaybe0,1,2,or3(or06ifyouarecompilingcodefortheLinuxkernel).The
defaultvalueofnis1.Largervaluesofnresultinbetteroptimizationbutmayincrease
boththesizeoftheobjectfileandthetimeittakesgcctorun.UsingO0turnsoff
optimization.Manyrelatedoptionscontrolpreciselythetypesofoptimizationsattempted
bygccwhenyouuseO.Refertothegccinfopagefordetails.
pedantic
TheClanguageacceptedbytheGNUCcompilerincludesfeaturesthatarenotpartofthe
ANSIstandardfortheClanguage.Usingthisoptionforcesgcctorejecttheselanguage
extensionsandacceptonlystandardCprogramminglanguagefeatures.
QDisplaysthenamesoffunctionsasgcccompilesthem.Alsodisplaysstatisticsabouteach
pass.
S(suppress)Suppressestheassemblingandlinkingstepsofcompilationonsourcecode
files.Theresultingassemblylanguagefileshave.sfilenameextensions.
traditional
CausesgcctoacceptonlyCprogramminglanguagefeaturesthatexistedinthetraditional
KernighanandRitchieCprogramminglanguage.Thisoptionallowsyoutocompile
correctlyolderprogramswrittenusingthetraditionalClanguagethatexistedbeforethe
ANSIstandardClanguagewasdefined.
Wall
Causesgcctowarnyouaboutquestionablecodeinthesourcecodefiles.Manyrelated
optionscontrolwarningmessagesmoreprecisely.Seepage408.
Notes
Theprecedinglistofoptionsrepresentsonlyasmallfractionofthefullsetofoptionsavailablewiththe
GNUCcompiler.Seethegccinfopageforacompletelist.
See"ProgramminginC"onpage388formoreinformationaboutusingthegcccompiler.
Althoughtheooptionisgenerallyusedtospecifyafilenametostoreobjectcode,thisoptionalsoallows
youtonamefilesresultingfromothercompilationsteps.Inthefollowingexample,theooptioncausesthe
assemblylanguageproducedbythegcccommandtobestoredinthefileacodeinsteadofpgm.s,the
default:
$gcc-S-oacodepgm.c
ThelintutilityfoundinmanyUNIXsystemsisnotavailableonLinux.However,theWalloption(page
408)performsmanyofthesamechecksandcanbeusedinplaceoflint.
TheconventionsusedbytheCcompilerforassigningfilenameextensionsaresummarizedinTableV-15.
Examples
Thefirstexamplecompiles,assembles,andlinksasingleCprogram,compute.c.Theexecutableoutput
isputina.out.Thegccutilitydeletestheobjectfile.
$gcccompute.c
ThenextexamplecompilesthesameprogramusingtheCoptimizer(Ooption).Itassemblesandlinksthe
optimizedcode.Theooptioncausesgcctoputtheexecutableoutputincompute.
$gcc-O-ocomputecompute.c
NextaCsourcefile,anassemblylanguagefile,andanobjectfilearecompiled,assembled,andlinked.
Theexecutableoutputgoesinprogo.
$gcc-oprogoprocom.cprofast.sproout.o
Inthenextexample,gccsearchesthestandardmathlibrarystoredin/lib/libm.awhenitislinkingthe
himathprogramandputstheexecutableoutputina.out:
$gcchimath.c-lm
Inthefollowingexample,theCcompilercompilestopo.cwithoptionsthatcheckthecodefor
questionablesourcecodepractices(Walloption)andviolationsoftheANSICstandard(pedantic
option).Thegoptionembedsdebuggingsupportintheexecutablefile,whichissavedintopowiththeo
topooption.FulloptimizationisenabledwiththeO3option.
ThewarningsproducedbytheCcompileraresenttostandardoutput.Herethefirstandlastwarnings
resultfromthepedanticoption;theotherwarningsresultfromtheWalloption:
$gcc-Wall-g-O3-pedantic-otopotopo.c
Infileincludedfromtopo.c:2:
/usr/include/ctype.h:65:warning:commaatendofenumeratorlist
topo.c:13:warning:return-typedefaultsto'int'
topo.c:Infunction'main':
topo.c:14:warning:unusedvariable'c'
topo.c:Infunction'getline':
topo.c:44:warning:'c'mightbeuseduninitializedinthisfunction
WhencompilingprogramsthatusetheX11includefilesandlibraries,youmayneedtousetheIandL
optionstotellgccwheretolocatethoseincludefilesandlibraries.Thenextexampleusesthoseoptions
andinstructsgcctolinktheprogramwiththebasicX11library:
$gcc-I/usr/X11R6/includeplot.c-L/usr/X11R6/lib-lX11
grep:Searchesforapatterninfiles
grep[options]pattern[file-list]
Thegreputilitysearchesoneormorefiles,linebyline,forapattern,whichcanbeasimplestringor
anotherformofaregularexpression.Thegreputilitytakesvariousactions,specifiedbyoptions,each
timeitfindsalinethatcontainsamatchforthepattern.Thisutilitytakesitsinputfromfilesyouspecify
onthecommandlineorfromstandardinput.
Arguments
Thepatternisaregularexpression,asdefinedinAppendixA.Youmustquoteregularexpressionsthat
containspecialcharacters,SPACEs,orTABs.Aneasywaytoquotethesecharactersistoenclosethe
entireexpressionwithinsinglequotationmarks.
Thefile-listisalistofthepathnamesofordinaryfilesthatgrepsearches.Withtheroption,file-list
maycontaindirectorieswhosecontentsaresearched.
Options
Withoutanyoptionsgrepsendslinesthatcontainamatchforpatterntostandardoutput.Whenyou
specifymorethanonefileonthecommandline,grepprecedeseachlinethatitdisplayswiththenameof
thefilethatitcamefromfollowedbyacolon.
MajorOptions
Youcanuseonlyoneofthefollowingthreeoptionsatatime.Normallyyoudonotneedtouseany,
becausegrepdefaultstoG,whichisregulargrep.
E(extended)Interpretspatternasanextendedregularexpression(page836).The
commandgrepEisthesameasegrep.See"Notes"laterinthissection.
F(fixed)Interpretspatternasafixedstringofcharacters.ThecommandgrepFisthe
sameasfgrep.
G(grep)Interpretspatternasabasicregularexpression.Thisisthedefaultmajoroptionif
noneisspecified.
OtherOptions
Acceptsthecommonoptionsdescribedonpage587.
count cDisplaysonlythenumberoflinesthatcontaina
matchineachfile.
context=nCn
Displaysnlinesofcontextaroundeachmatching
line.
file=file fFile
Readsfile,whichcontainsonepatternperline,and
findslinesintheinputthatmatcheachofthe
patterns.
no-filename hDoesnotdisplaythefilenameatthebeginningof
eachlinewhensearchingthroughmultiplefiles.
ignore-case i
Causeslowercaselettersinthepatterntomatch
uppercaselettersinthefile,andviceversa.Usethis
optionwhenyouaresearchingforawordthatmay
beatthebeginningofasentence(thatis,mayor
maynotstartwithanuppercaseletter).
files-with-matches
l
(lowercase"l")Displaysonlythenameofeachfile
thatcontainsoneormorematches.Afilenameis
displayedonlyonce,evenifthefilecontainsmore
thanonematch.
max-count=nmn
Stopsreadingeachfile,orstandardinput,after
displayingnlinescontainingmatches.
line-number nPrecedeseachlinebyitslinenumberinthefile.The
filedoesnotneedtocontainlinenumbers.
quietorsilent qDoesnotwriteanythingtostandardoutput;only
setstheexitcode.
recursive rorR
Recursivelydescendsdirectoriesinfile-listand
processesfileswithinthesedirectories.
no-messages s(silent)Doesnotdisplayanerrormessageifafilein
file-listdoesnotexistorisnotreadable.
invert-match v
Causeslinesnotcontainingamatchtosatisfythe
search.Whenyouusethisoptionbyitself,grep
displaysalllinesthatdonotcontainamatchforthe
pattern.
word-regexp w
Withthisoption,thepatternmustmatchawhole
word.Thisoptionishelpfulifyouaresearchingfor
aspecificwordthatmayalsoappearasasubstring
ofanotherwordinthefile.
line-regexp x Thepatternmatcheswholelinesonly.
Notes
Thegreputilityreturnsanexitstatusof0ifitfindsamatch,1ifitdoesnotfindamatch,and2ifthefile
isnotaccessibleorthereisasyntaxerror.
egrepandfgrep
Twoutilitiesperformfunctionssimilartothatofgrep.Theegreputility(sameasgrepE)allowsyou
touseextendedregularexpressions(page836),whichincludeadifferentsetofspecialcharactersthan
basicregularexpressions(page834).Thefgreputility(sameasgrepF)isfastandcompactbut
processesonlysimplestrings,notregularexpressions.
Examples
Thefollowingexamplesassumethattheworkingdirectorycontainsthreefiles:testa,testb,andtestc:
FiletestaFiletestbFiletestc
aaabbaaaaaAAAAA
bbbccbbbbbBBBBB
ff-ffcccccCCCCC
cccdddddddDDDDD
dddaa
Thegreputilitycansearchforapatternthatisasimplestringofcharacters.Thefollowingcommand
linesearchestestaanddisplayseachlinecontainingthestringbb:
$grepbbtesta
aaabb
bbbcc
Thevoptionreversesthesenseofthetest.Thefollowingexampledisplaysthelinesintestawithoutbb:
$grep-vbbtesta
ff-ff
cccdd
dddaa
Thenoptiondisplaysthelinenumberofeachdisplayedline:
$grep-nbbtesta
1:aaabb
2:bbbcc
Thegreputilitycansearchthroughmorethanonefile.Heregrepsearchesthrougheachfileinthe
workingdirectory.Thenameofthefilecontainingthestringprecedeseachlineofoutput.
$grepbb*
testa:aaabb
testa:bbbcc
testb:bbbbb
Whenthesearchforthestringbbisdonewiththewoption,grepproducesnooutputbecausenoneofthe
filescontainsthestringbbasaseparateword:
$grep-wbb*
$
Thesearchthatgrepperformsiscasesensitive.Becausethepreviousexamplesspecifiedlowercasebb,
grepdidnotfindtheuppercasestringBBBBBintestc.Theioptioncausesbothuppercaseand
lowercaseletterstomatcheithercaseofletterinthepattern:
$grep-ibb*
testa:aaabb
testa:bbbcc
testb:bbbbb
testc:BBBBB
$grep-iBB*
testa:aaabb
testa:bbbcc
testb:bbbbb
testc:BBBBB
Thecoptiondisplaysthenumberoflinesineachfilethatcontainamatch:
$grep-cbb*
testa:2
testb:1
testc:0
Thefoptionfindsmatchesforeachpatterninafileofpatterns.Thenextexampleshowsgfile,which
holdstwopatterns,oneperline,andgrepsearchingformatchestothepatternsingfile:
$catgfile
aaa
bbb
$grep-fgfiletest*
testa:aaabb
testa:bbbcc
testb:aaaaa
testb:bbbbb
Thefollowingcommandlinedisplaysfromtext2linesthatcontainastringofcharactersstartingwithst,
followedbyzeroormorecharacters(.*representszeroormorecharactersinaregularexpressionsee
AppendixA),andendingining:
$grep'st.*ing'text2
...
The^regularexpression,whichmatchesthebeginningofaline,canbeusedalonetomatcheverylinein
afile.Togetherwiththenoption,^canbeusedtodisplaythelinesinafile,precededbytheirline
numbers:
$grep-n'^'testa
1:aaabb
2:bbbcc
3:ff-ff
4:cccdd
5:dddaa
Thenextcommandlinecountsthenumberoftimes#includestatementsappearinCsourcefilesinthe
workingdirectory.Thehoptioncausesgreptosuppressthefilenamesfromitsoutput.Theinputto
sortisalllinesfrom*.cthatmatch#include.Theoutputfromsortisanorderedlistoflinesthat
containsmanyduplicates.Whenuniqwiththecoptionprocessesthissortedlist,itoutputsrepeated
linesonlyonce,alongwithacountofthenumberofrepetitionsinitsinput.
$grep-h'#include'*.c|sort|uniq-c
9#include"buff.h"
2#include"poly.h"
1#include"screen.h"
6#include"window.h"
2#include"x2.h"
2#include"x3.h"
2#include<math.h>
3#include<stdio.h>
Thefinalcommandcallsthevimeditorwithalistoffilesintheworkingdirectorythatcontainthestring
Sampson.The$(…)commandsubstitutionconstruct(page329)causestheshelltoexecutegrepin
placeandsupplyvimwithalistoffilenamesthatyouwanttoedit:
$vim$(grep-l'Sampson'*)
...
Thesinglequotationmarksarenotnecessaryinthisexample,buttheyarerequirediftheregular
expressionyouaresearchingforcontainsspecialcharactersorSPACEs.Itisgenerallyagoodhabitto
quotethepatternsothattheshelldoesnotinterpretspecialcharactersitmaycontain.
gzip:Compressesordecompressesfiles
gzip[options][file-list]
gunzip[options][file-list]
zcat[file-list]
Thegziputilitycompressesfiles;gunziprestoresfilescompressedwithgzip;zcatdisplaysfiles
compressedwithgzip.
Arguments
Thefile-listisalistofthenamesofoneormorefilesthataretobecompressedordecompressed.Ifa
directoryappearsinfile-listwithnorecursiveoption,gzip/gunzipissuesanerrormessageand
ignoresthedirectory.Withtherecursiveoption,gzip/gunziprecursivelycompresses/decompresses
fileswithinthedirectoryhierarchy.
Iffile-listisemptyorifthespecialoptionispresent,gzipreadsfromstandardinput.Thestdoutoption
causesgzipandgunziptowritetostandardoutput.
Theinformationinthissectionalsoappliestogunzip,alinktogzip.
Options
Acceptsthecommonoptionsdescribedonpage587.
stdout cWritestheresultsofcompressionordecompressiontostandardoutput
insteadofoverwritingtheoriginalfile.
decompressor
uncompress dDecompressesafilecompressedwithgzip.Thisoptionwithgzipis
equivalenttothegunzipcommand.
fastorbest n
Controlsthetradeoffbetweenthespeedofcompressionandthe
amountofcompression.Thenisadigitfrom1to9;level1isthe
fastest(least)compressionandlevel9isthebest(slowestandmost)
compression.Thedefaultlevelis6.Theoptionsfastandbestare
synonymsfor1and9,respectively.
force fOverwritesanexistingoutputfileoncompression/decompression.
list l
Foreachcompressedfileinfile-list,displaysthefile'scompressedand
decompressedsizes,thecompressionratio,andthenameofthefile
beforecompression.Usewithverboseforadditionalinformation.
quiet qSuppresseswarningmessages.
recursive rRecursivelydescendsdirectoriesinfile-listand
compresses/decompressesfileswithinthesedirectories.
test tVerifiestheintegrityofacompressedfile.Displaysnothingifthefileis
OK.
verbose vDisplaysthenameofthefile,thenameofthecompressedfile,andthe
amountofcompressionaseachfileisprocessed.
Discussion
Compressingfilesreducesdiskspacerequirementsandthetimeneededtotransmitfilesbetweensystems.
Whengzipcompressesafile,itaddstheextension.gztothefilename.Forexample,compressingthe
filefnamecreatesthefilefname.gzanddeletestheoriginalfile.Torestorefname,usethecommand
gunzipwiththeargumentfname.gz.
Almostallfilesbecomemuchsmallerwhencompressedwithgzip.Onrareoccasionsafilewill
becomelarger,butonlybyaslightamount.Thetypeofafileanditscontents(aswellasthenoption)
determinehowmuchsmallerafilebecomes;textfilesareoftenreducedby60to70percent.
Theattributesofafile,suchasitsowner,permissions,andmodificationandaccesstimes,areleftintact
whengzipcompressesandgunzipdecompressesafile.
Ifthecompressedversionofafilealreadyexists,gzipreportsthatfactandasksforyourconfirmation
beforeoverwritingtheexistingfile.Ifafilehasmultiplelinkstoit,gzipissuesanerrormessageand
exits.Theforceoptionoverridesthedefaultbehaviorinbothofthesesituations.
Notes
Formoreinformationreferto"gzip:CompressesaFile"onpage58.
Inadditiontothegzipformat,gunziprecognizesseveralothercompressionformats,enabling
gunziptodecompressfilescompressedwithcompress.
Toseeanexampleofafilethatbecomeslargerwhencompressedwithgzip,comparethesizeofafile
thathasbeencompressedoncewiththesamefilecompressedwithgzipagain.Becausegzip
complainswhenyougiveitanargumentwiththeextension.gz,youneedtorenamethefilebefore
compressingitasecondtime.
Thetarutilitywiththezmodifier(page789)callsgzip.
Thefollowingrelatedutilitiesdisplayandmanipulatecompressedfiles.Noneoftheseutilitieschanges
thefilesthatitworkson.
zcatfile-list Workslikecatexceptthatitusesgunziptodecompressfile-list
asitcopiesfilestostandardoutput.
zdiff[options]file1[file2]
Workslikediff(page638)exceptthatfile1andfile2are
decompressedwithgunzipasneeded.Thezdiffutilityaccepts
thesameoptionsasdiff.Ifyouomitfile2,zdiffcompares
file1withthecompressedversionoffile1.
zlessfile-list Workslikelessexceptthatitusesgunziptodecompressfile-
listasitdisplaysfiles.
Examples
Inthefirstexample,gzipcompressestwofiles.Thengunzipdecompressesoneofthefiles.Whena
fileiscompressedanddecompressed,itssizechangesbutitsmodificationtimeremainsthesame:
$ls-l
total175
-rw-rw-r--1alexgroup33557Jul2017:32patch-2.0.7
-rw-rw-r--1alexgroup143258Jul2017:32patch-2.0.8
$gzip*
$ls-l
total51
-rw-rw-r--1alexgroup9693Jul2017:32patch-2.0.7.gz
-rw-rw-r--1alexgroup40426Jul2017:32patch-2.0.8.gz
$gunzippatch-2.0.7.gz
$ls-l
total75
-rw-rw-r--1alexgroup33557Jul2017:32patch-2.0.7
-rw-rw-r--1alexgroup40426Jul2017:32patch-2.0.8.gz
Inthenextexample,thefilesinJenny'shomedirectoryarearchivedbyusingthecpioutility(page619).
Thearchiveiscompressedwithgzipbeforeitiswrittentotape:
$find/home/jenny-depth-print|cpio-oBm|gzip>/dev/ftape
head:Displaysthebeginningofafile
head[options][file-list]
Theheadutilitydisplaysthebeginning(head)ofafile.Theutilitytakesitsinputfromoneormorefiles
youspecifyonthecommandlineorfromstandardinput.
Arguments
Thefile-listisalistofthepathnamesofthefilesthatheaddisplays.Whenyouspecifymorethanone
file,headdisplaysthefilenamebeforedisplayingthefirstfewlinesofeachfile.Whenyoudonot
specifyafile,headtakesitsinputfromstandardinput.
Options
Acceptsthecommonoptionsdescribedonpage587.
bytes=n[u]cn[u]
Displaysthefirstnbytes(characters)ofafile.Theuis
anoptionalunitofmeasurethatcanbeb(512-byte
blocks),k(kilobyteor1,024-byteblocks),orm
(megabyteor1,048,576-byteblocks).Ifyouincludethe
unitofmeasure,headcountsbythisunitinsteadofby
bytes.
lines=nnn
Displaysthefirstnlinesofafile.Youcanusento
specifynlineswithoutusingthelineskeywordorthen
option.Ifyouspecifyanegativevalueforn,head
displaysallbutthelastnlinesofthefile.
quiet qSuppressesheaderinformationwhenyouspecifymore
thanonefilenameonthecommandline.
Notes
Theheadutilitydisplaysthefirsttenlinesofafilebydefault.
Examples
Theexamplesinthissectionarebasedonthefollowingfile:
$cateleven
lineone
linetwo
linethree
linefour
linefive
linesix
lineseven
lineeight
linenine
lineten
lineeleven
Withoutanyargumentsheaddisplaysthefirsttenlinesofafile:
$headeleven
lineone
linetwo
linethree
linefour
linefive
linesix
lineseven
lineeight
linenine
lineten
Thenextexampledisplaysthefirstthreelines(lines3)ofthefile:
$head--lines3eleven
lineone
linetwo
linethree
Thefollowingexampleisequivalenttotheprecedingone:
$head-3eleven
lineone
linetwo
linethree
Thenextexampledisplaysthefirstsixcharacters(bytes6)inthefile:
$head--bytes6eleven
lineo$
Thefinalexampledisplaysallbutthelastsevenlinesofthefile:
$head--lines=-7eleven
lineone
linetwo
linethree
linefour
kill:TerminatesaprocessbyPID
kill[option]PID-list
Thekillutilityterminatesoneormoreprocessesbysendingthemsignals.Bydefaultkillsendsa
softwareterminationsignal(signalnumber15).Forkilltowork,theprocessmustbelongtotheuser
executingkill,withoneexception:Superusercanterminateanyprocess.
Arguments
ThePID-listisalistofprocessidentification(PID)numbersofprocessesthatkillistoterminate.
Options
Youcanspecifyasignalnumberorname,precededbyahyphen,asanoptiontocausekilltosendthe
signalyouspecifytothePID-list.
l(list)Displaysalistofsignals.(DonotspecifyPID-list.)
Notes
Seealsokillallonpage695.
SeeTable11-5onpage494foralistofsignals.Thecommandkillldisplaysacompletelistofsignal
numbersandnames.
Inadditiontothekillutility,killisabuiltinintheBourneAgainandTCShells.Thebuiltinswork
similarlytotheutilitydescribedhere.Givethecommand/bin/killtousethekillutilityandthe
commandkilltousethebuiltin.Itdoesnotusuallymatterwhichyouuse.
TheshelldisplaysthePIDnumberofabackgroundprocesswhenyouinitiatetheprocess.Youcanalso
usethepsutilitytodeterminePIDnumbers.
Ifthesoftwareterminationsignaldoesnotterminateaprocess,tryusingaKILLsignal(signalnumber9).
AprocesscanchoosetoignoreanysignalexceptKILL.
Thekillutility/builtinacceptsjobidentifiersinplaceofthePID-list.Jobidentifiersconsistofa
percentsign(%)followedbyeitherajobnumberorastringthatuniquelyidentifiesthejob.
Toterminateallprocessesthatthecurrentloginprocessinitiatedandhavetheoperatingsystemlogyou
out,givethecommandkill90.
caution:root:donotrunkillwithargumentsof90orKILL0
Ifyourunthecommandkill90whileyouareloggedinasSuperuser,youwillbringthe
systemdown.
Examples
Thefirstexampleshowsacommandlineexecutingthefilecomputeasabackgroundprocessandthe
killutilityterminatingit:
$compute&
[2]259
$kill259
$RETURN
[2]+Terminatedcompute
ThenextexampleshowsthepsutilitydeterminingthePIDnumberofthebackgroundprocessrunninga
programnamedxprogandthekillutilityterminatingxprogwiththeTERMsignal:
$ps
PIDTTYSTATTIMECOMMAND
1161S0:00-tcsh
1281SN0:00xinit/home/alex/.xinitrc--
1371SN0:01fvwm
138p0SN0:00-tcsh
161p0SN0:10xprog
262p0RN0:00ps
$kill-TERM161
$
killall:Terminatesaprocessbyname
killall[option]name-list
Thekillallutilitysendssignalstoprocessesexecutingspecifiedcommands.Forkillalltowork,
theprocessesmustbelongtotheuserexecutingkillall,withoneexception:Superusercanterminate
anyprocess.
Arguments
Thename-listisaSPACE-separatedlistofnamesofprogramsthataretoreceivesignals.
Options
Youcanspecifyasignalnumberorname,precededbyahyphen,asanoptionbeforethename-listto
causekillalltosendthesignalyouspecify.Bydefaultkillallsendssoftwareterminationsignals
(signalnumber15,SIGTERM).
interactive iPromptsforconfirmationbeforekillingaprocess.
list lDisplaysalistofsignals(butkillldisplaysabetterlist).Withthis
optionkillalldoesnotacceptaname-list.
quiet qDoesnotdisplayamessageifkillallfailstoterminateaprocess.
Notes
Seealsokillonpage693.
SeeTable11-5onpage494foralistofsignals.Thecommandkillldisplaysacompletelistofsignal
numbersandnames.
Ifthesoftwareterminationsignaldoesnotterminatetheprocess,tryusingaKILLsignal(signalnumber
9).AprocesscanchoosetoignoreanysignalexceptKILL.
Youcanuseps(page746)todeterminethenameoftheprogramyouwanttoterminate.
Examples
Youcangivethefollowingcommandstoexperimentwithkillall:
$sleep60&
[1]23274
$sleep50&
[2]23275
$sleep40&
[3]23276
$sleep120&
[4]23277
$killallsleep
$RETURN
[1]Terminatedsleep60
[2]Terminatedsleep50
[3]-Terminatedsleep40
[4]+Terminatedsleep120
IfyouwanttoterminateallinstancesoftheFirefoxbrowser,givethefollowingcommandtodetermine
howFirefoxwascalled:
$ps-ef|grep-ifirefox
max17517175120Apr02?00:00:54
/usr/local/firefox/firefox-bin
max193402787000:33pts/600:00:00grepfirefox
Thenextcommand,runasroot,terminatesallinstancesoftheFirefoxbrowser:
#killallfirefox-bin
less:Displaystextfiles,onescreenatatime
less[options][file-list]
Thelessutilitydisplaystextfiles,onescreenatatime.
Arguments
Thefile-lististhelistoffilesyouwanttoview.Ifthereisnofile-list,lessreadsfromstandardinput.
Options
Acceptsthecommonoptionsdescribedonpage587.
clear-screen cRepaintsthescreenfromthetoplinedown
insteadofscrolling.
quit-at-eof e
(exit)Normallylessrequiresyoutoenterqto
terminate.Thisoptionexitsautomaticallythe
secondtimelessreadstheendoffile.
QUIT-AT-EOF E
(exit)Similartoe,exceptthatlessexits
automaticallythefirsttimeitreadstheendof
file.
quit-if-one-screen
FDisplaysthefileandquitsifthefilecanbe
displayedonasinglescreen.
ignore-case i
Causesasearchforastringoflowercaseletters
tomatchbothuppercaseandlowercaseletters.
Thisoptionisignoredifyougiveapatternthat
includesuppercaseletters.
IGNORE-CASE
I
Causesasearchforastringoflettersofany
casetomatchbothuppercaseandlowercase
letters,regardlessofthecaseofthesearch
pattern.
long-prompt m
Reportsthepercentageofthefilethatyouhave
viewedwitheachprompt.Thisoptioncauses
lesstodisplayapromptthatissimilartothe
promptusedbymore.Itdoesnotworkwhen
lessreadsfromstandardinputbecauseless
hasnowayofdetermininghowmuchinput
thereis.
LINE-NUMBERS
NDisplaysalinenumberatthestartofeachline.
Psprompt
Changestheshortpromptstring(theprompt
thatappearsatthebottomofeachscreenof
output)toprompt.Enclosepromptinquotation
marksifitcontainsSPACEs.Youcanuse
specialsymbolsinpromptthatlesswill
replacewithothervalueswhenitdisplaysthe
prompt.Forexample,lessdisplaysthe
currentfilenameinplaceof%finprompt.See
thelessmanpageforalistofthesespecial
symbolsanddescriptionsofotherprompts.
Custompromptsareusefulifyouarerunning
lessfromwithinanotherprogramandwantto
giveinstructionsorinformationtotheperson
whoisusingtheprogram.Thedefaultprompt
isthenameofthefiledisplayedinreverse
video.
squeeze-blank-lines
s
Displaysmultiple,adjacentblanklinesasa
singleblankline.Whenyouuselesstodisplay
textthathasbeenformattedforprintingwith
blankspaceatthetopandbottomofeachpage,
thisoptionshortenstheseheadersandfooters
toasingleline.
tabs=nxn
Setstabstopsncharactersapart.Thedefaultis
eightcharacters.
window=n[z]n
Setsthescrollingsizetonlines.Thedefaultis
thesizeofthedisplay.Eachtimeyoumove
forwardorbackwardapage,youmovenlines.
+command
Anycommandyoucangivelesswhileitis
runningcanalsobegivenasanoptionby
precedingitwithaplussign(+)onthe
commandline.Seethe"Commands"section.A
commandprecededbyaplussignonthe
commandlineisexecutedassoonasless
startsandappliesonlytothefirstfile.
++command
Similarto+commandexceptthatcommandis
appliedtoeveryfileinfile-list,notjustthefirst.
Notes
Thephrase"lessismore"explainstheoriginofthisutility.ThemoreutilityistheoriginalBerkeley
UNIXpager(alsoavailableunderLinux).Thelessutilityissimilartomorebutincludesmany
enhancements.Afterdisplayingascreenoftext,lessdisplaysapromptandwaitsforyoutoentera
command.Youcanskipforwardandbackwardinthefile,invokeaneditor,searchforapattern,or
performanumberofothertasks.
Seethevcommandinthenextsectionforinformationonhowyoucaneditthefileyouareviewingwith
less.
Youcansettheoptionstolesseitherfromthecommandlinewhenyoucalllessorbysettingthe
LESSenvironmentvariable.Forexample,youcanusethefollowingcommandfrombashtouseless
withthex4andsoptions.
$exportLESS="-x4-s"
NormallyyouwouldsetLESSin~/.bash_profileifyouareusingbashorin~/.loginifyouareusing
tcsh.OnceyouhavesettheLESSvariable,lessisinvokedwiththespecifiedoptionseachtimeyou
callit.AnyoptionsyougiveonthecommandlineoverridethesettingsintheLESSvariable.TheLESS
variableisusedbothwhenyoucalllessfromthecommandlineandwhenlessisinvokedbyanother
program,suchasman.Tospecifylessasthepagertousewithmanandotherprograms,setthe
environmentvariablePAGERtoless.Forexample,withbashyoucanaddthefollowinglineto
~/.bash_profile:
exportPAGER=less
Commands
Wheneverlesspauses,youcanenteranyofalargenumberofcommands.Thissectiondescribessome
commonlyusedcommands.Refertothelessmanpageforthefulllistofcommands.Theoptional
numericargumentndefaultsto1,withtheexceptionsnoted.Youdonotneedtofollowthesecommands
withaRETURN.
nbornCONTROL-B (backward)Scrollsbackwardnlines.Thedefaultvalueofnisthesize
ofthescreen.
ndornCONTROL-D
(down)Scrollsforwardnlines.Thedefaultvalueofnisone-halfthe
screensize.Whenyouspecifyn,itbecomesthenewdefaultvaluefor
thiscommand.
F
(forward)Scrollsforward.Iftheendoftheinputisreached,this
commandwaitsformoreinputandthencontinuesscrolling.This
commandallowsyoutouselessinamannersimilartotailf(page
783),exceptthatlesspaginatestheoutputasitappears.
ng
(go)Goestolinenumbern.Thiscommandmaynotworkifthefileis
readfromstandardinputandyouhavemovedtoofarintothefile.The
defaultvalueofnis1.
horH(help)Displaysasummaryofallavailablecommands.Thesummaryis
displayedusingless,asthelistofcommandsisquitelong.
nRETURNornj(jump)Scrollsforwardnlines.Thedefaultvalueofnis1.
qor:q Terminatesless.
nuornCONTROL-U Scrollsbackwardnlines.Thedefaultvalueofnisone-halfthescreen
size.Whenyouspecifyn,itbecomesthedefaultvalueforthis
command.
v
Bringsthecurrentfileintoaneditorwiththecursoronthecurrentline.
ThelessutilityusestheeditorspecifiedintheEDITORenvironment
variable.IfEDITORisnotset,lessusesvi(whichistypically
linkedtovim).
nwScrollsbackwardlikenb,exceptthatthevalueofnbecomesthenew
defaultvalueforthiscommand.
nyornkScrollsbackwardnlines.Thedefaultvalueofnis1.
nz
DisplaysthenextnlineslikenSPACEexceptthatthevalueofn,if
present,becomesthenewdefaultvalueforthezandSPACE
commands.
nSPACE Displaysthenextnlines.PressingSPACEbyitselfdisplaysthenext
screenoftext.
/regular-expression
Skipsforwardinthefile,lookingforlinesthatcontainamatchfor
regular-expression.Ifyoubeginregular-expressionwithan
exclamationpoint(!),thiscommandlooksforlinesthatdonotcontain
amatchforregular-expression.Ifregular-expressionbeginswithan
asterisk(*),thiscommandcontinuesthesearchthroughfile-list.(A
normalsearchstopsattheendofthecurrentfile.)Ifregular-
expressionbeginswithanatsign(@),thiscommandbeginsthesearch
atthestartoffile-listandcontinuestotheendoffile-list.
?regular-expression
Thiscommandissimilartothepreviousonebutsearchesbackward
throughthefile(andfile-list).Anasterisk(*)asthefirstcharacterin
regular-expressioncausesthesearchtocontinuebackwardthrough
file-listtothebeginningofthefirstfile.Anatsign(@)causesthe
searchtostartwiththelastlineofthelastfileinfile-listandprogress
towardthefirstlineofthefirstfile.
{or(or[
Ifoneofthesecharactersappearsinthetoplineofthedisplay,this
commandscrollsforwardtothematchingrightbrace,parenthesis,or
bracket.Forexample,typing{causeslesstomovethecursor
forwardtothematching}.
}or)or]Similartotheprecedingcommands,thesecommandsmovethecursor
backwardtothematchingleftbrace,parenthesis,orbracket.
CONTROL-L Redrawsthescreen.Thiscommandisusefulifthetextonthescreen
hasbecomegarbled.
[n]:n Skipstothenextfileinfile-list.Ifnisgiven,skipstothenthnextfile
infile-list.
![commandline]
ExecutescommandlineundertheshellspecifiedbytheSHELL
environmentvariable,orsh(usuallylinkedtobash)bydefault.A
percentsign(%)incommandlineisreplacedbythenameofthe
currentfile.Ifyouomitcommandline,lessstartsaninteractive
shell.
Examples
Thefollowingexampledisplaysthefilememo.txt.Toseemoreofthefile,theuserpressestheSPACE
barinresponsetothelesspromptatthebottomleftofthescreen:
$lessmemo.txt
...
memo.txtSPACE
...
Inthenextexample,theuserchangestheprompttoamoremeaningfulmessageandusestheNoptionto
displaylinenumbers.Finallytheuserinstructslesstoskipforwardtothefirstlinecontainingthestring
procedure.
$less-Ps"PressSPACEtocontinue,qtoquit"-N+/procedure
ncut.icn
28proceduremain(args)
29localfilelist,arg,fields,delim
30
31filelist:=[]
...
45#Checkforrealfieldlist
46#
47if/fieldsthenstop("-fFIELD_LISTisrequired.")
48
49#Processthefilesandoutputthefields
PressSPACEtocontinue,qtoquit
ln:Makesalinktoafile
ln[options]existing-file[new-link]
ln[options]existing-file-listdirectory
Thelnutilitycreateshardorsymboliclinkstooneormorefiles.Youcancreateasymboliclink,butnot
ahardlink,toadirectory.
Arguments
Inthefirstformattheexisting-fileisthepathnameofthefileyouwanttocreatealinkto.Thenew-linkis
thepathnameofthenewlink.Whenyouarecreatingasymboliclink,theexisting-filecanbeadirectory.
Ifyouomitnew-link,lncreatesalinktoexisting-fileintheworkingdirectory,andusesthesamesimple
filenameasexisting-file.
Inthesecondformattheexisting-file-listisalistofthepathnamesoftheordinaryfilesyouwanttocreate
linksto.Thelnutilityestablishesthenewlinksinthedirectory.Thesimplefilenamesoftheentriesin
thedirectoryarethesameasthesimplefilenamesofthefilesintheexisting-file-list.
Options
backup bIfthelnutilitywillremoveafile,thisoptionmakesabackupby
appending~tothefilename.Thisoptionworksonlywithforce.
force f
Normallylndoesnotcreatethelinkifnew-linkalreadyexists.This
optionremovesnew-linkbeforecreatingthelink.Whenyouuse
forceandbackuptogether,lnmakesacopyofnew-linkbefore
removingit.
interactive i
Ifnew-linkalreadyexists,thisoptionpromptsyoubeforeremoving
new-link.Ifyouenteryoryes,lnremovesnew-linkbeforecreating
thelink.Ifyouanswernorno,nonewlinkismade.
symbolic s
Createsasymboliclink.Whenyouusethisoption,theexisting-file
andnew-linkmaybedirectoriesandmayresideondifferent
filesystems.Referto"SymbolicLinks"onpage99.
Notes
Formoreinformationreferto"Links"onpage96.Thelsutilitywiththeloptiondisplaysthenumberof
hardlinkstoafile(Figure4-12,page92).
Hardlinks
Bydefaultlncreateshardlinks.Ahardlinktoafileisindistinguishablefromtheoriginalfile.Allhard
linkstoafilemustbeinthesamefilesystem.Formoreinformationreferto"HardLinks"onpage97.
Symboliclinks
Youcanalsouselntocreatesymboliclinks.Unlikeahardlink,asymboliclinkcanexistinadifferent
filesystemfromthelinked-tofile.Also,asymboliclinkcanpointtoadirectory.Formoreinformation
referto"SymbolicLinks"onpage99.
Ifnew-linkisthenameofanexistingfile,lndoesnotcreatethelinkunlessyouusetheforceoptionor
answeryeswhenusingtheinteractiveoption.
Examples
Thefollowingcommandcreatesalinkbetweenmemo2inthe/home/zach/literaturedirectoryandthe
workingdirectory.Thefileappearsasmemo2(thesimplefilenameoftheexistingfile)intheworking
directory:
$ln/home/zach/literature/memo2.
Youcanomittheperiodthatrepresentstheworkingdirectoryfromtheprecedingcommand.Whenyou
giveasingleargumenttoln,itcreatesalinkintheworkingdirectory.
Thenextcommandcreatesalinktothesamefile.Thistimethefileappearsasnew_memointheworking
directory:
$ln/home/zach/literature/memo2new_memo
Thefollowingcommandcreatesalinkthatcausesthefiletoappearinanotheruser'sdirectory:
$ln/home/zach/literature/memo2/home/jenny/new_memo
Youmusthavewriteandexecuteaccesspermissiontotheotheruser'sdirectoryforthiscommandto
work.Ifyouownthefile,youcanusechmodtogivetheotheruserwriteaccesspermissiontothefile.
Thenextcommandcreatesasymboliclinktoadirectory.Thelsldcommandshowsthelink:
$ln-s/usr/local/binbin
$ls-ldbin
lrwxrwxrwx1zachzach14Feb1013:26bin->/usr/local/bin
Thefinalexampleattemptstocreateasymboliclinknamedmemo1tothefilememo2.Becausethefile
memo1exists,lnrefusestomakethelink.Whenyouusetheinteractiveoption,lnaskswhetheryou
wanttoreplacetheexistingmemo1filewiththesymboliclink.Ifyouenteryoryes,lncreatesthelink
andtheoldmemo1disappears.
$ls-lmemo?
-rw-rw-r--1zachgroup224Jul3114:48memo1
-rw-rw-r--1zachgroup753Jul3114:49memo2
$ln--symbolicmemo2memo1
ln:memo1:Fileexists
$ln--symbolic--interactivememo2memo1
ln:replace'memo1'?y
$ls-lmemo?
lrwxrwxrwx1zachgroup5Jul3114:49memo1->memo2
-rw-rw-r--1zachgroup753Jul3114:49memo2
Youcanalsousetheforceoptiontocauselntooverwriteafile.
lpr:Sendsfilestoprinters
lpr[options][file-list]
lpq[options][job-identifiers]
lprm[options][job-identifiers]
Thelprutilityplacesoneormorefilesintoaprintqueue,providingorderlyaccesstoprintersfor
severalusersorprocesses.Theutilitycanworkwithprintersattachedtoremotesystems.Youcanusethe
lprmutilitytoremovefilesfromtheprintqueuesandthelpqutilitytocheckthestatusoffilesinthe
queues.Referto"Notes"laterinthissection.
Arguments
Thefile-listisalistofoneormorefilenamesforlprtoprint.Oftenthesefilesaretextfiles,butmany
systemsareconfiguredsothatlprcanacceptandproperlyprintavarietyoffiletypes.Withoutafile-
list,lpracceptsinputfromstandardinput.
Thejob-identifiersisalistofjobnumbersorusernames.Ifyoudonotknowthejobnumberofaprint
job,uselpqtodisplayalistofprintjobs.
Options
Someofthefollowingoptionsdependonthetypeoffilebeingprintedaswellasonhowthesystemis
configuredforprinting.
l(lowercase"l")Specifiesthatlprshouldnotpreprocess(filter)thefilebeingprinted.
Usethisoptionwhenthefileisalreadyformattedfortheprinter.
Pprinter
Routestheprintjobstothequeuefortheprinternamedprinter.Ifyoudonotusethis
option,printjobsareroutedtothedefaultprinterforthelocalsystem.Theacceptable
valuesforprinterarefoundinthefile/etc/printcapandvaryfromsystemtosystem.
r(remove)Deletesthefilesinfile-listaftercallinglpr.
#n
Printsncopiesofeachfile.Dependingonwhichshellyouareusing,youmayneedto
escapethe#withabackslashtopassittolpr.
Discussion
Thelprutilitytakesinputfromfilesyouspecifyonthecommandlineorfromstandardinputandadds
thefilestotheprintqueueasprintjobs.Theutilityassignsauniqueidentificationnumbertoeachprint
job.Thelpqutilitydisplaysthejobnumbersoftheprintjobsthatlprhassetup;youcanusethelprm
utilitytoremoveaprintjobfromtheprintqueue.
lpq
Thelpqutilitydisplaysinformationaboutjobsinaprintqueue.Whencalledwithoutanyarguments,
lpqlistsalltheprintjobsqueuedforthedefaultprinter.Uselpr'sPprinteroptionwithlpqtolookat
otherprintqueueseventhoseforprintersconnectedtoothersystems.Withtheloptionlpqdisplaysmore
informationabouteachjob.Ifyougivetheusernameofauserasanargument,lpqdisplaysonlythe
printerjobsbelongingtothatuser.
lprm
Oneitemdisplayedbylpqisthejobnumberforeachprintjobinthequeue.Toremoveajobfromthe
printqueue,usethejobnumberasanargumenttolprm.UnlessyouareSuperuser,youcanremoveonly
yourownjobs.EvenasSuperuseryoumaynotbeabletoremoveajobfromaqueueforaremoteprinter.
Ifyoudonotgiveanyargumentstolprm,itremovesthecurrentlyactiveprinterjob(thatis,thejobthat
isnowprinting)fromthequeue,ifyouownthatjob.
Notes
Ifyounormallyuseaprinterotherthanthesystemdefaultprinter,youcansetuplprtouseanother
printerasyourpersonaldefaultbyassigningthenameofthisprintertotheenvironmentvariable
PRINTER.Forexample,ifyouusebash,youcanaddthefollowinglineto~/.bash_profiletosetyour
defaultprintertotheprinternamedps:
exportPRINTER=ps
LPDandLPR
Traditionally,UNIXhadtwoprintingsystems:theBSDLinePrinterDaemon(LPD)andtheSystemV
LinePrintersystem(LPR).Linuxadoptedthosesystemsatfirst,andbothUNIXandLinuxhaveseen
modificationstoandreplacementsforthesesystems.TodayCUPSisthedefaultprintingsystemunder
manyLinuxdistributions.
CUPS
CUPS(CommonUNIXPrintingSystem)isacross-platformprintserverbuiltaroundIPP(Internet
PrintingProtocol),whichisbasedonHTTP.CUPSprovidesanumberofprinterdriversandcanprint
differenttypesoffiles,includingPostScriptfiles.CUPSprovidesSystemVandBSDcommandline
interfacesand,inadditiontoIPP,supportsLPD/LPR,HTTP,SMB,andJetDirect(socket)protocols,
amongothers.
ThissectiondescribestheLPDcommandlineinterfacethatrunsunderCUPSandalsoinnativemodeon
oldersystems.
Examples
Thefirstcommandsendsthefilenamedmemo2tothedefaultprinter:
$lprmemo2
Nextapipesendstheoutputoflstotheprinternameddeskjet:
$ls|lpr-Pdeskjet
Thenextexamplepaginatesandsendsthefilememototheprinter:
$pr-h"Today'smemo"memo|lpr
Thenextexampleshowsanumberofprintjobsqueuedforthedefaultprinter.Alexownsallofthesejobs,
andthefirstoneiscurrentlybeingprinted(active).Jobs635and639werecreatedbysendinginputto
lpr'sstandardinput;job638wascreatedbygivingncut.icnasanargumenttothelprcommand.The
lastcolumngivesthesizeofeachprintjob.
$lpq
deskjetisreadyandprinting
RankOwnerJobFilesTotal
Size
activealex635(stdin)38128
bytes
1stalex638ncut.icn3587
bytes
2ndalex639(stdin)3960
bytes
Thenextcommandremovesjob638fromthedefaultprintqueue:
$lprm638
ls:Displaysinformationaboutoneormorefiles
ls[options][file-list]
Thelsutilitydisplaysinformationaboutoneormorefiles.Itliststheinformationalphabeticallyby
filenameunlessyouuseanoptiontochangetheorder.
Arguments
Whenyoudonotprovideanargument,lsdisplaysthenamesofthevisiblefilesintheworkingdirectory
(thosefileswhosefilenamesdonotbeginwithaperiod).
Thefile-listisalistofoneormorepathnamesofanyordinary,directory,ordevicefiles.Itcaninclude
ambiguousfilereferences.
Whenyouspecifyadirectory,lsdisplaysthecontentsofthedirectory.Itdisplaysthenameofthe
directoryonlywhenneededtoavoidambiguity,suchaswhenthelistingincludesmorethanonedirectory.
Whenyouspecifyanordinaryfile,lsdisplaysinformationaboutthatonefile.
Options
Theoptionsdeterminethetypeofinformationlsdisplays,themannerinwhichitdisplaysthe
information,andtheorderinwhichitisdisplayed.Whenyoudonotuseanoption,lsdisplaysashort
listthatcontainsonlythenamesoffiles.
all a
Includesinvisiblefiles(thosewithfilenamesthatbeginwithaperiod)in
thelisting.Withoutthisoptionlsdoesnotlistinformationaboutinvisible
filesunlessyoulistthenameofaninvisiblefileinthefile-list.Whenyou
usethisoptionwithafile-listthatincludesanappropriateambiguousfile
reference,lsdisplaysinformationaboutinvisiblefiles.The*ambiguous
filereferencedoesnotmatchaleadingperiodinafilename(seepage
129).
almost-all AThesameasallbutdoesnotlistthe.and..entries.
escape b
Displaysnonprintingcharactersinafilename,usingbackslashescape
sequencessimilartothoseusedinClanguagestrings.Apartiallistis
giveninTableV-16.Othernonprintingcharactersaredisplayedasa
backslashfollowedbyanoctalnumber.

TableV-16.Backslashescapesequences
Sequence Meaning
\b BACKSPACE
\n NEWLINE
\r RETURN
\t HORIZONTALTAB
\v VERTICALTAB
\\ BACKSLASH
color[=when]
Thelsutilitycandisplayvarioustypesoffilesindifferentcolorsbut
normallydoesnotusecolors(thesameresultaswhenyouspecify
whenasnone).Ifyoudonotspecifywhenorifyouspecifywhenas
always,lsusescolors.Whenyouspecifywhenasauto,lsuses
colorsonlywhentheoutputgoestoascreen.See"Notes"formore
information.
directory d
Displaysthenamesofdirectorieswithoutdisplayingtheircontents.
Withoutanargumentthisoptiondisplaysinformationabouttheworking
directory.Itdoesnotdereferencesymboliclinks(itlistsalink,notthe
directoryitpointsto).
format=word
Bydefaultlsdisplaysfilessortedvertically.Thisoptionsortsfiles
basedonword:across(x),separatedbycommas(m),horizontal(x),
long(l),orsingle-column(1).
classify FDisplaysaslash(/)aftereachdirectory,anasterisk(*)aftereach
executablefile,andanatsign(@)afterasymboliclink.
human-readable
h
DisplayssizesinK(kilobyte),M(megabyte),andG(gigabyte)blocks,
asappropriate.Workswiththeloptiononly.Thisoptionusespowers
of1,024;usesiforpowersof1,000.
inode i
Displaystheinodenumberofeachfile.Withtheloptionthisoption
displaystheinodenumberincolumn1andshiftsallotheritemsone
columntotheright.
format=long l
(lowercase"l")Listsmoreinformationabouteachfile.Usethisoption
withhtomakefilesizesmorereadable.See"Discussion"formore
information.

dereference LListsinformationaboutthefilereferencedbyasymboliclinkratherthan
informationaboutthelinkitself.
mDisplaysacomma-separatedlistoffilesthatfillsthewidthofthe
screen.
hide-control-chars
qDisplaysnonprintingcharactersinafilenameasquestionmarks.When
outputisgoingtothescreen,thisisthedefaultbehavior.
reverse rDisplaysthelistoffilenamesinreversesortedorder.
recursive RRecursivelylistssubdirectories.
size s
Displaysthenumberof1,024-byteblocksallocatedtothefile.Thesize
precedesthefilename.Withtheloptionthisoptiondisplaysthesizein
column1andshiftsallotheritemsonecolumntotheright.Youcan
includethehoptiontomakethefilesizeseasiertoread.
sort=word
BydefaultlsdisplaysfilesinASCIIorder.Thisoptionsortsthefiles
basedonword:filenameextension(X),none(U),filesize(S),access
time(u),ormodificationtime(t).Seetimeforanexception.
time=word
Bydefaultlswiththeloptiondisplaysthemodificationtimeofafile.
Setwordtoatimetodisplaytheaccesstime(orusethetoption)orto
ctimetodisplaythecreationtime.Thelistissortedbywordwhenyou
alsogivethesort=timeoption.
xDisplaysfilessortedbylines(thedefaultdisplayissortedbycolumns).
XDisplaysfilessortedbyfilenameextension.Fileswithnofilename
extensionarelistedfirst.
1(one)Displaysfilesoneperline.
Discussion
Thelslonglisting(format=longorloptions)displaysthesevencolumnsshowninFigure4-12onpage
92.Thefirstcolumn,whichcontains11characters,isdividedasdescribedinthefollowingparagraphs.
Thefirstcharacterdescribesthetypeoffile,asshowninTableV-17.
TableV-17.Firstcharacterinalonglsdisplay
Character Meaning

Ordinary
bBlockdevice
cCharacterdevice
dDirectory
pFIFO(namedpipe)
lSymboliclink
Thenextninecharactersofthefirstcolumnrepresenttheaccesspermissionsassociatedwiththefile.
Theyaredividedintothreesetsofthreecharacterseach.
Thefirstthreecharactersrepresenttheowner'saccesspermissions.Iftheownerhasreadaccess
permissiontothefile,rappearsinthefirstcharacterposition.Iftheownerisnotpermittedtoreadthe
file,ahyphenappearsinthisposition.Thenexttwopositionsrepresenttheowner'swriteandexecute
accesspermissions.Ifwappearsinthesecondpositiontheownerispermittedtowritetothefile;ifx
appearsinthethirdpositiontheownerispermittedtoexecutethefile.Ansinthethirdpositionindicates
thatthefilehassetuidpermissionandexecutepermission.AnSindicatessetuidwithoutexecute
permission.Ahyphenindicatesthattheownerdoesnothavetheaccesspermissionassociatedwiththe
characterposition.
Inasimilarmannerthesecondandthirdsetsofthreecharactersrepresenttheaccesspermissionsofthe
groupthefileisassociatedwithandofotherusers.Ansinthethirdpositionofthesecondsetof
charactersindicatesthatthefilehassetgidpermissionwithexecutepermission,andanSindicatessetgid
withoutexecutepermission.
Thelastcharacteristifthestickybit(page903)issetwithexecutepermissionandTifitissetwithout
executepermission.Refertochmodonpage604forinformationonchangingaccesspermissions.
Figure4-12onpage92illustratesthecolumnsdescribedinthefollowingparagraphs.
Thesecondcolumnindicatesthenumberofhardlinkstothefile.Refertopage96formoreinformation
onlinks.
Thethirdandfourthcolumnsdisplaythenameoftheownerofthefileandthenameofthegroupthefileis
associatedwith.
Thefifthcolumnindicatesthesizeofthefileinbytesor,ifinformationaboutadevicefileisbeing
displayed,themajorandminordevicenumbers.Inthecaseofadirectory,thisnumberisthesizeofthe
directoryfile,notthesizeofthefilesthatareentrieswithinthedirectory.(Usedutodisplaythesumof
thesizesofallfilesinadirectory.)Usethehoptiontodisplaythesizeoffilesinkilobytes,megabytes,or
gigabytes.
Thelasttwocolumnsdisplaythedateandtimethefilewaslastmodifiedandthefilename,respectively.
Notes
Refertopage127forexamplesofusinglswithambiguousfilereferences.
Withthecoloroptionlsdisplaysfilenamesofvarioustypesoffilesindifferentcolors.Bydefault
executablefilesaregreen,directoryfilesareblue,symboliclinksarecyan,archivesandcompressed
filesarered,andordinarytextfilesareblack.Themannerinwhichlscolorsthevariousfiletypesis
specifiedinthe/etc/DIR_COLORSfile.Ifthisfiledoesnotexistonthelocalsystem,lswillnotcolor
filenames.Youcanmodify/etc/DIR_COLORStoalterthedefaultcolor/filetypemappingsona
systemwidebasis.Foryourpersonaluse,youcancopy/etc/DIR_COLORStothe~/.dir_colorsfilein
yourhomedirectoryandmodifyit.Foryourlogin,~/.dir_colorsoverridesthesystemwidecolors
establishedin/etc/DIR_COLORS.Refertothedir_colorsanddircolorsmanpagesformore
information.
Examples
Thefirstcommandlineshowsthelsutilitywiththexoption,whichsortsthefileshorizontally.Thels
utilitydisplaysanalphabeticallistofthenamesofthefilesintheworkingdirectory:
$ls-x
binccalendar
executelettersshell
TheFoptionappendsaslash(/)tofilesthataredirectories,anasterisktofilesthatareexecutable,and
anatsign(@)aftersymboliclinks:
$ls-Fx
bin/c/calendar
execute*letters/shell@
Nextthel(long)optiondisplaysalonglist.Thefilesarestillinalphabeticalorder:
$ls-l
total8
drwxrwxr-x2jennypubs80May2009:17bin
drwxrwxr-x2jennypubs144Mar2611:59c
-rw-rw-r--1jennypubs104May2811:44calendar
-rwxrw-r--1jennypubs85May608:27execute
drwxrwxr-x2jennypubs32Oct622:56letters
drwxrwxr-x16jennypubs1296Jun617:33shell
Thea(all)optionlistsallfiles,includinginvisibleones:
$ls-a
..profilecexecuteshell
..bincalendarletters
Combiningtheaandloptionsdisplaysalonglistingofallfiles,includinginvisiblefiles,intheworking
directory.Thislistisstillinalphabeticalorder:
$ls-al
total12
drwxrwxr-x6jennypubs480Jun617:42.
drwxrwx---26rootroot816Jun614:45..
-rw-rw-r--1jennypubs161Jun617:15.profile
drwxrwxr-x2jennypubs80May2009:17bin
drwxrwxr-x2jennypubs144Mar2611:59c
-rw-rw-r--1jennypubs104May2811:44calendar
-rwxrw-r--1jennypubs85May608:27execute
drwxrwxr-x2jennypubs32Oct622:56letters
drwxrwxr-x16jennypubs1296Jun617:33shell
Whenyouaddther(reverse)optiontothecommandline,lsproducesalistinreversealphabetical
order:
$ls-ral
total12
drwxrwxr-x16jennypubs1296Jun617:33shell
drwxrwxr-x2jennypubs32Oct622:56letters
-rwxrw-r--1jennypubs85May608:27execute
-rw-rw-r--1jennypubs104May2811:44calendar
drwxrwxr-x2jennypubs144Mar2611:59c
drwxrwxr-x2jennypubs80May2009:17bin
-rw-rw-r--1jennypubs161Jun617:15.profile
drwxrwx---26rootroot816Jun614:45..
drwxrwxr-x6jennypubs480Jun617:42.
Usethetandloptionstolistfilessothatthemostrecentlymodifiedfileappearsatthetopofthelist:
$ls-tl
total8
drwxrwxr-x16jennypubs1296Jun617:33shell
-rw-rw-r--1jennypubs104May2811:44calendar
drwxrwxr-x2jennypubs80May2009:17bin
-rwxrw-r--1jennypubs85May608:27execute
drwxrwxr-x2jennypubs144Mar2611:59c
drwxrwxr-x2jennypubs32Oct622:56letters
Togethertherandtoptionscausethefileyoumodifiedleastrecentlytoappearatthetopofthelist.
$ls-trl
total8
drwxrwxr-x2jennypubs32Oct622:56letters
drwxrwxr-x2jennypubs144Mar2611:59c
-rwxrw-r--1jennypubs85May608:27execute
drwxrwxr-x2jennypubs80May2009:17bin
-rw-rw-r--1jennypubs104May2811:44calendar
drwxrwxr-x16jennypubs1296Jun617:33shell
Thenextexampleshowslswithadirectoryfilenameasanargument.Thelsutilityliststhecontentsof
thedirectoryinalphabeticalorder:
$lsbin
celsdir
Todisplayinformationaboutthedirectoryfileitself,usethed(directory)option.Thisoptionlists
informationonlyaboutthedirectory:
$ls-dlbin
drwxrwxr-x2jennypubs80May2009:17bin
Youcanusethefollowingcommandtodisplayalistofallinvisiblefilenames(thosestartingwitha
period)inyourhomedirectory.Thisisaconvenientwaytolisttheinitializationfilesinyourhome
directory:
$ls-d~/.*
/home/sam/./home/sam/.gtkrc-kde
/home/sam/../home/sam/.history
...
make:Keepsasetofprogramscurrent
make[options][target-files][arguments]
TheGNUmakeutilitykeepsasetofexecutableprogramscurrent,basedondifferencesinthe
modificationtimesoftheprogramsandthesourcefilesthateachprogramisdependenton.
Arguments
Thetarget-filesrefertotargetsondependencylinesinthemakefile.Whenyoudonotspecifyatarget-
file,makeupdatesthetargetonthefirstdependencylineinthemakefile.Commandlineargumentsof
theformname=valuesetthevariablenametovalueinsidethemakefile.See"Discussion"formore
information.
Options
Ifyoudonotusethefoption,maketakesitsinputfromafilenamedGNUmakefile,makefile,or
Makefile(inthatorder)intheworkingdirectory.Inthissection,thisinputfileisreferredtoasmakefile.
ManyusersprefertousethenameMakefilebecauseitshowsupearlierindirectorylistings.
Cdirectory
Changesdirectoriestodirectorybeforestarting.
d(debug)Displaysinformationabouthowmakedecideswhattodo.
ffile
(inputfile)Usesfileasinputinsteadofmakefile.
jn
(jobs)Runsuptoncommandsatthesametimeinsteadofthedefaultofone
command.Runningmultiplecommandssimultaneouslyisespeciallyeffectiveifyou
arerunningLinuxonamultiprocessorsystem.Ifyouomitn,makedoesnotlimitthe
numberofsimultaneousjobs.
kContinueswiththenextfilefromthelistoftarget-filesinsteadofquittingwhena
constructioncommandfails.
n
(noexecution)Displays,butdoesnotexecute,thecommandsthatmakewould
executetobringthetarget-filesup-to-date.
s(silent)Doesnotdisplaythenamesofthecommandsbeingexecuted.
t(touch)Updatesthemodificationtimesoftargetfilesbutdoesnotexecuteany
constructioncommands(page403).Refertotouchonpage801.
Discussion
Themakeutilitybasesitsactionsonthemodificationtimesoftheprogramsandthesourcefilesthateach
programisdependenton.Eachoftheexecutableprograms,ortarget-files,isdependentononeormore
prerequisitefiles.Therelationshipsbetweentarget-filesandprerequisitesarespecifiedondependency
linesinamakefile.Constructioncommandsfollowthedependencyline,specifyinghowmakecanupdate
thetarget-files.
Documentation
Refertopage399formoreinformationaboutmakeandmakefiles.Foradditionalinformationreferto
www.gnu.org/software/make/manual/make.htmlandtothemakeinfopage.
Althoughthemostcommonuseofmakeistobuildprogramsfromsourcecode,thisgeneral-purpose
buildutilityissuitableforawiderangeofapplications.Anywhereyoucandefineasetofdependencies
togetfromonestatetoanotherrepresentsanidealcandidateforusingmake.
Muchofmake'spowerderivesfromthefeaturesyoucansetupinamakefile.Forexample,youcan
definevariablesusingthesamesyntaxfoundintheBourneAgainShell.Alwaysdefinethevariable
SHELLinamakefile;setittothepathnameoftheshellyouwanttousewhenrunningconstruction
commands.Todefinethevariableandassignitavalue,placethefollowinglinenearthetopofa
makefile:
SHELL=/bin/sh
Assigningthevalue/bin/shtoSHELLallowsyoutouseamakefileonothercomputersystems.OnLinux
systems/bin/shisgenerallylinkedto/bin/bash.Themakeutilityusesthevalueoftheenvironment
variableSHELLifyoudonotsetSHELLinamakefile.IfSHELLdoesnotholdthepathoftheshell
youintendedtouseandifyoudonotsetSHELLinamakefile,theconstructioncommandsmayfail.

Followingisalistofadditionalfeaturesassociatedwithmake:
Youcanrunspecificconstructioncommandssilentlybyprecedingthemwithan@sign.For
example,thefollowinglineswilldisplayashorthelpmessagewhenyourunthecommandmake
help:
help:
@echo"Youcanmakethefollowing:"
@echo""
@echo"libbuf.a--thebufferlibrary"
@echo"Bufdisplay--displayany-formatbuffer"
@echo"Buf2ppm--convertbuffertopixmap"
Withoutthe@signsintheprecedingexample,makewoulddisplayeachoftheechocommands
beforeexecutingit.Thiswayofdisplayingamessageworksbecausenofileisnamedhelpinthe
workingdirectory.Asaresultmakerunstheconstructioncommandsinanattempttobuildthisfile.
Becausetheconstructioncommandsdisplaymessagesbutdonotbuildthefilehelp,youcanrun
makehelprepeatedlywiththesameresult.
Youcancausemaketoignoretheexitstatusofacommandbyprecedingthecommandwithahyphen
().Forexample,thefollowinglineallowsmaketocontinueregardlessofwhetherthecallto
/bin/rmissuccessful(thecallto/bin/rmfailsiflibbuf.adoesnotexist):
-/bin/rmlibbuf.a
Youcanusespecialvariablestorefertoinformationthatmightchangefromoneuseofmaketothe
next.Suchinformationmightincludethefilesthatneedupdating,thefilesthatarenewerthanthe
target,orthefilesthatmatchapattern.Forexample,youcanusethevariable$?inaconstruction
commandtoidentifyallprerequisitefilesthatarenewerthanthetargetfile.Thisvariableallows
youtoprintanyfilesthathavechangedsincethelasttimeyouprintedfilesout:

list:.list
.list:Makefilebuf.hxtbuff_ad.hbuff.cbuf_print.cxtbuff.c
pr$?|lpr
date>.list
Thetargetlistdependsonthesourcefilesthatmightbeprinted.Theconstructioncommandpr$?|
lprprintsonlythosesourcefilesthatarenewerthanthefile.list.Thelinedate>.listmodifiesthe
.listfilesothatitisnewerthananyofthesourcefiles.Thenexttimeyourunthecommandmakelist,
onlythefilesthathavebeenchangedareprinted.
Youcanincludeothermakefilesasiftheywerepartofthecurrentmakefile.Thefollowingline
causesmaketoreadMake.configandtreatthecontentsofthatfileasthoughitwerepartofthe
currentmakefile,allowingyoutoputinformationcommontomorethanonemakefileinasingle
place:
includeMake.config
Notes
Thesection"make:KeepsaSetofProgramsCurrent"onpage399providesmoreinformationabout
make.
Examples
Thefirstexamplecausesmaketobringthetarget-filenamedanalysisup-to-datebyissuingthreecc
commands.ItusesamakefilenamedGNUmakefile,makefile,orMakefileintheworkingdirectory.
$makeanalysis
cc-canaly.c
cc-cstats.c
cc-oanalysisanaly.ostats.o
Thefollowingexamplealsoupdatesanalysisbutusesamakefilenamedanalysis.mkintheworking
directory:
$make-fanalysis.mkanalysis
'analysis'isuptodate.
Thenextexampleliststhecommandsmakewouldexecutetobringthetarget-filenamedcreditup-to-
date.Becauseofthen(no-execution)option,makedoesnotexecutethecommands.
$make-ncredit
cc-c-Ocredit.c
cc-c-Oaccounts.c
cc-c-Oterms.c
cc-ocreditcredit.caccounts.cterms.c
Thenextexampleusesthetoptiontoupdatethemodificationtimeofthetarget-filenamedcredit.After
youusethisoption,makethinksthatcreditisup-to-date.
$make-tcredit
$makecredit
'credit'isuptodate.
Nextisasimplemakefileforbuildingautilitynamedff.Becausethecccommandneededtobuildff
iscomplex,usingamakefileallowsyoutorebuildffeasily,withouthavingtorememberandretypethe
cccommand.
$catMakefile
#Buildtheffcommandfromthefastfind.csource
SHELL=/bin/sh
ff:
cc-traditional-O2-g-DBIG=5120-offfastfind.cmyClib.a
$makeff
cc-traditional-O2-g-DBIG=5120-offfastfind.cmyClib.a
Thefollowingexampleshowsamuchmoresophisticatedmakefilethatusesfeaturesnotdiscussedinthis
section.Refertothesourcescitedunder"Documentation"onpage716forinformationabouttheseand
otheradvancedfeatures.
$catMakefile
###########################################################
##buildandmaintainthebufferlibrary
###########################################################
SHELL=/bin/sh
###########################################################
##Flagsandlibrariesforcompiling.TheXLDLIBSareneeded
#wheneveryoubuildaprogramusingthelibrary.TheCCFLAGS
#givemaximumoptimization.
CC=gcc
CCFLAGS=-O2$(CFLAGS)
XLDLIBS=-lXaw3d-lXt-lXmu-lXext-lX11-lm
BUFLIB=libbuf.a
###########################################################
##Miscellaneous
INCLUDES=buf.h
XINCLUDES=xtbuff_ad.h
OBJS=buff.obuf_print.oxtbuff.o
###########################################################
##Justa'make'generatesahelpmessage
help:Help
@echo"Youcanmakethefollowing:"
@echo""
@echo"libbuf.a--thebufferlibrary"
@echo"bufdisplay--displayany-formatbuffer"
@echo"buf2ppm--convertbuffertopixmap"
###########################################################
##Themaintargetisthelibrary
libbuf.a:$(OBJS)
-/bin/rmlibbuf.a
arrvlibbuf.a$(OBJS)
ranliblibbuf.a
###########################################################
##Secondarytargets--utilitiesbuiltfromthelibrary
bufdisplay:bufdisplay.clibbuf.a
$(CC)$(CCFLAGS)bufdisplay.c-obufdisplay$(BUFLIB)$(XLDLIBS)
buf2ppm:buf2ppm.clibbuf.a
$(CC)$(CCFLAGS)buf2ppm.c-obuf2ppm$(BUFLIB)
###########################################################
##Buildtheindividualobjectunits
buff.o:$(INCLUDES)buff.c
$(CC)-c$(CCFLAGS)buff.c
buf_print.o:$(INCLUDES)buf_print.c
$(CC)-c$(CCFLAGS)buf_print.c
xtbuff.o:$(INCLUDES)$(XINCLUDES)xtbuff.c
$(CC)-c$(CCFLAGS)xtbuff.c
Themakeutilitycanbeusedfortasksotherthancompilingcode.Asafinalexample,assumethatyou
haveadatabasethatlistsIPaddressesandthecorrespondinghostnamesintwocolumnsandthatthe
databasedumpsthesevaluestoafilenamedhosts.tab.Youneedtoextractonlythehostnamesfromthis
fileandgenerateaWebpagenamedhosts.htmlcontainingthesenames.Thefollowingmakefileisa
simplereportwriter:
$catmakefile
#
SHELL=/bin/bash
#
hosts.html:hosts.tab
@echo"<HTML><BODY>">hosts.html
@awk'{print$$2,"<br>"}'hosts.tab>>hosts.html
@echo"</BODY></HTML>">>hosts.html
man:Displaysdocumentationforcommands
man[options][section]command
mankkeyword
ThemanutilityprovidesonlinedocumentationforLinuxcommands.Inadditiontousercommands,
documentationisavailableformanyothercommandsanddetailsthatrelatetoLinux.BecausemanyLinux
commandscomefromGNU,theGNUinfoutility(page32)frequentlyprovidesmorecomplete
information.
Aone-lineheaderisassociatedwitheachmanualpage.Thisheaderconsistsofacommandname,the
sectionofthemanualinwhichthecommandisfound,andabriefdescriptionofwhatthecommanddoes.
Theseheadersarestoredinadatabasesothatyoucanperformquicksearchesonkeywordsassociated
witheachmanpage.
Arguments
Thesectionargumenttellsmantolimititssearchtothespecifiedsectionofthemanual(seepage30fora
listingofmanualsections).Withoutthisargumentmansearchesthesectionsinnumericalorderand
displaysthefirstmanpageitfinds.Inthesecondformofthemancommand,thekoptionsearchesforthe
keywordinthedatabaseofmanpageheaders;mandisplaysalistofheadersthatcontainthekeyword.A
mankcommandperformsthesamefunctionasapropos(page62).
Options
a
Displaysmanpagesforallsectionsofthemanual.Withoutthisoptionmandisplaysonly
thefirstpageitfinds.Usethisoptionwhenyouarenotsurewhichsectioncontainsthe
informationyouarelookingfor.
kkeyword
Displaysmanualpageheadersthatcontainthestringkeyword.Youcanscanthislistfor
commandsofinterest.Thisoptionisequivalenttotheaproposcommand(page62).
Kkeyword
Searchesforkeywordinallmanpages.Thisoptioncantakealongtimetorun.
Mpath
Searchesthedirectoriesinpathformanpages,wherepathisacolon-separatedlistof
directories.
tFormatsthepageforprintingonaPostScriptprinter.Theoutputgoestostandardoutput.
Discussion
Themanualpagesareorganizedinsections,eachpertainingtoaseparateaspectoftheLinuxsystem.
Section1containsuser-callablecommandsandisthesectionmostlikelytobeaccessedbyuserswhoare
notsystemadministratorsorprogrammers.Othersectionsofthemanualdescribesystemcalls,library
functions,andcommandsusedbysystemadministrators.Seepage30foralistingofthemanualsections.
Pager
Themanutilityuseslesstodisplaymanualpagesthatfillmorethanonescreen.Tochangetoanother
pager,settheenvironmentvariablePAGERtothepathnameofthepageryouwanttouse.Forexample,
addingthefollowinglinetothe~/.bash_profilefileallowsabashusertousemoreinsteadofless:
exportPAGER=/bin/more
MANPATH
YoucantellmanwheretolookformanpagesbysettingtheenvironmentvariableMANPATHtoa
colon-separatedlistofdirectories.Forexample,bashuserscanaddthefollowinglineto
~/.bash_profiletocausemantosearchthe/usr/man,/usr/local/man,and/usr/X11R6/mandirectories:
exportMANPATH=/usr/man:/usr/local/man:/usr/X11R6/man
Youcanedit/etc/man.configtofurtherconfigureman.Refertothemanmanpageformoreinformation.
Notes
Theargumenttomanisnotalwaysacommandname.Forexample,thecommandmanasciiliststhe
ASCIIcharactersandtheirvariousrepresentations;thecommandmankpostscriptlistsmanpagesthat
pertaintoPostScript.
Themanpagesarecommonlystoredinunformatted,compressedform.Whenyourequestamanpage,it
hastobedecompressedandformattedbeforebeingdisplayed.Tospeedupsubsequentrequestsforthat
manpage,manattemptstosavetheformattedversionofthepage.
Someutilitiesdescribedinthemanualpageshavethesamenameasshellbuiltincommands.Thebehavior
oftheshellbuiltinmaydifferslightlyfromthebehavioroftheutilityasdescribedinthemanualpage.
Examples
Thefollowingexampleusesmantodisplaythedocumentationforthecommandwrite,whichsends
messagestoanotheruser'sterminal:
$manwrite
WRITE(1)LinuxProgrammer'sManualWRITE(1)
NAME
write-sendamessagetoanotheruser
SYNOPSIS
writeuser[ttyname]
DESCRIPTION
Writeallowsyoutocommunicatewithotherusers,bycopy-
inglinesfromyourterminaltotheirs.
Whenyourunthewritecommand,theuseryouarewriting
...
Thenextexampledisplaysthemanpageforanothercommandthemancommanditself,agoodstarting
placeforsomeonelearningaboutthesystem:
$manman
man(1)man(1)
NAME
man-formatanddisplaytheonlinemanualpages
manpath-determineuserssearchpathformanpages
SYNOPSIS
man[-acdfFhkKtwW][--path][-msystem][-pstring][-C
config_file][-Mpathlist][-Ppager][-Ssection_list]
[section]name...
DESCRIPTION
manformatsanddisplaystheonlinemanualpages.Ifyou
specifysection,manonlylooksinthatsectionofthe
...
Thenextexampleshowshowyoucanusethemanutilitytofindthemanpagesthatpertaintoacertain
topic.Inthiscasemankdisplaysmanpageheaderscontainingthestringlatex.Theaproposutility(a
shellscriptstoredin/usr/bin/apropos)functionssimilarlytomank.
$man-klatex
Pod::LaTeX(3pm)-ConvertPoddatatoformattedLatex
einitex[elatex](1)-extendedTeX
elatex[latex](1)-structuredtextformattingand
typesetting
etex[elatex](1)-extendedTeX
evirtex[elatex](1)-extendedTeX
lambda[latex](1)-structuredtextformattingand
typesetting
latex(1)-structuredtextformattingand
typesetting
...
Thesearchforthekeywordenteredwiththekoptionisnotcasesensitive.Althoughthekeywordentered
onthecommandlineisalllowercase,itmatchesthefirstheader,whichcontainsthestringLaTeX
(uppercaseandlowercase).The3pmonthefirstlineindicatesthatthemanpageisfromSection3
(Subroutines)oftheLinuxSystemManualandcomesfromthePerlProgrammersReferenceGuide(itis
aPerlsubroutine;seewww.perl.orgformoreinformationonthePerlprogramminglanguage).
mkdir:Createsadirectory
mkdir[option]directory-list
Themkdirutilitycreatesoneormoredirectories.
Arguments
Thedirectory-listisalistofoneormorepathnamesofdirectoriesthatmkdircreates.
Options
Acceptsthecommonoptionsdescribedonpage587.
mode=mode mmode
Setsthepermissiontomode.Youcanrepresentthemodeabsolutely
byusinganoctalnumber(page605)orsymbolically(seeTableV-4
onpage604).
parents pCreatesanydirectoriesthatdonotexistinthepathtothedirectory
youwishtocreate.
verbose vDisplaysthenameofeachdirectorycreated.Thisoptionishelpful
whenusedwiththeparentsoption.
Notes
Youmusthavepermissiontowritetoandsearch(executepermission)theparentdirectoryofthe
directoryyouarecreating.Themkdirutilitycreatesdirectoriesthatcontainthestandardinvisible
entries(.and..).
Examples
Thefollowingcommandcreatestheaccountsdirectoryasasubdirectoryoftheworkingdirectoryandthe
prospectivedirectoryasasubdirectoryofaccounts:
$mkdir--parentsaccounts/prospective
Withoutchangingworkingdirectories,thesameusercreatesanothersubdirectorywithintheaccounts
directory:
$mkdiraccounts/existing
Nexttheuserchangestheworkingdirectorytotheaccountsdirectoryandcreatesonemoresubdirectory:
$cdaccounts
$mkdirclosed
Thelastexampleshowstheusercreatinganothersubdirectory.Thistimethemodeoptionremovesall
accesspermissionsforgroupandothers:
$mkdir--modego=accounts/past_due
mkfs:Createsafilesystemonadevice
mkfs[options]device
Themkfsutilitycreatesafilesystemonadevicesuchasafloppydisketteorapartitionofaharddisk.It
actsasafrontendforprogramsthatcreatefilesystems,eachspecifictoafilesystemtype.
caution:mkfsdestroysalldataonadevice
Becarefulwhenusingmkfs,asitdestroysalldataonadevice.
Arguments
Thedeviceisthenameofthedevicethatyouwanttocreatethefilesystemon.Ifthedevicenameisin
/etc/fstab,youcanusethemountpointofthedeviceinsteadofthedevicename.
Options
Whenyourunmkfs,youcanspecifybothglobaloptionsandoptionsspecifictothefilesystemtypethat
mkfsiscreating(forexample,ext2,ext3,msdos,reiserfs).Globaloptionsmustprecedetype-specific
options.
GlobalOptions
tfstype
(type)Thefstypeisthetypeoffilesystemyouwanttocreateforexample,ext2,ext3,
msdos,orreiserfs.ThedefaultfilesystemvariesbetweenLinuxdistributions.
V(verbose)Displaysmoreoutput,includingfile-specificinformation.
FilesystemType-SpecificOptions
Thefollowingoptionsapplytomanycommonfilesystemtypes,includingext2andext3.Thefollowing
commandliststhefilesystemcreationutilitiesavailableonthelocalsystem:
$ls/sbin/mkfs.*
/sbin/mkfs.cramfs/sbin/mkfs.ext3/sbin/mkfs.vfat
/sbin/mkfs.ext2/sbin/mkfs.msdos
Thereisfrequentlyalinkto/sbin/mkfs.ext2at/sbin/mke2fs.Reviewthemanpageorgivethepathname
ofthefilesystemcreationutilitytodeterminewhichoptionstheutilityaccepts.
$/sbin/mkfs.ext3
Usage:mkfs.ext3[-c|-t|-lfilename][-bblock-size][-ffragment-
size]
[-ibytes-per-inode][-j][-Jjournal-options][-Nnumber-of-
inodes]
[-mreserved-blocks-percentage][-ocreator-os][-gblocks-
per-group]
[-Lvolume-label][-Mlast-mounted-directory][-O
feature[,...]]
[-rfs-revision][-Roptions][-qvSV]device[blocks-count]
bsize
(block)Specifiesthesizeofblocksinbytes.Onext2andext3filesystemsvalidblock
sizesare1,024,2,048,and4,096bytes.
c(check)Checksforbadblocksonthedevicebeforecreatingafilesystem.Specifythis
optiontwicetoperformaslow,destructive,read-writetest.
Discussion
Beforeyoucanwritetoandreadfromaharddiskorfloppydisketteintheusualfashion,theremustbea
filesystemonit.Typicallyaharddiskisdividedintopartitions(page892),eachwithaseparate
filesystem.Afloppydiskettenormallyholdsasinglefilesystem.RefertoChapter4formoreinformation
onfilesystems.
Notes
Youcanusetune2fs(page808)withthejoptiontochangeanexistingext2filesystemintoa
journalingfilesystem(page883)oftypeext3.(See"Examples.")Youcanalsousetune2fstochange
howoftenfsck(page666)checksafilesystem.
mkfsisafrontend
Muchlikefsck,mkfsisafrontendthatcallsotherutilitiestohandlevarioustypesoffilesystems.For
example,mkfscallsmke2fs(whichistypicallylinkedtomkfs.ext2andmkfs.ext3)tocreate
thewidelyusedext2andext3filesystems.Refertothemke2fsmanpageformoreinformation.Other
utilitiesthatmkfscallsaretypicallynamedmkfs.type,wheretypeisthefilesystemtype.Bysplitting
mkfsinthismanner,filesystemdeveloperscanprovideprogramstocreatetheirfilesystemswithout
affectingthedevelopmentofotherfilesystemsorchanginghowsystemadministratorsusemkfs.
Examples
Inthefollowingexample,mkfscreatesafilesystemonthedeviceat/dev/hda8.Inthiscasethedefault
filesystemtypeisext2.
#/sbin/mkfs/dev/hda8
mke2fs1.35(28-Feb-2004)
max_blocks1309867008,rsv_groups=39974,rsv_gdb=312
Filesystemlabel=
OStype:Linux
Blocksize=4096(log=2)
Fragmentsize=4096(log=2)
640000inodes,1279167blocks
63958blocks(5.00%)reservedforthesuperuser
Firstdatablock=0
Maximumfilesystemblocks=1312817152
40blockgroups
32768blockspergroup,32768fragmentspergroup
16000inodespergroup
Superblockbackupsstoredonblocks:
32768,98304,163840,229376,294912,819200,884736
Writinginodetables:0/40...39/40...done
inode.i_blocks=19976,i_size=4243456
Writingsuperblocksandfilesystemaccountinginformation:done

Thisfilesystemwillbeautomaticallycheckedevery23mountsor
180days,whichevercomesfirst.Usetune2fs-cor-itooverride.
Nexttheadministratorusestune2fstoconverttheext2filesystemtoanext3journalingfilesystem:
#/sbin/tune2fs-j/dev/hda8
tune2fs1.35(28-Feb-2004)
Creatingjournalinode:done
Thisfilesystemwillbeautomaticallycheckedevery23mountsor
180days,whichevercomesfirst.Usetune2fs-cor-itooverride.
Mtools:UsesDOS-stylecommandsonfilesanddirectories
mcd[directory]
mcopy[options]file-listtarget
mdelfile-list
mdir[w]directory
mformat[options]device
mtype[options]file-list
TheseutilitiesmimicDOScommandsandmanipulateLinuxfilesorDOSfiles.Themcopyutility
providesaneasywaytomovefilesbetweenaLinuxfilesystemandaDOSdisk.Thedefaultdriveforall
commandsis/dev/fd0orA:.
Utilities
TableV-18listssomeoftheutilitiesintheMtoolscollection.
TableV-18.TheMtoolscollection

Utility Function
mcd ChangestheworkingdirectoryontheDOSdisk
mcopy CopiesDOSfilesfromonedirectorytoanother
mdel DeletesDOSfiles
mdir ListscontentsofDOSdirectories
mformat AddsDOSformattinginformationtoadisk
mtype DisplaysthecontentsofDOSfiles
Arguments
Thedirectory,usedwithmcdandmdir,mustbethenameofadirectoryonaDOSdisk.Thefile-list,
usedwithmcopyandmtype,isaSPACE-separatedlistoffilenames.Thetarget,usedwithmcopy,is
thenameofaregularfileoradirectory.Ifyougivemcopyafile-listwithmorethanonefilename,target
mustbethenameofadirectory.Thedevice,usedwithmformat,istheDOSdrivelettercontainingthe
disktobeformatted(forexample,A:).
Options
mcopy
nAutomaticallyreplacesexistingfileswithoutasking.Normallymcopyasksfor
verificationbeforeoverwritingafile.
p(preserve)Preservestheattributesoffileswhentheyarecopied.
s(recursive)Copiesdirectoriesandtheircontentsrecursively.
t
(text)ConvertsDOStextfilesforuseonaLinuxsystem,andviceversa.LinesinDOS
textfilesareterminatedwiththecharacterpairRETURN-NEWLINE;linesinLinuxtext
filesendinNEWLINE.ThisoptionremovestheRETURNcharacterwhilecopyingfrom
aDOSfileandaddsitwhencopyingfromaLinuxfile.
mdir
w
(wide)Displaysonlyfilenamesandfitsasmanyaspossibleoneachline.Bydefault
mdirlistsinformationabouteachfileonaseparateline,showingfilename,size,and
creationtime.
mformat
f1440
Specifiesa1,440K3.5-inchHDfloppydiskette.
f2880
Specifiesa2,880K3.5-inchEDfloppydiskette.
vvol
(label)PutsvolasthevolumelabelonthenewlyformattedDOSdisk.
mtype
t
(text)Similartothetoptionformcopy,thisoptionreplaceseachRETURN-
NEWLINEcharacterpairintheDOSfilewithasingleNEWLINEcharacterbefore
displayingthefile.
Discussion
AlthoughtheseutilitiesmimictheirDOScounterparts,theydonotattempttomatchthosetoolsexactly.In
mostcasesrestrictionsimposedbyDOSareremoved.Forexample,theasteriskambiguousfilereference
(*)matchesallfilenames(asitdoesunderLinux),includingthosefilenamesthatDOSwouldrequire*.*
tomatch.
Notes
Inthisdiscussion,thetermDOSdiskreferstoeitheraDOSpartitiononaharddiskoraDOSfloppy
diskette.
YoucandownloadMtoolsfromtheMtoolshomepage(mtools.linux.lu)orfromrpmfind.net.
IfthelocalkernelisconfiguredtosupportDOSfilesystems,youcanmountDOSdisksonaLinux
filesystemandmanipulatethefilesusingLinuxutilities.Althoughthisfeatureishandyandreducesthe
needforMtools,itmaynotbepracticalorefficienttomountandunmountDOSfilesystemseachtimeyou
needtoaccessaDOSfile.Thesetaskscanbetime-consuming,andsomesystemsaresetupsothat
regularuserscannotmountandunmountfilesystems.
UsecautionwhenusingMtools.Theseutilitiesmaynotwarnyouifyouareabouttooverwriteafile.
Usingexplicitpathnamesnotambiguousfilereferencesreducesthechanceofoverwritingafile.
ThemostcommonusesoftheMtoolsutilitiesaretoexaminefilesonDOSfloppydiskettes(mdir)andto
copyfilesbetweenaDOSfloppydisketteandtheLinuxfilesystem(mcopy).YoucanidentifyDOSdisks
byusingtheusualDOSdriveletters:A:forthefirstfloppydrive,C:forthefirstharddisk,andsoon.
YoucanseparatefilenamesinpathsbyusingeithertheLinuxforwardslash(/)ortheDOSbackslash(\).
Youneedtoescapebackslashestopreventtheshellfrominterpretingitbeforepassingthepathnametothe
utilityyouareusing.
EachoftheMtoolsutilitiesreturnsanexitcodeof0onsuccess,1oncompletefailure,and2onpartial
failure.
Examples
Inthefirstexample,mdirdisplaysthecontentsofaDOSfloppydiskettein/dev/fd0:
$mdir
VolumeindriveAisDOSUTY
DirectoryforA:/
ACADLIF4193705-10-051:29p
CADVANCELIF405602-08-0410:36a
CHIPTSTEXE22094-26-054:22p
DISKID3112-27-054:49p
GENERICLIF209832-08-0410:37a
INSTALLCOM8967-05-0510:23a
INSTALLDAT4527712-27-054:49p
KDINSTALEXE1105298-13-0510:50a
LOTUSLIF440991-18-053:36p
PCADLIF178465-01-053:46p
READIDEXE172615-07-058:26a
READMETXT98514-30-0510:32a
UTILITYLIF510695-05-059:13a
WORDLIF168177-01-059:58a
WPLIF579928-29-054:22p
15File(s)599040bytesfree
Thenextexampleusesmcopytocopythe*.TXTfilesfromtheDOSfloppydiskettetotheworking
directoryontheLinuxfilesystem.Becauseonlyonefilehastheextension.TXT,onlyonefileiscopied.
Because.TXTfilesareusuallytextfilesunderDOS,thetoptionstripsofftheunnecessaryRETURN
charactersattheendofeachline.Theambiguousfilereference*isescapedonthecommandlineto
preventtheshellfromattemptingtoexpanditbeforepassingtheargumenttomcopy.Themcopyutility
locatesthefileREADME.TXTwhengiventhepattern*.txtbecauseDOSdoesnotdifferentiatebetween
uppercaseandlowercaselettersinfilenames.
$mcopy-ta:\*.txt.
CopyingREADME.TXT
Finally,theDOSfloppydisketteisreformattedusingmformat,wipingalldatafromthediskette.Ifthe
diskettehasnotbeenlow-levelformatted,youneedtousefdformatbeforegivingthefollowing
commands:
$mformata:
Acheckwithmdirshowsthefloppydisketteisemptyafterformatting:
$mdira:
VolumeindriveAhasnolabel
DirectoryforA:/
File"*"notfound
mv:Renamesormovesafile
mv[options]existing-filenew-filename
mv[options]existing-file-listdirectory
mv[options]existing-directorynew-directory
Themvutility,whichrenamesormovesoneormorefiles,hasthreeformats.Thefirstrenamesasingle
filewithanewfilenamethatyousupply.Thesecondrenamesoneormorefilessothattheyappearina
specifieddirectory.Thethirdrenamesadirectory.Themvutilityphysicallymovesthefileifitisnot
possibletorenameit(thatis,ifyoumovethefilefromonefilesystemtoanother).
Arguments
Inthefirstform,theexisting-fileisapathnamethatspecifiestheordinaryfilethatyouwanttorename.
Thenew-filenameisthenewpathnameofthefile.
Inthesecondform,theexisting-file-listisalistofthepathnamesofthefilesthatyouwanttorenameand
thedirectoryspecifiesthenewparentdirectoryforthefiles.Thefilesyourenamewillhavethesame
simplefilenamesaseachofthefilesintheexisting-file-listbutnewabsolutepathnames.
Thethirdformrenamestheexisting-directorywiththenew-directoryname.Thisformworksonlywhen
thenew-directorydoesnotalreadyexist.
Options
Acceptsthecommonoptionsdescribedonpage587.
backup bMakesabackupcopy(byappending~tothefilename)ofanyfilethat
wouldbeoverwritten.
force f
Causesmvnottopromptyouifamovewouldoverwriteanexisting
filethatyoudonothavewritepermissionfor.Youmusthavewrite
permissionforthedirectoryholdingthetargetfile.
interactive i
Promptsyouforconfirmationifmvwouldoverwriteafile.Ifyour
responsebeginswithayorY,mvoverwritesthefile;otherwise,mv
doesnotmovethefile.
update u
Ifamovewouldoverwriteanexistingfile,notadirectory,thisoption
causesmvtocomparethemodificationtimesofthesourceandtarget
files.Ifthetargetfilehasamorerecentmodificationtime(thetargetis
newerthanthesource),mvdoesnotreplaceit.
verbose vListsfilesastheyaremoved.
Notes
GNUmvisimplementedascp(withtheaoption)andrm.Whenyouexecutethemvutility,itfirstcopies
theexisting-filetothenew-file.Itthendeletestheexisting-file.Ifthenew-filealreadyexists,mvmay
deleteitbeforecopying.
Aswithrm,youmusthavewriteandexecuteaccesspermissiontotheparentdirectoryoftheexisting-
file,butyoudonotneedreadorwriteaccesspermissiontothefileitself.Ifthemovewouldoverwritea
filethatyoudonothavewritepermissionfor,mvdisplaysthefile'saccesspermissionsandwaitsfora
response.IfyouenteryorY,mvoverwritesthefile;otherwise,itdoesnotmovethefile.Ifyouusethef
option,mvdoesnotpromptyouforaresponsebutsimplyoverwritesthefile.
Althoughearlierversionsofmvcouldmoveonlyordinaryfilesbetweenfilesystems,mvcannowmove
anytypeoffile,includingdirectoriesanddevicefiles.
Examples
Thefirstcommandrenamesletter,afileintheworkingdirectory,asletter.1201:
$mvletterletter.1201
Thenextcommandrenamesthefilesothatitappears,withthesamesimplefilename,intheuser's
~/archivesdirectory:
$mvletter.1201~/archives
Thefollowingcommandmovesallfilesintheworkingdirectorywhosenamesbeginwithmemosothey
appearinthe/p04/backupdirectory:
$mvmemo*/p04/backup
Usingtheuoptionpreventsmvfromreplacinganewerfilewithanolderone.Afterthemvucommand
shownbelow,thenewerfile,memo2,hasnotbeenoverwritten.Themvcommandwithouttheuoption
overwritesthenewerfile(memo2'smodificationtimeandsizehavechangedtothoseofmemo1).
$ls-l
-rw-rw-r--1samsam22Mar2523:34memo1
-rw-rw-r--1samsam19Mar2523:40memo2
$mv-umemo1memo2
$ls-l
-rw-rw-r--1samsam22Mar2523:34memo1
-rw-rw-r--1samsam19Mar2523:40memo2
$mvmemo1memo2
$ls-l
-rw-rw-r--1samsam22Mar2523:34memo2
nice:Changesthepriorityofacommand
nice[option][command-line]
Theniceutilityreportsthepriorityoftheshelloraltersthepriorityofacommand.Anordinaryusercan
decreasethepriorityofacommand.OnlySuperusercanincreasethepriorityofacommand.TheTC
Shellhasanicebuiltinthathasadifferentsyntax.Referto"Notes"formoreinformation.
Arguments
Thecommand-lineisthecommandlineyouwanttoexecuteatadifferentpriority.Withoutanyoptionsor
arguments,nicedisplaysthepriorityoftheshellrunningnice.
Options
Withoutanoption,nicedefaultstoanadjustmentof10,loweringthepriorityofthecommandby
10typicallyfrom0to10.Asyouraisethepriorityvalue,thecommandrunsatalowerpriority.
adjustment=value
nvalue
Changestheprioritybytheincrement(ordecrement)specifiedbyvalue.Therangeof
prioritiesisfrom20(thehighestpriority)to19(thelowestpriority).Apositivevalue
lowersthepriority,whereasanegativevalueraisesthepriority.OnlySuperusercan
specifyanegativevalue.Whenyouspecifyavalueoutsidethisrange,thepriorityisset
tothelimitoftherange.
Notes
Youcanusetop'srcommand(page799)tochangethepriorityofarunningprocess.
Higher(morepositive)priorityvaluesmeanthatthekernelschedulesajoblessoften.Lower(more
negative)valuescausethejobtobescheduledmoreoften.
WhenSuperuserschedulesajobtorunatthehighestpriority,thischangecanaffecttheperformanceofthe
systemforallotherjobs,includingtheoperatingsystemitself.Forthisreasonyoushouldbecarefulwhen
usingnicewithnegativevalues.
TheTCShellhasanicebuiltin.Undertcsh,usethefollowingsyntaxtochangethepriorityatwhich
command-lineisrun.Thedefaultpriorityis4.Youmustincludetheplussignforpositivevalues.
nice[±value]commandline
Examples
Thefollowingcommandexecutesfindinthebackgroundatthelowestpossiblepriority.Thepsl
commanddisplaysthenicevalueofthecommandintheNIcolumn:
#nice-n19find/-namecore-print>corefiles.out&
[1]2610
#ps-l
FSUIDPIDPPIDCPRINIADDRSZWCHANTTY
TIMECMD
100S0109910970750-605wait4pts/0
00:00:00bash
100R02610109909919-634-pts/0
00:00:03find
100R0261110990760-747-pts/0
00:00:00ps
Thenextcommandfindsverylargefilesandrunsatahighpriority(15):
#nice-n-15find/-size+50000k
nohup:Runsacommandthatkeepsrunningafteryoulogout
nohupcommandline
Thenohuputilityexecutesacommandlinesuchthatthecommandkeepsrunningafteryoulogout.In
otherwords,nohupcausesaprocesstoignoreaSIGHUPsignal.Dependingonhowtheshellis
configured,itmaykillyourbackgroundprocesseswhenyoulogout.TheTCShellhasanohupbuiltin.
Referto"Notes"formoreinformation.
Arguments
Thecommandlineisthecommandlineyouwanttoexecute.
Notes
Acceptsthecommonoptionsdescribedonpage587.
Ifyoudonotredirecttheoutputfromacommandthatyouexecuteusingnohup,bothstandardoutputand
standarderroraresenttothefilenamednohup.outintheworkingdirectory.Ifyoudonothavewrite
permissionfortheworkingdirectory,nohupsendsoutputto~/nohup.out.
Unlikethenohuputility,theTCShell'snohupbuiltindoesnotsendoutputtonohup.out.Background
jobsstartedfromtcshcontinuetorunafteryoulogout.
Examples
Thefollowingcommandexecutesfindinthebackground,usingnohup:
$nohupfind/-namecore-print>corefiles.out&
[1]14235
od:Dumpsthecontentsofafile
od[options][file-list]
Theod(octaldump)utilitydumpsthecontentsofafile.Thedumpisusefulforviewingexecutable
(object)filesandtextfileswithembeddednonprintingcharacters.Thisutilitytakesitsinputfromthefile
youspecifyonthecommandlineorfromstandardinput.
Arguments
Thefile-listspecifiesthepathnamesofthefilesthatoddisplays.Whenyoudonotspecifyafile-list,od
readsfromstandardinput.
Options
Acceptsthecommonoptionsdescribedonpage587.
addressradix=base
Abase
Specifiesthebaseusedwhendisplayingtheoffsetsshownfor
positionsinthefile.Bydefaultoffsetsaregiveninoctal.Possible
valuesforbaseared(decimal),o(octal),x(hexadecimal),andn(no
offsetsprinted).
skip-bytes=njn
Skipsnbytesbeforedisplayingdata.
read-bytes=nNn

Readsamaximumofnbytesandquits.
strings=nsn
Outputsfromthefileonlythosebytesthatcontainrunsofnormore
printableASCIIcharactersthatareterminatedbyaNULLbyte.The
defaultvaluefornis3.
format=type[n]
ttype[n]
Specifiestheoutputformattousewhendisplayingdatafromafile.
Youcanrepeatthisoptionwithdifferentformattypestoseethefile
inseveraldifferentformats.TableV-19liststhepossiblevaluesfor
type.
Bydefaultoddumpsafileas2-byteoctalnumbers.Youcanspecify
thenumberofbytesodusestocomposeeachnumberbyspecifying
alengthindicator,n.Youcanspecifyalengthindicatorforalltypes
exceptaandc.TableV-21liststhepossiblevaluesofn.
TableV-19.Outputformats
type Typeofoutput
aNamedcharacter.Displaysnonprintingcontrolcharactersusingtheirofficial
ASCIInames.Forexample,FORMFEEDisdisplayedasff.
cASCIIcharacter.Displaysnonprintingcontrolcharactersasbackslash
escapesequences(TableV-20)orthree-digitoctalnumbers.
dSigneddecimal.
fFloatingpoint.
oOctal(default).
uUnsigneddecimal.
xHexadecimal.
TableV-21.Lengthindicators

nNumberofbytestouse
Integers(typesd,o,u,andx)
C(character) Usessinglecharactersforeachdecimalvalue
S(shortinteger) Uses2bytes
I(integer) Uses4bytes
L(long) Uses4byteson32-bitmachinesand8byteson64-bitmachines
Floatingpoint(typef)
F(float) Uses4bytes
D(double) Uses8bytes
L(longdouble) Typicallyuses8bytes
TableV-20.Outputformattypecbackslashescapesequences
Sequence Meaning
\0 NULL
\a BELL
\b BACKSPACE
\f FORMFEED
\n NEWLINE
\r RETURN
\t HORIZONTALTAB
\v VERTICALTAB

Notes
Toretainbackwardcompatibilitywitholder,non-POSIXversionsofod,theodutilityincludesthe
optionslistedinTableV-22asshorthandversionsofmanyoftheprecedingoptions.
TableV-22.Shorthandformatspecifications
Shorthand Equivalentspecification
ata
btoC
c tc
d tu2
ftfF
htx2
itd2
l td4
o to2
xtx2
Examples
Thefileac,usedinthefollowingexamples,containsalltheASCIIcharacters.Inthefirstexample,the
bytesinthisfilearedisplayedasnamedcharacters.Thefirstcolumnshowstheoffsetofeachbytefrom
thestartofthefile.Theoffsetsaregivenasoctalvalues.
$od-taac
0000000nulsohstxetxeotenqackbelbshtnlvtffcrsosi
0000020dledc1dc2dc3dc4naksynetbcanemsubescfsgsrsus
0000040sp!"#$%&'()*+,-./
00000600123456789:;<=>?
0000100@ABCDEFGHIJKLMNO
0000120PQRSTUVWXYZ[\]^_
0000140`abcdefghijklmno
0000160pqrstuvwxyz{|}~del
0000200nulsohstxetxeotenqackbelbshtnlvtffcrsosi
0000220dledc1dc2dc3dc4naksynetbcanemsubescfsgsrsus
0000240sp!"#$%&'()*+,-./
00002600123456789:;<=>?
0000300@ABCDEFGHIJKLMNO
0000320PQRSTUVWXYZ[\]^_
0000340`abcdefghijklmno
0000360pqrstuvwxyz{|}~del
0000400nl
0000401
Inthenextexample,thebytesaredisplayedasoctalnumbers,ASCIIcharacters,orprintingcharacters
precededbyabackslash(refertoTableV-20onpage738):
$od-tcac
0000000\0001002003004005006\a\b\t\n\v\f\r016017
0000020020021022023024025026027030031032033034035036
037
0000040!"#$%&'()*+,-./
00000600123456789:;<=>?
0000100@ABCDEFGHIJKLMNO
0000120PQRSTUVWXYZ[\]^_
0000140`abcdefghijklmno
0000160pqrstuvwxyz{|}~177
0000200200201202203204205206207210211212213214215216
217
0000220220221222223224225226227230231232233234235236
237
0000240240241242243244245246247250251252253254255256
257
0000260260261262263264265266267270271272273274275276
277
0000300300301302303304305306307310311312313314315316
317
0000320320321322323324325326327330331332333334335336
337
0000340340341342343344345346347350351352353354355356
357
0000360360361362363364365366367370371372373374375376
377
0000400\n
0000401
Thefinalexamplefindsinthefile/usr/bin/whoallstringsthatareatleastthreecharacterslong(the
default)andterminatedbyanullbyte.Seestringsonpage777foranotherwayofdisplayingasimilar
list.Theoffsetpositionsaregivenasdecimaloffsetsinsteadofoctaloffsets.
$$od-Ad--strings/usr/bin/who
...
0015170JosephArceneaux
0015187MichaelStone
0015201DavidMacKenzie
00152175.2.1
0015223who
0015227toomanyarguments
0015568%-8.8s%s%-12s%-12s%s%s%-8s%s
0016840Warning:-iwillberemovedinafuturerelease;use-u
instead
0016906writeerror
0016918%s:%s
0016925literal
0016933shell
0016939shell-always
0016952escape
0016959clocale
0017708Copyright(C)2004FreeSoftwareFoundation,Inc.
0018352memoryexhausted
...
paste:Joinscorrespondinglinesfromfiles
paste[option][file-list]
Thepasteutilityreadslinesfromthefile-listandjoinscorrespondinglinesinitsoutput.Bydefault
outputlinesareseparatedbyaTABcharacter.
Arguments
Thefile-listisalistofordinaryfiles.Whenyouomitthefile-list,pastereadsfromstandardinput.
Options
Acceptsthecommonoptionsdescribedonpage587.
delimiter=dlist
ddlist
Thedlistisalistofcharacterstobeusedtoseparateoutputfields.Ifdlist
containsasinglecharacter,pasteusesthatcharacterinsteadofthedefault
TABcharactertoseparatefields.Ifdlistcontainsmorethanonecharacter,the
charactersareusedinturntoseparateoutputlinesandarethenreusedfromthe
beginningofthelistasnecessary.
serial sProcessesonefileatatime;pasteshorizontally.See"Examples."
Notes
Acommonuseofpasteistorearrangethecolumnsofatable.Autility,suchascut,canplacethe
desiredcolumnsinseparatefiles,andthenpastecanjointheminanyorder.
Examples
Thefollowingexampleusesthefilesfnamesandacctinfo.Thesefilescaneasilybecreatedbyusing
cut(page627)andthe/etc/passwdfile.Thepastecommandputsthefull-namefieldfirst,followed
bytheremaininguseraccountinformation.ATABcharacterseparatesthetwooutputfields.
$catfnames
JennyChen
AlexWatson
ScottAdams
HelenSimpson
$catacctinfo
jenny:x:401:50:/home/jenny:/bin/zsh
alex:x:402:50:/home/alex:/bin/bash
scott:x:504:500:/home/scott:/bin/tcsh
hls:x:505:500:/home/hls:/bin/bash
$pastefnamesacctinfo
JennyChenjenny:x:401:50:/home/jenny:/bin/zsh
AlexWatsonalex:x:402:50:/home/alex:/bin/bash
ScottAdamsscott:x:504:500:/home/scott:/bin/tcsh
HelenSimpsonhls:x:505:500:/home/hls:/bin/bash
Thenextexamplesusethefilesp1,p2,p3,andp4.Thelastexampleinthisgroupusesthedelimiter
optiontogivepastealistofcharacterstousetoseparateoutputfields:
$catp1
1
one
ONE
$catp2
2
two
TWO
extra
$catp3
3
three
THREE
$catp4
4
four
FOUR
$pastep4p3p2p1
4321
fourthreetwoone
FOURTHREETWOONE
extra
$paste--delimiter="+-="p3p2p1p4
3+2-1=4
three+two-one=four
THREE+TWO-ONE=FOUR
+extra-=
Thefinalexampleusestheserialoptiontopastethefilesoneatatime:
$paste--serialp1p2p3p4
1oneONE
2twoTWOextra
3threeTHREE
4fourFOUR
pr:Paginatesfilesforprinting
pr[options][file-list]
Theprutilitybreaksfilesintopages,usuallyinpreparationforprinting.Eachpagehasaheaderwiththe
nameofthefile,date,time,andpagenumber.
Theprutilitytakesitsinputfromfilesyouspecifyonthecommandlineorfromstandardinput.The
outputfromprgoestostandardoutputandisfrequentlyredirectedbyapipetoaprinter.
Arguments
Thefile-listisalistofthepathnamesoftextfilesthatyouwantprtopaginate.Whenyouomitthefile-
list,prreadsfromstandardinput.
Options
Acceptsthecommonoptionsdescribedonpage587.
Youcanembedoptionswithinthefile-list.Anembeddedoptionaffectsonlythosefilesfollowingiton
thecommandline.
show-control-chars
cDisplayscontrolcharacterswithacaret(^;forexample,^H).Displays
othernonprintingcharactersasoctalnumbersprecededbyabackslash.
columns=col col
Displaysoutputincolcolumnswithadefaultofone.Thisoptionmay
truncatelinesandcannotbeusedwiththemergeoption.
double-space dDouble-spacestheoutput.
form-feed fUsesaFORMFEEDcharactertoskiptothenextpageratherthanfilling
thecurrentpagewithNEWLINEcharacters.
header=head hhead
Displaysheadatthetopofeachpageinsteadofthefilename.Ifhead
containsSPACEs,youmustencloseitwithinquotationmarks.
length=lines llines
Setsthepagelengthtolineslines.Thedefaultis66lines.
merge mDisplaysallspecifiedfilessimultaneouslyinmultiplecolumns.Thisoption
cannotbeusedwithcolumns.
number-lines=[c[num]]
n[c[num]]
Numbersthelinesofoutput.Thecisacharacter
thatprappendstothenumbertoseparateitfrom
thecontentsofthefile(thedefaultisaTAB).The
numspecifiesthenumberofdigitsineachline
number(thedefaultis5).
indent=spaces ospaces
Indentstheoutputbyspacescharacters(specifies
theleftmargin).
separator=cs[c]
Separatescolumnswiththesinglecharacterc
(defaultstoTABwhenyouomitc).Bydefaultpr
usesTABsasseparationcharacterstoaligncolumns
unlessyouusethewoption,inwhichcasenothing
separatescolumns.
omit-header t
Causesprnottodisplayitsfive-linepageheaderand
trailer.Theheaderthatprnormallydisplaysincludes
thenameofthefile,thedate,time,andpagenumber.
Thetrailerisfiveblanklines.
width=num wnum
Setsthepagewidthtonumcolumns.Thisoptionis
effectiveonlywithmulticolumnoutput(themerge
orcolumnsoption).
firstpage[:lastpage]
+firstpage[:lastpage]
Outputbeginswiththepagenumberedfirstpageandends
withlastpage.Withoutlastpage,proutputsthroughthe
lastpageofthedocument.Theshortversionofthis
optionbeginswithaplussign,notahyphen.
Notes
Whenyouusethecolumnsoptiontodisplaytheoutputinmultiplecolumns,prdisplaysthesamenumber
oflinesineachcolumn(withthepossibleexceptionofthelast).
Examples
Thefirstcommandshowsprpaginatingafilenamedmemoandsendingitsoutputthroughapipetolpr
forprinting:
$prmemo|lpr
Nowmemoissenttotheprinteragain,thistimewithaspecialheadingatthetopofeachpage.Thejobis
runinthebackground.
$pr-h'MEMORE:BOOK'memo|lpr&
[1]4904
Nextprdisplaysthememofileonthescreen,withoutanyheader,startingwithpage3:
$pr-t+3memo
...
ps:Displaysprocessstatus
ps[options][process-list]
Thepsutilitydisplaysstatusinformationaboutprocessesrunningonthelocalsystem.
Arguments
Theprocess-listisacomma-orSPACE-separatedlistofPIDnumbers.Whenyouspecifyaprocess-list,
psreportsonjusttheprocessesinthatlist.
Options
Thepsutilityacceptsthreetypesofoptions,eachprecededbyadifferentprefix.Youcanintermixthe
options.
Twohyphens: GNU(long)options
Onehyphen: UNIX98(short)options
Nohyphens: BSDoptions
A(all)Reportsonallprocesses.Alsoe.
e(everything)Reportsonallprocesses.AlsoA.
f(full)Displaysalistingwithmorecolumnsofinformation.
forest Displaystheprocesstree.
l
(long)Producesalonglistingshowingmoreinformationabouteach
process.Seethe"Discussion"sectionforadescriptionofallthe
columnsthatthisoptiondisplays.
no-headers Omitstheheader.Thisoptionisusefulifyouaresendingtheoutput
toanotherprogramforfurtherprocessing.
u
(user-oriented)Addstothedisplaytheusernameoftheuser
runningtheprocess,thetimetheprocesswasstarted,thepercentage
ofCPUandmemorytheprocessisusing,andotherinformation.
User=username
Reportsonprocessesbeingrunbyusername,whichcanbethenameor
UIDofauseronthelocalsystem.

w
(wide)Withoutthisoptionpstruncatesoutputlinesattherightsideofthe
screen.Thisoptionextendsthedisplaysoitwrapsaroundonemoreline,if
needed.
Discussion
Withoutanyoptions,psdisplaysthestatusesofallactiveprocessesthatyourterminal/screencontrols.
TableV-23liststheheadingandcontentofeachofthefourcolumnsthatpsdisplays.
TableV-23.ColumnheadingsI
Heading Meaning
PID Theprocessidentificationnumber.
TTY(terminal) Thenameoftheterminalthatcontrolstheprocess.
TIME Thenumberofhours,minutes,andsecondstheprocesshas
beenrunning.
CMD
Thecommandlinetheprocesswascalledwith.The
commandistruncatedtofitononeline.Usethewoptionto
seemoreofthecommandline.
Thecolumnsthatpsdisplaysdependonyourchoiceofoptions.TableV-24liststheheadingsand
contentsofthemostcommoncolumns.
TableV-24.ColumnheadingsII
Thecolumntitlesdiffer,dependingonthetypeofoptionyouuse.Thistableshowsthe
headingsforUNIX98(one-hyphen)options.
Heading Meaning
%CPU
ThepercentageoftotalCPUtimethattheprocessisusing.
OwingtothewaythatLinuxhandlesprocessaccounting,this
figureisapproximate,andthetotalof%CPUvaluesforall
processesmayexceed100%.
%MEM(memory) ThepercentageofRAMthattheprocessisusing.
COMMANDorCMD
Thecommandlinetheprocesswascalledwith.The
commandistruncatedtofitononeline.Usethewoptionto

seemoreofthecommandline.Thiscolumnisalways
displayedlastonaline.
F(flags) Theflagsassociatedwiththeprocess.
PID Theprocessidentificationnumber.
PPID(parentPID) Theprocessidentificationnumberoftheparentprocess.
PRI(priority) Thepriorityoftheprocess.
RSS(residentsetsize) Thenumberofblocksofmemorythattheprocessisusing.
SIZEorSZ Thesize,inblocks,ofthecoreimageoftheprocess.
STIMEorSTART Thedatetheprocessstarted.
STATorS(status) Thestatusoftheprocessasspecifiedbyoneormoreletters
fromthefollowinglist:
<Highpriority
DSleepingandcannotbeinterrupted
LPageslockedinmemory(real-timeandcustomI/O)
NLowpriority
RAvailableforexecution(intherunqueue)
SSleeping
TEitherstoppedorbeingtraced
WHasnopagesresidentinRAM
XDead
ZZombieprocessthatiswaitingforitschildprocesses
toterminatebeforeitterminates
TIME Thenumberofminutesandsecondsthattheprocesshas
beenrunning.
TTY(terminal) Thenameoftheterminalcontrollingtheprocess.
USERorUID Theusernameoftheuserwhoownstheprocess.

WCHAN(waitchannel)
Iftheprocessiswaitingforanevent,theaddressofthe
kernelfunctionthatcausedtheprocesstowait.Itis0for
processesthatarenotwaitingorsleeping.
Notes
Usetop(page798)todisplayprocessstatusinformationdynamically.
Examples
Thefirstexampleshowsps,withoutanyoptions,displayingtheuser'sactiveprocesses.Thefirstprocess
istheshell(bash),andthesecondistheprocessexecutingthepsutility.
$ps
PIDTTYTIMECMD
2697pts/000:00:02bash
3299pts/000:00:00ps
Withthel(long)option,psdisplaysmoreinformationabouttheprocesses:
$ps-l
FSUIDPIDPPIDCPRINIADDRSZWCHANTTY
TIMECMD
000S500269726960750-639wait4pts/0
00:00:02bash
000R500330026970760-744-pts/0
00:00:00ps
Theuoptionshowsvarioustypesofinformationabouttheprocesses,includinghowmuchofthelocal
systemCPUandmemoryeachoneisusing:
$ps-u
USERPID%CPU%MEMVSZRSSTTYSTATSTARTTIME
COMMAND
alex26970.00.525561460pts/0SJul310:02-bash
alex33030.00.22476616pts/0RJul310:00ps-u
Theforestoptioncausespstodisplaywhatthemanpagedescribesasan"ASCIIartprocesstree."
Processesthatarechildrenofotherprocessesappearindentedundertheirparents,makingtheprocess
hierarchy,ortree,easiertosee.
$ps-ef--forest
UIDPIDPPIDCSTIMETTYTIMECMD
root100Jul22?00:00:03init
root210Jul22?00:00:00[keventd]
...
root78510Jul22?00:00:00/usr/sbin/apmd-p10
-w5-W-P
root83910Jul22?00:00:01/usr/sbin/sshd
root33058390Aug01?00:00:00\_/usr/sbin/sshd
alex330733050Aug01?00:00:00\_
/usr/sbin/sshd
alex330833070Aug01pts/100:00:00\_-bash
alex377433080Aug01pts/100:00:00\_ps-
ef--forest
...
root104010Jul22?00:00:00login--root
root335110400Aug01tty200:00:00\_-bash
root340233510Aug01tty200:00:00\_makemodules
root341634020Aug01tty200:00:00\_make-C
driversCFLA
root376434160Aug01tty200:00:00\_make
-Cscsimod
root377337640Aug01tty200:00:00\_
ld-melf_i3
psandkill
ThenextsequenceofcommandsshowshowtousepstodeterminethePIDnumberofaprocessrunning
inthebackgroundandhowtoterminatethatprocessbyusingthekillcommand.Inthiscaseitisnot
necessarytousepsbecausetheshelldisplaysthePIDnumberofthebackgroundprocesses.Theps
utilityverifiesthePIDnumber.
Thefirstcommandexecutesfindinthebackground.TheshelldisplaysthejobandPIDnumbersofthe
process,followedbyaprompt.
$find~-namememo-print>memo.out&
[1]3343
NextpsconfirmsthePIDnumberofthebackgroundtask.Ifyoudidnotalreadyknowthisnumber,using
pswouldbetheonlywaytofinditout.
$ps
PIDTTYTIMECMD
3308pts/100:00:00bash
3343pts/100:00:00find
3344pts/100:00:00ps
Finallykill(page693)terminatestheprocess:
$kill3343
$RETURN
[1]+Terminatedfind~-namememo-print>memo.out
$
rcp:Copiesoneormorefilestoorfromaremotesystem
rcp[options]source-filedestination-file
rcp[options]source-file-listdestination-directory
Thercputilitycopiesoneormoreordinaryfilesbetweentwosystemsthatcancommunicateovera
network.
security:rcpisnotsecure
Thercputilityuseshost-basedtrust,whichisnotsecure,toauthorizefilestobecopied.
Usescp(page758)whenitisavailable.
Arguments
Thesource-file,source-file-list,anddestination-filearepathnamesoftheordinaryfiles,andthe
destination-directoryisthepathnameofadirectoryfile.Apathnamethatdoesnotcontainacolon(:)is
thenameofafileonthelocalsystem.Apathnameoftheformname@host:pathnamesafileonthe
remotesystemnamedhost.Thepathisrelativetothehomedirectoryoftheusername(unlesspathisan
absolutepathname).Whenyouomitthename@portionofthedestination,arelativepathnameisrelative
tothehomedirectoryonthehostoftheusergivingthercpcommand.
Likecp,rcphastwomodesofoperation:Thefirstcopiesonefiletoanother,andthesecondcopiesone
ormorefilestoadirectory.Thesource-file[-list]isalistofthename(s)ofthefile(s)thatrcpwill
copy;destination-fileisthenamethatrcpassignstotheresultingcopyofthefile,ordestination-
directoryisthenameofthedirectorythatrcpputsthecopiedfilesin.Whenrcpcopiesfilestoa
destination-directory,thefilesmaintaintheiroriginalsimplefilenames.
Options
p
(preserve)Setsthemodificationtimesandfileaccesspermissionsofeachcopyto
matchthoseofthesource-file.Whenyoudonotusep,rcpusesthefile-creationmask
(umask;seepage810)ontheremotesystemtomodifytheaccesspermissions.
r
(recursive)Whenafileinthesource-file-listisadirectory,copiesthecontentsofthat
directoryandanysubdirectoriesintothedestination-directory.Youcanusethisoption
onlywhenthedestinationisadirectory.
Notes
Youmusthaveanaccountontheremotesystemtocopyfilestoorfromitusingrcp.Thercputilitydoes
notpromptforapasswordbutusesseveralalternativemethodstoverifythatyouhavetheauthorityto
readorwritefilesontheremotesystem.
Onemethodrequiresthatthenameofthelocalsystembespecifiedinthe/etc/hosts.equivfileonthe
remotesystem.Ifthenameisthere,rcpallowsyoutocopyfilesifyourusernamesarethesameonboth
systemsandyouraccountontheremotesystemhasthenecessarypermissionstoaccessfilesthere.
Authorizationcanalsobespecifiedonaper-userbasis.Usingthismethodtheremoteuser'shome
directorymustcontainafilenamed~/.rhoststhatliststrustedremotesystemsandusers.Withthismethod,
yourlocalandremoteusernamesdonothavetomatchbutyourlocalusernamemustappearonthelinein
theremote~/.rhostsfilethatstartswiththenameofthelocalsystem.See"Examples"forrlogin(page
752)forasample.rhostsfile.
Ifyouuseawildcard(suchas*)inaremotepathname,youmustquotethewildcardcharacteror
pathnamesothatthewildcardisinterpretedbytheshellontheremotesystemandnotbythelocalshell.
Aswithcp,ifthedestination-fileexistsbeforeyouexecutercp,rcpoverwritesthefile.
Examples
Thefirstexamplecopiesthefileswithfilenamesendingin.cintothearchivesdirectoryontheremote
systemnamedbravo.Becauseausernameisnotspecified,rcpusesthelocaluser'susernameonthe
remotesystem.Becausethefullpathnameofthearchivesdirectoryisnotspecified,rcpassumesthatit
isasubdirectoryoftheuser'shomedirectoryonbravo.Eachofthecopiedfilesretainsitssimple
filename.
$rcp*.cbravo:archives
Thenextexamplecopiesmemofromthe/home/jennydirectoryonbravototheworkingdirectoryonthe
localsystem:
$rcpbravo:/home/jenny/memo.
Nextrcpcopiesthefilesnamedmemo.newandlettertoJenny'shomedirectoryontheremotesystem
bravo.Theabsolutepathnamesofthecopiedfilesonbravoare/home/jenny/memo.newand
/home/jenny/letter:
$rcpmemo.newletterbravo:/home/jenny
ThefinalcommandcopiesallthefilesinJenny'sreportsdirectoryonbravototheoldreportsdirectory
onthelocalsystem,preservingtheoriginalmodificationdatesandfileaccesspermissionsonthecopies:
$rcp-p'bravo:reports/*'oldreports
rlogin:Logsinonaremotesystem
rlogin[option]remote-system
Therloginutilityestablishesaloginsessiononaremotesystemoveranetwork.
security:rloginisnotsecure
Therloginutilityuseshost-basedtrust,whichisnotsecure,toauthorizeyourlogin.
Alternatively,itsendsyourpasswordoverthenetworkascleartext,whichisnotasecure
practice.Usessh(page773)whenitisavailable.
Arguments
Theremote-systemisthenameofasystemthatthelocalsystemcanreachoveranetwork.
Options
lusername (login)Logsyouinontheremotesystemastheuserspecifiedby
username.
Notes
Ifthefilenamed/etc/hosts.equivlocatedontheremotesystemspecifiesthenameofthelocalsystem,the
remotesystemwillnotpromptyoutoenteryourpassword.Systemsthatarelistedinthe/etc/hosts.equiv
fileareconsideredassecureasthelocalsystem.
Analternativewaytospecifyatrustedrelationshipisonaper-userbasis.Eachuser'shomedirectorycan
containafilenamed~/.rhoststhatholdsalistoftrustedremotesystemsandusers.See"Examples"fora
sample.rhostsfile.
Examples
Thefollowingexampleillustratestheuseofrlogin.Onthelocalsystem,Alex'susernameisalex;on
theremotesystembravo,hisusernameiswatson.TheremotesystempromptsAlextoenterapassword
becauseheislogginginusingausernamedifferentfromtheoneheusesonthelocalsystem.
$whoami
alextty06Oct1413:26
$rlogin-lwatsonbravo
Password:
~/.rhostsfile
Ifthelocalsystemisnamedhurrah,thefollowing.rhostsfileonbravoallowstheuseralextologinas
theuserwatsonwithoutenteringapassword:
$cat/home/watson/.rhosts
hurrahalex
rm:Removesafile(deletesalink)
rm[options]file-list
Thermutilityremoveshardand/orsymboliclinkstooneormorefiles.Whenyouremovethelasthard
linktoafile,thefileisdeleted.
caution:Becarefulwhenyouusermwithwildcards
Becauseyoucanremovealargenumberoffileswithasinglecommand,usermcautiously,
especiallywhenyouareworkingwithambiguousfilereferences.Ifyouhavedoubtsabout
theeffectofanrmcommandwithanambiguousfilereference,firstuseechowiththe
samefilereferenceandevaluatethelistoffilesthereferencegenerates.Alternatively,you
canusetheinteractiveoption.
Arguments
Thefile-listisalistofthelistoffilesthatrmdeletes.
Options
Acceptsthecommonoptionsdescribedonpage587.
force f
Withoutaskingforyourconsent,removesfilesforwhich
youdonothavewriteaccesspermission.Thisoptionalso
suppressesinformativeoutputifafiledoesnotexist.
interactive i
Asksbeforeremovingeachfile.Ifyouuserecursivewith
thisoption,rmalsoasksyoubeforeexaminingeach
directory.
recursive r
Deletesthecontentsofthespecifieddirectory,includingall
itssubdirectories,andthedirectoryitself.Usethisoption
cautiously.
verbose vDisplaysthenameofeachfileasitisremoved.
Notes
Todeleteafile,youmusthaveexecuteandwriteaccesspermissiontotheparentdirectoryofthefile,but
youdonotneedreadorwriteaccesspermissiontothefileitself.Ifyouarerunningrminteractively(that
is,ifrm'sstandardinputiscomingfromthekeyboard)andyoudonothavewriteaccesspermissiontothe
file,rmdisplaysyouraccesspermissionandwaitsforyoutorespond.Ifyourresponsestartswithayor
Y,rmdeletesthefile;otherwise,ittakesnoaction.Ifstandardinputisnotcomingfromakeyboard,rm
deletesthefilewithoutquestion.
Refertopage97forinformationonhardlinksandpage99forinformationonsymboliclinks.Page101
includesadiscussionaboutremovinglinks.Refertothermdirutility(page755)ifyouneedtoremove
anemptydirectory.
Whenyouwanttoremoveafilethatbeginswithahyphen,youmustpreventrmfrominterpretingthe
filenameasanoption.Onewaytodosoistogivethespecialoptionbeforethenameofthefile.This
optiontellsrmthatnomoreoptionsfollow:Anyargumentsthatcomeafteritarefilenames,evenifthey
looklikeoptions.
security:Useshredtoremoveafilesecurely
Usingrmdoesnotsecurelydeleteafileitispossibletorecoverafiledeletedwithrm.Use
theshredutilitytodeletefilesmoresecurely.Seetheexample"Wipingafile"onpage634
foranothermethodofdeletingfilesmoresecurely.
Examples
Thefollowingcommandsdeletefilesbothintheworkingdirectoryandinanotherdirectory:
$rmmemo
$rmlettermemo1memo2
$rm/home/jenny/temp
Thenextexampleaskstheuserbeforeremovingeachfileintheworkingdirectoryanditssubdirectories:
$rm-ir.
Thiscommandisusefulforremovingfilenamesthatcontainspecialcharacters,especiallySPACEs,
TABs,andNEWLINEs.(Youshouldnotcreatefilenamescontainingthesecharactersonpurpose,butit
mayhappenaccidentally.)
rmdir:Removesadirectory
rmdirdirectory-list
Thermdirutilitydeletesemptydirectories.
Arguments
Thedirectory-listisalistofpathnamesofemptydirectoriesthatrmdirremoves.
Options
Acceptsthecommonoptionsdescribedonpage587.
ignore-fail-on-non-empty
Suppressesthemessagermdirnormallydisplayswhenitfailsbecausea
directoryisnotempty.Withtheparentsoption,rmdirdoesnotquit
whenitfindsadirectorythatisnotempty.
parents pRemovesaseriesofempty,nesteddirectories,startingwiththechild.
verbose vDisplaysthenamesofdirectoriesastheyareremoved.
Notes
Usethermutilitywiththeroptionifyouneedtoremovedirectoriesthatarenotempty,togetherwith
theircontents.
Examples
Thefollowingcommanddeletestheemptyliteraturedirectoryfromtheworkingdirectory:
$rmdirliterature
Thenextcommandremovesthelettersdirectory,usinganabsolutepathname:
$rmdir/home/jenny/letters
Thefinalcommandremovestheletters,march,and05directories,assumingthedirectoriesareempty
exceptforotherdirectoriesnamedinthepath:
$rmdir--parentsletters/march/05
rsh:Executescommandsonaremotesystem
rsh[option]host[command-line]
Thershutilityrunscommand-lineonhostbystartingashellontheremotesystem.Withouta
command-linershcallsrlogin,whichlogsyouinontheremotesystem.
security:rshisnotsecure
Thershutilityuseshost-basedtrust,whichisnotsecure,toauthorizeyourlogin.
Alternatively,itsendsyourpasswordoverthenetworkascleartext,whichisnotasecure
practice.Usessh(page773)whenitisavailable.
Arguments
Thehostisthenameoftheremotesystem.Thershutilityrunscommand-lineontheremotesystem.You
mustquotespecialcharactersincommand-linesothattheyarenotexpandedbythelocalshellpriorto
passingthemtorsh.
Options
lusername (login)Logsyouinontheremotesystemastheuserspecifiedby
username.
Notes
Ifthefilenamed/etc/hosts.equivlocatedontheremotesystemspecifiesthenameofthelocalsystem,the
remotesystemwillnotpromptyoutoenteryourpassword.Systemsthatarelistedinthe/etc/hosts.equiv
fileareconsideredassecureasthelocalsystem.
Analternativewaytospecifyatrustedrelationshipisonaper-userbasis.Eachuser'shomedirectorycan
containafilenamed~/.rhoststhatholdsalistoftrustedremotesystemsandusers.See"Examples"under
rlogin(page752)forasample.rhostsfile.
Examples
Inthefirstexample,Alexusesrshtoobtainalistingofthefilesinhishomedirectoryonbravo:
$rshbravols
cost_of_living
info
preferences
work
Nexttheoutputofthepreviouscommandisredirectedintothefilebravo.ls.Becausetheredirection
character(>)isnotescaped,itisinterpretedbythelocalshell,andthefilebravo.lsiscreatedonthe
localsystem.
$rshbravols>bravo_ls
$catbravo_ls
cost_of_living
info
preferences
work
Thenextexamplequotestheredirectioncharacter(>)sothatthefilebravo.lsiscreatedontheremote
system(bravo),asshownbylsrunonbravo:
$rshbravols">"bravo.ls
$rshbravols
bravo.ls
cost_of_living
info
preferences
work
Inthefinalexample,rshwithoutcommand-linelogsinontheremotesystem.Alexhasusedthel
watsonoptiontologinonbravoaswatson.The/home/watson/.rhostsfilemustbeconfiguredtoallow
Alextologinontheaccountinthismanner.See"Examples"underrlogin(page752)forasample
.rhostsfile.
$rsh-lwatsonbravo
Lastlogin:SatJul3016:13:53fromkudos
$hostname
bravo
$exit
rlogin:connectionclosed.
scp:Securelycopiesoneormorefilestoorfromaremote
system
scp[[user@]from-host:]source-file[[user@]to-host:][destination-
file]
Thescp(securecopy)utilitycopiesanordinaryordirectoryfilefromonesystemtoanotherona
network.Thisutilityusessshtotransferfilesandthesameauthenticationmechanismasssh;therefore
itprovidesthesamesecurityasssh.Thescputilityasksyouforapasswordwhenitisneeded.
Arguments
Thefrom-hostisthenameofthesystemyouarecopyingfilesfromandtheto-hostisthesystemyouare
copyingto.Whenyoudonotspecifyahost,scpassumesthelocalsystem.Theuseroneithersystem
defaultstotheuseronthelocalsystemwhoisgivingthecommand;youcanspecifyadifferentuserwith
user@.Thescputilitypermitsyoutocopybetweentworemotesystems.
Thesource-fileisthefileyouarecopying,andthedestination-fileistheresultingcopy.Youcanspecify
plainordirectoryfilesasrelativeorabsolutepathnames.Arelativepathnameisrelativetothespecified
orimplicituser'shomedirectory.Whenthesource-fileisadirectory,youmustusetheroptiontocopy
itscontents.Whenthedestination-fileisadirectory,eachofthesourcefilesmaintainsitssimple
filename.
Options
p(preserve)Preservesthemodificationandaccesstimesaswellasthepermissions
oftheoriginalfile.
q(quiet)Doesnotdisplaytheprogressmeter.
r(recursive)Recursivelycopiesadirectoryhierarchy.
v(verbose)Displaysdebuggingmessagesabouttheconnectionandtransfer.This
optionisusefulifthingsarenotgoingasexpected.
Notes
ThescputilityisoneoftheOpenSSHsuiteofsecurenetworkconnectivitytools.See"Notes"onpage
774foradiscussionofOpenSSHsecurity.Referto"Messageoninitialconnectiontoaserver"onpage
774forinformationaboutamessageyoumaygetwhenusingscptoconnecttoaremotesystemforthe
firsttime.
Youcancopyfromortothelocalsystemorbetweentworemotesystems.Makesurethatyouhaveread
permissionforthefileyouarecopyingandwritepermissionforthedirectoryyouarecopyingitinto.
Youmustquoteawildcardcharacter(suchas*)inaremotepathnamesothatitisinterpretedbytheshell
ontheremotesystemandnotbythelocalshell.
Aswithcp,ifthedestination-fileexistsbeforeyourunscp,scpoverwritesthefile.
Examples
Thefirstexamplecopiesthefileswithfilenamesendingin.cfromtheworkingdirectoryonthelocal
systemintothe~jenny/archivesdirectoryonbravo.Thewildcardcharacterisnotquotedsothatthe
localshellwillexpandit.Becausearchivesisarelativepathname,scpassumesthatitisasubdirectory
ofJenny'shomedirectoryonbravo.Eachofthecopiedfilesretainsitssimplefilename.
$scp*.cjenny@bravo:archives
NextAlexcopiesthedirectorystructureunder~alex/memosonthesystemnamedbravoto
~jenny/alex.memos.bravoonkudos.HemusthavethenecessarypermissionstowritetoJenny'shome
directoryonkudos.
$scp-rbravo:memosjenny@kudos:alex.memos.bravo
FinallyAlexcopiesthefileswithfilenamesendingin.cfromJenny'sarchivesdirectoryonbravotothe
jenny.c.bravodirectoryinhisworkingdirectory.Thewildcardcharacterisquotedtoprotectitfrom
expansionbythelocalshell;itwillbeinterpretedbytheremotesystem,bravo.
$scp-r'jenny@bravo:archives/*.c'jenny.c.bravo
Itisimportanttorememberthatwheneveryoucopymultiplefilesordirectories,thedestinationeither
localorremotemustbeanexistingdirectoryandnotanordinaryornonexistentfile.
sleep:Createsaprocessthatsleepsforaspecifiedinterval
sleeptime
sleeptime-list
Thesleeputilitycausestheprocessexecutingittogotosleepforthetimespecified.
Arguments
Traditionallytheamountoftimethataprocesssleepsisgivenasasingleintegerargument,time,which
denotesanumberofseconds.Thetimedoesnothavetobeaninteger,however:Youcanspecifya
decimalfraction.Youcanalsoappendaunitspecificationtotime:s(seconds),m(minutes),h(hours),
andd(days).
Youcanconstructatime-listbyincludingseveraltimesonthecommandline:Thetotaltimethatthe
processsleepsisthesumofthesetimes.Forexample,ifyouspecify1h30m100s,theprocesswillsleep
for91minutesand40seconds.
Examples
Youcanusesleepfromthecommandlinetoexecuteacommandafteraperiodoftime.Thefollowing
exampleexecutesinthebackgroundaprocessthatremindsyoutomakeaphonecallin20minutes(1,200
seconds):
$(sleep1200;echo"Remembertomakecall.")&
[1]4660
Alternatively,youcouldgivethefollowingcommandtogetthesamereminder:
$(sleep20m;echo"Remembertomakecall.")&
[2]4667
Youcanalsousesleepwithinashellscripttoexecuteacommandatregularintervals.Thepershell
scriptexecutesaprogramnamedupdateevery90seconds:
$catper
#!/bin/bash
whiletrue
do
update
sleep90
done
Ifyouexecuteashellscriptsuchasperinthebackground,youcanterminateitonlybyusingkill.
Thefinalshellscriptacceptsthenameofafileasanargumentandwaitsforthatfiletoappearonthe
disk.Ifthefiledoesnotexist,thescriptsleepsfor1minuteand45secondsbeforecheckingforthefile
again:
$catwait_for_file
#!/bin/bash
if[$#!=1];then
echo"Usage:wait_for_filefilename"
exit1
fi
whiletrue
do
if[-f"$1"];then
echo"$1isherenow"
exit0
fi
sleep1m45
done
sort:Sortsand/ormergesfiles
sort[options][file-list]
Thesortutilitysortsand/ormergesoneormoretextfiles.
Arguments
Thefile-listisalistofpathnamesofoneormoreordinaryfilesthatcontainthetexttobesorted.Ifthe
file-listisomitted,sorttakesitsinputfromstandardinput.Withouttheooptionsortsendsitsoutput
tostandardoutput.Thisutilitysortsandmergesfilesunlessyouusethem(mergeonly)orc(checkonly)
option.
Options
Whenyoudonotspecifyanoption,sortordersthefileinthemachinecollatingsequence(usually
ASCII).Withoutakeyoptionsortordersafilebasedonfulllines.Usekeytospecifysortfieldswithina
line.Youcanfollowakeyoptionwithadditionaloptionswithoutaleadinghyphen;see"Discussion"for
moreinformation.
ignore-leading-blanks
b
Blanks(TABandSPACEcharacters)normallymarkthebeginningof
fieldsintheinputfile.Withoutthisoption,sortconsidersleading
blankstobepartofthefieldtheyprecede.Thisoptionignores
leadingblankswithinafield,sosortdoesnotconsiderthese
charactersinsortcomparisons.
check c
Checkswhetherthefileisproperlysorted.Thesortutilitydoes
notdisplayanythingifeverythingisinorder.Itdisplaysamessageif
thefileisnotinsortedorderandreturnsanexitstatusof1.
dictionary-order
d
Ignoresallcharactersthatarenotalphanumericcharactersor
blanks.Forexample,sortdoesnotconsiderpunctuationwiththis
option.
ignore-case f
(fold)Considersalllowercaseletterstobeuppercaseletters.Use
thisoptionwhenyouaresortingafilethatcontainsbothuppercase
andlowercasetext.
ignore-nonprinting
iIgnoresnonprintingcharacters.Thisoptionisoverriddenbythedictionary-orderoption.
key=start[,stop]
kstart[,stop]
Specifiesasortfieldwithinaline.Withoutthisoption
sortordersafilebasedonfulllines.Thesortfieldstarts
atthepositiononthelinespecifiedbystartandendsat
stop,ortheendofthelineifstopisomitted.Thestart
andstoppositionsareintheformatf[.c],wherefisthe
fieldnumberandcistheoptionalcharacterwithinthe
field.Numberingstartswith1.Whencisomittedfrom
start,itdefaultstothefirstcharacterinthefield;whenc
isomittedfromstop,itdefaultstothelastcharacterin
thefield.See"Discussion"forfurtherexplanationofsort
fieldsand"Examples"forillustrationsoftheiruse.
merge mAssumesthatmultipleinputfilesareeachinsortedorder
andmergesthemwithoutverifyingthattheyaresorted.
numeric-sort n
Sortsinarithmeticsequence;doesnotorderlinesorsort
fieldsinthemachinecollatingsequence.Withthisoption,
minussignsanddecimalpointstakeontheirarithmetic
meaning.
output=filename
ofilename
Sendsoutputtofilenameinsteadofstandardoutput;filenamecan
bethesameasoneofthenamesinthefile-list.
reverse rReversesthesenseofthesort(forexample,zprecedesa).
field-separator=x
tx
Specifiesxasthefieldseparator.See"Discussion"formore
information.
unique u
Outputsrepeatedlinesonlyonce.Whenyouusethisoptionwith
check,sortdisplaysamessageifthesamelineappearsmore
thanonceintheinputfile,evenifthefileisinsortedorder.
Discussion
Withoutanyoptionssortbasesitsorderingonfulllines.
Inthefollowingdescription,afieldisasequenceofcharactersinalineofinput.Withoutthefield-

separatoroption,fieldsareboundedbytheemptystringprecedingagroupofoneormoreblanks(TAB
andSPACEcharacters).Youcannotseetheemptystringthatdelimitsthefields;itisanimaginarypoint
betweentwofields.Fieldsarealsoboundedbythebeginningandendoftheline.Thelineshownin
Figure0-1holdsthefieldsToni,SPACEBarnett,andSPACESPACESPACESPACE55020.Thesefields
areusedtodefinesortfields.Sometimefieldsandsortfieldsarethesame.
Sortfield
Asortfieldisasequenceofcharactersthatsortusestoputlinesinorder.Asortfieldcancontainallor
partofoneormorefields(FigureV-1).
FigureV-1.Fieldsandsortfields
Thekeyoptionspecifiespairsofpointersthatdefinesubsectionsofeachline(sortfields)for
comparison.Seethekeyoption(page763)fordetails.
Leadingblanks
Theboptioncausessorttoignoreleadingblanksinasortfield.Ifyoudonotusethisoption,sort
considerseachleadingblanktobeacharacterinthesortfieldandincludesitinthesortcomparison.
Options
Youcanspecifyoptionsthatpertainonlytoagivensortfieldbyimmediatelyfollowingthestoppointer
(orthestartpointerifthereisnostoppointer)withoneoftheoptionsb,d,f,i,n,orr.Inthiscaseyou
mustnotprecedetheoptionwithahyphen.
Multiplesortfields
Whenyouspecifymorethanonesortfield,sortexaminesthemintheorderyouspecifythemonthe
commandline.Ifthefirstsortfieldoftwolinesisthesame,sortexaminesthesecondsortfield.Ifthese
areagainthesame,sortlooksatthethirdfield.Thisprocesscontinuesforallthesortfieldsyou
specify.Ifallthesortfieldsarethesame,sortexaminestheentireline.
Examples
Theexamplesinthissectiondemonstratesomeofthefeaturesandusesofthesortutility.Theexamples
assumethatthelistfileshownhereisintheworkingdirectory:
$catlist
TomWinstrom94201
JanetDempsey94111
AliceMacLeod94114
DavidMack94114
ToniBarnett95020
JackCooper94072
RichardMacDonald95510
ThisfilecontainsalistofnamesandZIPcodes.Eachlineofthefilecontainsthreefields:thefirstname
field,thelastnamefield,andtheZIPcodefield.Fortheexamplestowork,makesuretheblanksinthe
fileareSPACEs,andnotTABs.
Thefirstexampledemonstratessortwithoutanyoptionstheonlyargumentisthenameoftheinputfile.
Inthiscasesortordersthefileonaline-by-linebasis.Ifthefirstcharactersontwolinesarethesame,
sortlooksatthesecondcharacterstodeterminetheproperorder.Ifthesecondcharactersarethesame,
sortlooksatthethirdcharacters.Thisprocesscontinuesuntilsortfindsacharacterthatdiffers
betweenthelines.Ifthelinesareidentical,itdoesnotmatterwhichonesortputsfirst.Inthisexample,
sortneedstoexamineonlythefirstthreecharacters(atmost)ofeachline.Thesortutilitydisplaysa
listthatisinalphabeticalorderbyfirstname.
$sortlist
AliceMacLeod94114
DavidMack94114
JackCooper94072
JanetDempsey94111
RichardMacDonald95510
TomWinstrom94201
ToniBarnett95020
Youcaninstructsorttoskipanynumberoffieldsandcharactersonalinebeforebeginningits
comparison.Blanksnormallymarkthebeginningofafield.Thenextexamplesortsthesamelistbylast
name,thesecondfield.Thekey=2argumentinstructssorttobeginitscomparisonwiththesecond
field,thelastname.Becausethereisnosecondpointer,thesortfieldextendstotheendoftheline.Now
thelistisalmostinlast-nameorder,butthereisaproblemwithMac.
$sort--key=2list
ToniBarnett95020
JackCooper94072
JanetDempsey94111
RichardMacDonald95510
AliceMacLeod94114
DavidMack94114
TomWinstrom94201
Intheprecedingexample,MacLeodcomesbeforeMack.Afterfindingthatthesortfieldsofthesetwo
lineswerethesamethroughthethirdletter(Mac),sortputLbeforekbecauseitarrangeslinesbased
onASCIIcharactercodes,inwhichuppercaseletterscomebeforelowercaseones.
Theignore-caseoptionmakessorttreatuppercaseandlowercaselettersasequalsandfixesthe
problemwithMacLeodandMack:
$sort--ignore-case--key=2list
ToniBarnett95020
JackCooper94072
JanetDempsey94111
RichardMacDonald95510
DavidMack94114
AliceMacLeod94114
TomWinstrom94201
Thenextexampleattemptstosortlistonthethirdfield,theZIPcode.Inthiscasesortdoesnotputthe
numbersinorderbutratherputstheshortestnamefirstinthesortedlistandthelongestnamelast.The
key=3argumentinstructssorttobeginitscomparisonwiththethirdfield,theZIPcode.Afieldstarts
withablankandincludessubsequentblanks.Inthecaseofthelistfile,theblanksareSPACEs.The
ASCIIvalueofaSPACEcharacterislessthanthatofanyotherprintablecharacter,sosortputstheZIP
codethatisprecededbythemostSPACEsfirstandtheZIPcodethatisprecededbythefewestSPACEs
last.
$sort--key=3list
DavidMack94114
JackCooper94072
TomWinstrom94201
ToniBarnett95020
JanetDempsey94111
AliceMacLeod94114
RichardMacDonald95510
Theb(ignore-leading-blanks)optioncausessorttoignoreleadingSPACEswithinafield.Withthis
option,theZIPcodescomeoutintheproperorder.WhensortdeterminesthatMacLeodandMack
havethesameZIPcodes,itcomparestheentirelines,puttingAliceMacLeodbeforeDavidMack
(becauseAcomesbeforeD).
$sort-b--key=3list
JackCooper94072
JanetDempsey94111
AliceMacLeod94114
DavidMack94114
TomWinstrom94201
ToniBarnett95020
RichardMacDonald95510
TosortalphabeticallybylastnamewhenZIPcodesarethesame,sortneedstomakeasecondpassthat
sortsonthelastnamefield.Thenextexampleshowshowtomakethissecondpassbyspecifyingasecond
sortfieldandusesthef(ignore-case)optiontokeeptheMack/MacLeodproblemfromcroppingup
again:
$sort-b-f--key=3--key=2list
JackCooper94072
JanetDempsey94111
DavidMack94114
AliceMacLeod94114
TomWinstrom94201
ToniBarnett95020
RichardMacDonald95510
Thenextexampleshowsasortcommandthatskipsnotonlyfieldsbutalsocharacters.Thek3.4option
(equivalenttokey=3.4)causessorttostartitscomparisonwiththefourthcharacterofthethirdfield.
Becausethecommanddoesnotdefineanendtothesortfield,itdefaultstotheendoftheline.Thesort
fieldisthelasttwodigitsintheZIPcode.
$sort-fb-k3.4list
TomWinstrom94201
RichardMacDonald95510
JanetDempsey94111
AliceMacLeod94114
DavidMack94114
ToniBarnett95020
JackCooper94072
TheproblemofhowtosortbylastnamewithinthelasttwodigitsoftheZIPcodeissolvedbyasecond
passcoveringthelast-namefield.Thefoptionfollowingthek2affectsthesecondpass,whichordersby
lastnameonly.
$sort-b-k3.4-k2flist
TomWinstrom94201
RichardMacDonald95510
JanetDempsey94111
DavidMack94114
AliceMacLeod94114
ToniBarnett95020
JackCooper94072
Thenextsetofexamplesusesthecarsdatafile.Fromlefttorightthecolumnsinthefilecontaineach
car'smake,model,yearofmanufacture,mileage,andprice:
$catcars
plymfury1970732500
chevymalibu1999603000
fordmustang19654510000
volvos8019981029850
fordthundbd20031510500
chevymalibu2000503500
bmw325i1985115450
hondaaccord2001306000
fordtaurus20041017000
toyotarav42002180750
chevyimpala1985851550
fordexplor2003259500
Withoutanyoptionssortdisplaysasortedcopyofthefile:
$sortcars
bmw325i1985115450
chevyimpala1985851550
chevymalibu1999603000
chevymalibu2000503500
fordexplor2003259500
fordmustang19654510000
fordtaurus20041017000
fordthundbd20031510500
hondaaccord2001306000
plymfury1970732500
toyotarav42002180750
volvos8019981029850
Theobjectiveofthenextexampleistosortbymanufacturerandbypricewithinmanufacturer.Unlessyou
specifyotherwise,asortfieldextendstotheendoftheline.Thek1sortfieldspecifiersortsfromthe
beginningoftheline.Thecommandlineinstructssorttosortontheentirelineandthenmakeasecond
pass,sortingonthefifthfieldalllineswhosefirst-passsortfieldswerethesame(k5):
$sort-k1-k5cars
bmw325i1985115450
chevyimpala1985851550
chevymalibu1999603000
chevymalibu2000503500
fordexplor2003259500
fordmustang19654510000
fordtaurus20041017000
fordthundbd20031510500
hondaaccord2001306000
plymfury1970732500
toyotarav42002180750
volvos8019981029850
Becausenotwolinesarethesame,sortmakesonlyonepass,sortingoneachentireline.(Iftwolines
differedonlyinthefifthfield,theywouldbesortedproperlyonthefirstpassanyway,sothesecondpass
wouldbeunnecessary.)Lookatthelinescontainingtaurusandthundbd.Theyaresortedbythesecond
fieldratherthanthefifth,demonstratingthatsortnevermadeasecondpassandsoneversortedonthe
fifthfield.
Thenextexampleforcesthefirst-passsorttostopattheendofthefirstfield.Thek1,1optionspecifiesa
startpointerofthefirstcharacterofthefirstfieldandastoppointerofthelastcharacterofthefirstfield.
Whenyoudonotspecifyacharacterwithinastartpointer,itdefaultstothefirstcharacter;whenyoudo
notspecifyacharacterwithinastoppointer,itdefaultstothelastcharacter.Nowthetaurusandthundbd
areproperlysortedbyprice.Butlookattheexplor:ItislessexpensivethantheotherFords,butsort
hasitpositionedasthemostexpensive.ThesortutilityputthelistinASCIIcollatingsequenceorder,
notinnumericorder:Thus9500comesafter10000because9comesafter1.
$sort-k1,1-k5cars
bmw325i1985115450
chevyimpala1985851550
chevymalibu1999603000
chevymalibu2000503500
fordmustang19654510000
fordthundbd20031510500
fordtaurus20041017000
fordexplor2003259500
hondaaccord2001306000
plymfury1970732500
toyotarav42002180750
volvos8019981029850
Then(numeric)optiononthesecondpassputsthelistintheproperorder:
$sort-k1,1-k5ncars
bmw325i1985115450
chevyimpala1985851550
chevymalibu1999603000
chevymalibu2000503500
fordexplor2003259500
fordmustang19654510000
fordthundbd20031510500
fordtaurus20041017000
hondaaccord2001306000
plymfury1970732500
toyotarav42002180750
volvos8019981029850
Thenextexampleagaindemonstratesthat,unlessyouinstructitotherwise,sortordersafilestarting
withthefieldyouspecifyandcontinuingtotheendoftheline.Itdoesnotmakeasecondpassunlesstwo
ofthefirstsortfieldsarethesame.Becausethereisnostoppointeronthefirstsortfieldspecifier,the
sortfieldforthefirstpassincludesthethirdfieldthroughtheendoftheline.Althoughthisexamplesorts
thecarsbyyears,itdoesnotsortthecarsbymodelwithinmanufacturerwithinyears(fordthndbdcomes
beforefordexplor,theselinesshouldbereversed).
$sort-k3-k1cars
fordmustang19654510000
plymfury1970732500
bmw325i1985115450
chevyimpala1985851550
volvos8019981029850
chevymalibu1999603000
chevymalibu2000503500
hondaaccord2001306000
toyotarav42002180750
fordthundbd20031510500
fordexplor2003259500
fordtaurus20041017000
Specifyinganendtothesortfieldforthefirstpassallowssorttoperformitssecondarysortproperly:
$sort-k3,3-k1cars
fordmustang19654510000
plymfury1970732500
bmw325i1985115450
chevyimpala1985851550
volvos8019981029850
chevymalibu1999603000
chevymalibu2000503500
hondaaccord2001306000
toyotarav42002180750
fordexplor2003259500
fordthundbd20031510500
fordtaurus20041017000
Thenextexamplesdemonstrateimportantsortingtechniques:puttingalistinalphabeticalorder,merging
uppercaseandlowercaseentries,andeliminatingduplicates.Theunsortedlistfollows:
$catshort
Pear
Pear
apple
pear
Apple
Followingisaplainsort:
$sortshort
Apple
Pear
Pear
apple
pear
Thefollowingfoldedsortisagoodstart,butitdoesnoteliminateduplicates:
$sort-fshort
Apple
apple
Pear
Pear
pear
Theu(unique)optioneliminatesduplicatesbutwithouttheftheuppercaseentriescomefirst:
$sort-ushort
Apple
Pear
apple
pear
Whenyouattempttousebothuandf,someoftheentriesgetlost:
$sort-ufshort
apple
Pear
Twopassesistheanswer.Bothpassesareuniquesorts,andthefirstfoldslowercaselettersonto
uppercaseones:
$sort-u-k1f-k1short
Apple
apple
Pear
pear
split:Dividesafileintosections
split[options][filename[prefix]]
Thesplitutilitybreaksitsinputinto1000-linesectionsnamedxaa,xab,xac,andsoon.Thelast
sectionmaybeshorter.Optionscanchangethesizesofthesectionsandlengthsofthenames.
Arguments
Thefilenameisthepathnameofthefilethatsplitprocesses.Ifyoudonotspecifyanargumentorif
youspecifyahyphen()insteadofthefilename,splitreadsfromstandardinput.Theprefixisoneor
morecharactersthatsplitusestoprefixthenamesofthefilesitcreates.Thedefaultprefixisx.
Options
Acceptsthecommonoptionsdescribedonpage587.
suffix-length=len
alen
Specifiesthatthefilenamesuffixislencharacterslong(thedefaultis
2).
bytes=n[u] bn[u]
Breakstheinputintofilesthatarenbyteslong.Theuisanoptional
unitofmeasurethatcanbeb(512-byteblocks),k(kilobyteor
1,024-byteblocks),orm(megabyteor1,048,576-byteblocks).If
youincludetheunitofmeasure,splitcountsbythisunitinplace
ofbytes.
numeric-suffixes
dSpecifiesnumericsuffixesinsteadofalphabeticsuffixes.
lines=num lnum
Breakstheinputintofilesthatarenumlineslong(thedefaultis
1,000).
Discussion
Bydefaultsplitnamesthefirstfileitcreatesxaa.Thexisthedefaultprefix.Youcanchangetheprefix
withtheprefixargumentonthecommandline.Youcanchangethenumberofcharactersineachfilename
followingtheprefixwiththesuffix-lengthoption.
Examples
Bydefaultsplitbreaksafileinto1,000-linesectionswiththenamesxaa,xab,xac,andsoon.Thewc
utilitywiththeloptionshowsthenumberoflinesineachfile.Thelastfile,xar,issmallerthantherest.
$split/etc/termcap
$wc-l*
1000xaa
1000xab
1000xac
...
1000xap
1000xaq
103xar
17103total
ThenextexampleusestheprefixargumenttospecifyafilenameprefixofSECandusessuffix-lengthto
changethenumberoflettersinthefilenamesuffixto3:
$split--suffix-length=3/etc/termcapSEC
$ls
SECaaaSECaacSECaaeSECaagSECaaiSECaakSECaamSECaao
SECaaq
SECaabSECaadSECaafSECaahSECaajSECaalSECaanSECaap
SECaar
ssh:Securelyexecutescommandsonaremotesystem
ssh[option][user@]host[command-line]
Thesshutilityrunscommand-lineonhostbystartingashellontheremotesystemorlogsyouinon
host.Thesshutility,whichcanreplacershandrlogin,providessecure,encryptedcommunication
betweentwosystemsonaninsecurenetwork.
Arguments
Thehostisthesystemthatyouwanttologinorrunacommandon.Unlessyouhaveoneofseveralkinds
ofauthenticationestablished,sshpromptsyouforausernameandpasswordfortheremotesystem.When
sshisabletologinautomatically,itlogsinastheuserrunningthesshcommandorasuserifuser@
appearsonthesshcommandline.
Thecommand-linerunsontheremotesystem.Withoutcommand-line,sshlogsyouinontheremote
system.Youmustquotespecialcharactersincommand-lineifyoudonotwantthemexpandedbythe
localshell.
Options
f
(notforeground)Sendssshtothebackgroundafteraskingforapasswordandbefore
executingcommand-line.Thisoptionisusefulwhenyouwanttorunthecommand-line
inthebackgroundbutmustsupplyapassword.Itsuseimpliesn.
luser
(login)Attemptstologinasuser.Thisoptionisequivalenttousinguser@onthe
commandline.
n(null)Redirectsstandardinputtosshtocomefrom/dev/null.Seef.
pport
Connectstoportportontheremotehost.
q(quiet)Suppresseswarninganddiagnosticmessages.
t
(tty)Allocatesapseudo-ttytothesshprocessontheremotesystem.Withoutthisoption,
whenyourunacommandonaremotesystem,sshdoesnotallocateatty(terminal)tothe
process.Instead,sshattachesstandardinputandstandardoutputoftheremoteprocessto
thesshsessionthatis,normally,butnotalways,whatyouwant.Thisoptionforcessshto
allocateattyontheremotesystemsothatprogramsthatrequireattywillwork.
v(verbose)Displaysdebuggingmessagesabouttheconnectionandtransfer.Thisoptionis
usefulifthingsarenotgoingasexpected.
x(X11)TurnsoffX11forwarding.
X(X11)TurnsonX11forwarding.YoumaynotneedthisoptionX11forwardingmaybe
turnedoninaconfigurationfile.
Notes
OpenSSH
Usingpublic-keyencryption,OpenSSHprovidestwolevelsofauthentication:serverandclient/user.
First,theclient(sshorscp)verifiesthatitisconnectedtothecorrectserverandOpenSSHencrypts
communicationbetweentheclientandserver.Second,onceasecure,encryptedconnectionhasbeen
established,OpenSSHconfirmsthattheuserisauthorizedtologinonorcopyfilesfrom/totheserver.
Oncethesystemanduserhavebeenverified,OpenSSHallowsdifferentservicestopassthroughthe
connection.Theseservicesincludeinteractiveshellsessions(ssh),remotecommandexecution(ssh
andscp),X11client/serverconnections,andTCP/IPporttunneling.
Messageoninitialconnectiontoaserver
WhenyouconnecttoanOpenSSHserverforthefirsttime,theOpenSSHclientpromptsyoutoconfirm
thatyouareconnectedtothecorrectsystem.Thischeckingcanhelppreventaperson-in-the-middle
attack.
Theauthenticityofhost'grape(192.168.0.3)'can'tbeestablished.
RSAkeyfingerprintis
c9:03:c1:9d:c2:91:55:50:e8:19:2b:f4:36:ef:73:78.
Areyousureyouwanttocontinueconnecting(yes/no)?yes
Warning:Permanentlyadded'grape,192.168.0.3'(RSA)tothelistof
knownhosts.
Beforeyourespondtotheprecedingquery,verifythatyouarelogginginonthecorrectsystemandnotan
imposter.Ifyouarenotsure,atelephonecalltosomeonewhologsinonthatsystemlocallycanverify
thatyouareontheintendedsystem.Whenyouansweryes(youmustspellitout),theclientappendsthe
server'spublichostkeytotheuser's~/.ssh/known_hostsfileonthelocalsystem,creatingthe~/.ssh
directoryifnecessary.Sothatitcankeeptrackofwhichlineinknown_hostsappliestowhichserver,
OpenSSHprependsthenameoftheserverandtheserver'sIPaddresstotheline.Subsequently,whenyou
useOpenSSHtoconnecttothatserver,theclientverifiesthatitisconnectedtothecorrectserverby
comparingthiskeytotheonesuppliedbytheserver.
Examples
Inthefirstexample,Alexusessshtodisplayalistofthefilesinhishomedirectoryonkudos:
$sshkudosls
alex@kudos'spassword:
Work
code
graphs
reports
Nexttheoutputofthepreviouscommandisredirectedtothefilekudos_ls.Becausetheredirection
character(>)isnotescaped,itisinterpretedbythelocalshell,andthefilekudos_lsiscreatedonthe
localsystem.
$sshkudosls>kudos_ls
alex@kudos'spassword:
$catkudos_ls
Work
code
graphs
reports
Thenextexamplequotestheentirecommandthatwillrunontheremotesystem.Asaresult,thelocal
shelldoesnotinterprettheredirectioncharacter(>)butratherpassesittotheremoteshell.Thefile
kudos.lsiscreatedontheremotesystem(kudos),asshownbylsrunonkudos:
$sshkudos"ls>kudos.ls"
alex@kudos'spassword:
$sshkudosls
alex@kudos'spassword:
Work
code
graphs
kudos.ls
reports
Thenextcommanddoesnotquotethepipesymbol(|).Asaresultthepipeisinterpretedbythelocalshell,
whichsendstheoutputoftheremotelstostandardinputoflessonthelocalsystem:
$sshkudosls|less
Nextsshexecutesaseriesofcommands,connectedwithpipes,onaremotesystem.Thecommandsare
enclosedwithinsinglequotationmarkssothatthelocalshelldoesnotinterpretthepipesymbolsandall
thecommandsarerunontheremotesystem.
$sshkudos'ps-ef|grepnmbd|grep-vgrep|cut-c10-15|xargs
kill-1'
Theoutputofpsispipedthroughgrep,whichpassesalllinescontainingthestringnmbdtoanother
invocationofgrep.Thesecondgreppassesalllinesnotcontainingthestringgreptocut(page627).
ThecututilityextractstheprocessIDnumbersandpassesthemtoxargs(page821),whichkillsthe
listedprocesseswithaHUPsignal(kill1).
Inthefollowingexample,sshwithoutcommand-linelogsinontheremotesystem.HereAlexhasused
watson@kudostologinonkudosaswatson:
$sshwatson@kudos
watson@kudos'spassword:
Lastlogin:SatSep1706:51:59frombravo
$hostname
kudos
$exit
Alexnowdecidestochangethepasswordforhiswatsonloginonkudos.
$sshwatson@kudospasswd
watson@kudos'spassword:
(current)UNIXpassword:por
Alexstopsassoonasheseespasswd(runningonkudos)displayinghispassword:Heknowsthat
somethingiswrong.Forthepasswdtowork,itmustrunwithatty(terminal)sothatitcanturnoff
characterecho(sttyecho)andthusnotdisplaypasswordsastheuserentersthem.Thetoptionsolvesthe
problembyassociatingapseudo-ttywiththeprocessrunningpasswdontheremotesystem:
$ssh-twatson@kudospasswd
watson@kudos'spassword:
Changingpasswordforwatson
(current)UNIXpassword:
NewUNIXpassword:
RetypenewUNIXpassword:
passwd:allauthenticationtokensupdatedsuccessfully
Connectiontokudosclosed.
$
Thetoptionisalsousefulwhenyouarerunningaprogramthatusesacharacter-based/pseudographical
interface.
Thefollowingexampleusestar(page786)tocreateanarchivefileofthecontentsoftheworking
directoryhierarchy.Thefoptioncausestartosenditsoutputtostandardoutput.Apipesendstheoutput
oftarrunningonthelocalsystem,viassh,todd(page633)runningontheremotesystem.
$catbuwd
#!/bin/bash
#backuptheworkingdirectorytotheuser's
#homedirectoryontheremotesystemspecified
#by$machine
#remotesystem:
machine=speedy
dir=$(basename$(pwd))
filename=$$.$dir.tar
echoBackingup$(pwd)toyourhomedirectoryon$machine
tar-cf-.|ssh$machine"ddobs=256kof=$filename"
echodone.Nameoffileon$machineis$filename
strings:Displaysstringsofprintablecharacters
strings[options]file-list
Thestringsutilitydisplaysstringsofprintablecharactersfromobjectandothernontextfiles.
Arguments
Thefile-listisalistoffilesthatstringsprocesses.
Options
all a
Processeswholefiles.Withoutthisoptionstrings
processesonlytheinitializedandloadedpartsofan
objectfile.
bytes=min min
Displaysstringsofcharactersthatareatleastmin
characterslong(thedefaultis4).
print-file-name
fPrecedeseachstringwiththenameofthefilethatthestringcomesfrom.
Discussion
Thestringsutilitycanhelpyoudeterminethecontentsofnontextfiles.Oneapplicationforstrings
isdeterminingtheowneroffilesinalost+founddirectory.
Examples
Thefollowingexampledisplaysthestringsoffourormoreprintablecharactersintheexecutablefilefor
themanutility.Ifyoudidnotknowwhatthisfilewas,thesestringscouldhelpyoudeterminethatitwas
themanexecutable.
$strings/usr/bin/man
...
man:internalerror-cannotfindmessage%d
/unsafe/
my_xsprintfcalledwith%s
Errorparsingconfigfile
Nomanualentryfor%s
using%saspager
%s,version%s
foundmandirectory%s
foundmanpathmap%s-->%s
correspondingcatdiris%s
Linetoolonginconfigfile
section:%s
...
stty:Displaysorsetsterminalparameters
stty[options][arguments]
Withoutanyarguments,sttydisplayscertainparametersaffectingtheoperationoftheterminal/terminal
emulator.Foralistofsomeoftheseparametersandanexplanationofeach,see"Arguments."The
argumentsestablishorchangeparameters.
Options
Acceptsthecommonoptionsdescribedonpage587.
all aReportsonallparameters.Thisoptiondoesnotacceptarguments.
file=/dev/device
F/dev/device
Affectsdevice.Withoutthisoptionsttyaffectsthedeviceattached
tostandardinput.Youcanchangethecharacteristicsofadevice
onlyifyouownitsdevicefileorifyouareSuperuser.
save g
Generatesareportofthecurrentsettingsinaformatyoucanuseas
argumentstoanothersttycommand.Thisoptiondoesnotaccept
arguments.
Arguments
Theargumentstosttyspecifywhichterminalparameterssttyistoalter.Turnoneachofthe
parametersthatisprecededbyanoptionalhyphen(indicatedinthefollowinglistas[])byspecifyingthe
parameterwithoutthehyphen.Turnitoffbyusingthehyphen.Unlessspecifiedotherwise,thissection
describestheparametersintheironstates.
SpecialKeysandCharacteristics
ColumnsnSetsthelinewidthtoncolumns.
ek (erasekill)Setstheeraseandlinekillkeystotheirdefaultvalues.Many
systemsuseDELETEandCONTROL-Uasthedefaults.
erasex
Setstheerasekeytox.Tospecifyacontrolcharacter,precedexwith
CONTROL-V(forexample,useCONTROL-VCONTROL-Htoindicate
CONTROL-H)orusethenotation^h,where^isacaret(SHIFT6onmost
keyboards).
intrxSetstheinterruptkeytox.Seeerasexforconventions.
killxSetsthelinekillkeytox.Seeerasexforconventions.
rowsnSetsthenumberofscreenrowston.
sane
Setstheterminalparameterstovaluesthatareusuallyacceptable.Thesane
argumentisusefulwhenseveralsttyparametershavechanged,makingit
difficulttousetheterminaltorunsttytosetthingsright.Ifsanedoesnot
appeartowork,tryenteringthefollowingcharacters:
CONTROL-JsttysaneCONTROL-J
suspx(suspend)Setsthesuspend(terminalstop)keytox.Seeerasexfor
conventions.
werasex(worderase)Setstheworderasekeytox.Seeerasexforconventions.
ModesofDataTransmission
[]cooked Seeraw.
[]cstopb (stopbits)Selectstwostopbits(cstopbspecifiesonestopbit).
[]parenb (parityenable)Enablesparityoninputandoutput.Whenyouspecifyparenb,the
systemdoesnotuseorexpectaparitybitwhencommunicatingwiththeterminal.
[]parodd (parityodd)Selectsoddparity(paroddselectsevenparity).
[]raw
Thenormalstateisraw.Whenthesystemreadsinputinitsrawform,itdoesnot
interpretthefollowingspecialcharacters:erase(usuallyDELETE),linekill(usually
CONTROL-U),interruptexecution(CONTROL-C),andEOF(CONTROL-D).In
addition,thesystemdoesnotuseparitybits.Reflectingthehumorthatistypicalof
Linux'sheritage,youcanspecifyrawascooked.
TreatmentofCharacters
[]echo
Echoescharactersastheyaretyped(full-duplexoperation).Ifaterminalishalf-
duplexanddisplaystwocharactersforeachoneitshoulddisplay,turntheecho
parameteroff(echo).Useechowhentheuserisenteringpasswords.
[]echoe
(echoerase)Thenormalsettingisechoe,whichcausesthekerneltoechothe
charactersequenceBACKSPACESPACEBACKSPACEwhenyouusetheerasekey
todeleteacharacter.Theeffectistomovethecursorbackwardacrosstheline,
removingcharactersasyoudeletethem.
[]echoke
(echokillerase)Thenormalsettingisechoke.Whenyouusethekillcharacterto
deletealinewhilethisoptionisset,allcharactersbacktothepromptareerasedon
thecurrentline.Whenthisoptionisnegated,pressingthekillkeymovesthecursor
tothebeginningofthenextline.
[]echoprt
(echoprint)Thenormalsettingisechoprt,whichcausescharacterstodisappearas
youerasethem.Whenyousetechoprt,charactersthatyouerasearedisplayed
betweenabackslash(\)andaslash(/).Forexample,ifyoutypethewordsortand
theneraseitbypressingBACKSPACEfourtimes,Linuxdisplayssort\tros/when
echoprtisset.Also,ifyouusethekillcharactertodeletetheentireline,having
echoprtsetcausestheentirelinetobedisplayedasifyouhadBACKSPACEdtothe
beginningoftheline.
[]lcase Foruppercase-onlyterminals,translatesalluppercasecharactersintolowercaseas
theyareentered(also[]LCASE).
[]nl
AcceptsonlyaNEWLINEcharacterasalineterminator.Withnlineffect,the
systemacceptsaRETURNcharacterfromtheterminalasaNEWLINEbutsendsa
RETURNfollowedbyaNEWLINEtotheterminalinplaceofaNEWLINE.
[]tabs
TransmitseachTABcharactertotheterminalasaTABcharacter.Whentabsis
turnedoff(tabs),thekerneltranslateseachTABcharacterintotheappropriate
numberofSPACEsandtransmitsthemtotheterminal(also[]tab3).
JobControlParameters
[]tostop
Stopsbackgroundjobsiftheyattempttosend
outputtotheterminal(tostopallows
backgroundjobstosendoutputtotheterminal).
Notes
Thenamesttyisanabbreviationforsetteletypewriter,orsettty(page807),thefirstterminalthat
UNIXwasrunon.Todaysttyiscommonlythoughtofassetterminal.
Theshellsretainsomecontroloverstandardinputwhenyouusetheminteractively.Asaconsequencea
numberoftheoptionsavailablewithsttyappeartohavenoeffect.Forexample,thecommandstty
echoappearstohavenoeffectundertcsh:
tcsh$stty-echo
tcsh$date
FriFeb1821:21:14PST2005
Whilesttyechodoesworkwhenyouareusingbashinteractively,sttyechoedoesnot.However,you
canstillusetheseoptionstoaffectshellscriptsandotherutilities.
$cattestit
#!/bin/bash
stty-echo
echo-n"Enteravalue:"
reada
echo
echo"Youentered:$a"
sttyecho
$testit
Enteravalue:
Youentered:77
Intheprecedingexample,thekerneldoesnotdisplaytheuser'sresponsetotheEnteravalue:prompt.
Thevalueisretainedbytheavariableandisdisplayedbytheecho"Youentered:$a"statement.
Examples
Thefirstexampleshowsthatsttywithoutanyargumentsdisplaysseveralterminaloperation
parameters.(Yoursystemmaydisplaymoreordifferentparameters.)Thecharacterfollowingtheerase=
istheerasekey.A^precedingacharacterindicatesaCONTROLkey.Intheexampletheerasekeyisset
toCONTROL-H.Ifsttydoesnotdisplaytheerasecharacter,itissettoitsdefaultvalueofDELETE.
Ifyoudonotseeakillcharacter,itissettoitsdefaultof^U.
$stty
speed38400baud;line=0;
erase=^H;
Nexttheekargumentreturnstheeraseandlinekillkeystotheirdefaultvalues:
$sttyek
Thenextdisplayverifiesthechange.Thesttyutilitydoesnotdisplayeithertheerasecharacterorthe
linekillcharacter,indicatingthatbotharesettotheirdefaultvalues:
$stty
speed38400baud;line=0;
ThenextexamplesetstheerasekeytoCONTROL-H.TheCONTROL-VquotestheCONTROL-Hsothat
theshelldoesnotinterpretitanditispassedtostty:
$sttyeraseCONTROLVCONTROLH
$stty
speed38400baud;line=0;
erase=^H;
NextsttysetsthelinekillkeytoCONTROL-X.Thistimetheuserenteredacaret(^)followedbyanx
torepresentCONTROL-X.Youcanuseeitheralowercaseoruppercaseletter.
$sttykill^X
$stty
speed38400baud;line=0;
erase=^H;kill=^X;
NowsttychangestheinterruptkeytoCONTROL-C:
$sttyintrCONTROLVCONTROLC
Inthefollowingexample,sttyturnsoffTABssothattheappropriatenumberofSPACEsissenttothe
terminalinplaceofaTAB.UsethiscommandifaterminaldoesnotautomaticallyexpandTABs.
$stty-tabs
Ifyouloginandeverythingappearsontheterminalinuppercaseletters,givethefollowingcommandand
thenchecktheCAPSLOCKkey.Ifitisset,turnitoff:
$STTY-LCASE
Turnonlcaseifyouareusingaveryoldterminalthatcannotdisplaylowercasecharacters.
AlthoughnooneusuallychangesthesuspendkeyfromitsdefaultofCONTROL-Z,youcan.Givethe
followingcommandtochangethesuspendkeytoCONTROL-T:
$sttysusp^T
tail:Displaysthelastpart(tail)ofafile
tail[options][file-list]
Thetailutilitydisplaysthelastpart,orend,ofafile.
Arguments
Thefile-listisalistofpathnamesofthefilesthattaildisplays.Whenyouspecifymorethanonefile,
taildisplaysthefilenameofeachfilebeforedisplayingthelinesofthefile.Ifyoudonotspecifyan
argumentorifyouspecifyahyphen()insteadofafilename,tailreadsfromstandardinput.
Options
Acceptsthecommonoptionsdescribedonpage587.
bytes=[+]n[u]
c[+]n[u]
Countsbybytes(characters)insteadoflines.Thenisanintegerthat
specifiesthenumberofbytes.Thusthecommandtailc5displaysthelast
fivebytesofafile.Theuisanoptionalunitofmeasurethatcanbeb(512-
byteblocks),k(kilobyteor1,024-byteblocks),orm(megabyteor
1,048,576-byteblocks).Ifyouincludetheunitofmeasure,tailcounts
bythisunitinsteadofbybytes.
Ifyouputaplussign(+)infrontofn,tailcountsfromthestartofthe
fileinsteadoftheend.Thetailutilitystilldisplaystotheendofthefile,
eventhoughitstartscountingfromthebeginning.Thustailc+5causes
tailtodisplayfromthefifthcharacterthroughtheendofthefile.
follow f
Aftercopyingthelastlineofthefile,tailentersanendlessloop,waiting
andcopyingadditionallinesfromthefileifthefilegrows.Ifyouspecify
multiplefilesinfile-listwiththisoption,tailincludesanewheadereach
timeitdisplaysoutputfromadifferentfilesothatyouknowwhichfileis
beingaddedto.Thisoptionisusefulfortrackingtheprogressofaprocess
thatisrunninginthebackgroundandsendingitsoutputtoafile.The
tailutilitycontinuestowaitindefinitely,soyoumustusetheinterrupt
keytoterminateit.Seealsothesoption.
lines=[+]n[u] n[+]n[u]
Countsbylines(thedefault).Thenisanintegerthatspecifiesthenumber
oflines.Theuisanoptionalunitofmeasure;seethebytesoptionforan
explanationofitsuse.Althoughitisnotdocumented,youcanuse±nto
specifyanumberoflineswithoutusingthisoption.
Ifyouputaplussign(+)infrontofn,tailcountsfromthestartofthe
fileinsteadoftheend.Thetailutilitystilldisplaystotheendofthefile,
eventhoughitstartscountingfromthebeginning.Thustailn+5causes
tailtodisplayfromthefifthlinethroughthelastlineofthefile.
quiet qSuppressesheaderinformationwhenyouspecifymultiplefilesinfile-list.
sleep-interval=n
sn
Whenusedwithf,causestailtosleepfornsecondsbetweenchecks
foradditionaloutput.
Notes
Thetailutilitydisplaysthelasttenlinesofitsinputbydefault.
Examples
Theexamplesarebasedontheelevenfile:
$cateleven
lineone
linetwo
linethree
linefour
linefive
linesix
lineseven
lineeight
linenine
lineten
lineeleven
Firsttaildisplaysthelasttenlinesoftheelevenfile(nooptions):
$taileleven
linetwo
linethree
linefour
linefive
linesix
lineseven
lineeight
linenine
lineten
lineeleven
Nextitdisplaysthelastthreelines(lines3)ofthefile:
$tail--lines3eleven
linenine
lineten
lineeleven
Thefollowingexampledisplaysthefilestartingatline8(+8):
$tail-n+8eleven
lineeight
linenine
lineten
lineeleven
Thenextexampledisplaysthelastsixcharactersinthefile(bytes6).Onlyfivecharactersareevident
(leven);thesixthisaNEWLINE.
$tail--bytes6eleven
leven
Thefinalexampledemonstratesthefoption.Heretailtrackstheoutputofamakecommand,whichis
beingsenttothefileaccounts.out:
$makeaccounts>accounts.out&
$tail-faccounts.out
cc-ctrans.c
cc-creports.c
...
CONTROL-C
$
Intheprecedingexample,usingtailwithfhasthesameeffectasrunningmakeintheforegroundand
lettingitsoutputgototheterminal.However,usingtailofferssomeadvantages.First,theoutputof
makeissavedinafile.(Theoutputwouldnotbesavedifyouletitgototheterminal.)Second,ifyou
decidetodosomethingelsewhilemakeisrunning,youcankilltailandthescreenwillbefreeforyou
tousewhilemakecontinuesinthebackground.Whenyouarerunningalargejob,suchascompilinga
largeprogram,youcanusetailwiththefoptiontocheckonitsprogressperiodically.
tar:Storesorretrievesfilesto/fromanarchivefile
taroption[modifiers][file-list]
Thetar(tapearchive)utilitycreates,addsto,lists,andretrievesfilesfromanarchivefile.
Arguments
Thefile-listisalistofpathnamesofthefilesthattararchivesorextracts.
Options
Useonlyoneofthefollowingoptionstoindicatewhattypeofactionyouwanttartotake.Youcanalter
theactionoftheoptionbyfollowingitwithoneormoremodifiers.
create c
Createsanarchive.Thisoptionstoresthefilesnamedinfile-listinanew
archive.Ifthearchivealreadyexists,itisdestroyedbeforethenewarchive
iscreated.Ifafile-listargumentisadirectory,tarrecursivelycopiesthe
fileswithinthedirectoryintothearchive.Withoutthefileoption,thearchive
issenttostandardoutput.
compare d(diff)Comparesanarchivewiththecorrespondingdiskfilesandreportson
thedifferences.
help Displaysalistofoptionsandmodifiers,withshortdescriptionsofeach.
append r
Writesthefilesnamedinfile-listtotheendofthearchive.Thisoption
leavesfilesthatarealreadyinthearchiveintact,soduplicatecopiesoffiles
mayappearinthearchiveaftertarfinishes.Whentarextractsthefiles,
themostrecentcopyofafileinthearchiveistheonethatendsuponthe
disk.
list t
(tableofcontents)Withoutafile-list,thisoptionproducesatableof
contentslistingallfilesinanarchive.Withafile-list,itdisplaysthenameof
eachfileinthefile-listeachtimeitoccursinthearchive.Youcanusethis
optionwiththeverboseoptiontodisplaydetailedinformationabouteachfile
inanarchive.
update u
Addsthefilesfromfile-listiftheyarenotalreadyinthearchiveorifthey
havebeenmodifiedsincetheywerelastwrittentothearchive.Becauseof
theadditionalcheckingrequired,tarrunsmoreslowlywhenyouspecify
thisoption.
extract x
Extractsfile-listfromthearchiveandwritesittothedisk.Overwrites
existingfileswiththesamenames.Withoutafile-listthisoptionextractsall
filesfromthearchive.Ifthefile-listincludesadirectory,tarextractsthat
directoryandallthefilesbelowit.Thetarutilityattemptstokeepthe
owner,modificationtime,andaccessprivilegesthesameasthoseofthe
originalfile.Iftarreadsthesamefilemorethanonce,thelastversionread
willappearonthediskwhentarisfinished.
Modifiers
Youcanspecifyoneormoremodifiersfollowinganoption.Ifyouusethesingle-characterformofthe
modifier,aleadinghyphenisnotrequired.Ingeneral,itisagoodpracticetousethehyphenunlessyou
combinethemodifierwithothersingle-charactermodifiers.
Ifamodifiertakesanargument,thatmodifiermustbethelastoneinagroup.Forexample,thearguments
arearrangedlegallyinthefollowingtarcommand:
$tar-cb10-f/dev/ftapememos
Conversely,thefollowingtarcommandgeneratesanerror:
$tar-cbf10/dev/ftapememos
tar:f:Invalidblockingfactor
Try'tar--help'formoreinformation.
Theerroroccursbecausethebmodifiertakesanargumentbutisnotthelastmodifierinagroup.
blocking-factor=n
bn
Usesnastheblockingfactorforcreatinganarchive.Usethis
optiononlywhentariscreatinganarchivedirectlytoatape.
(Whentarreadsatapearchive,itautomaticallydeterminesthe
blockingfactor.)Thevalueofnisthenumberof512-byteblocks
towriteasasingleblockonthetape.
directory=dir Cdir
Changestheworkingdirectorytodirbeforeprocessing.
checkpoint Displaysperiodicmessages.Thisoptionletsyouknowtaris
runningwithoutdisplayingalltheverbosemessages.
file=filename ffilename
Usesfilenameasthenameofthefile(device)toholdthearchive.
Thefilenamecanbethenameofanordinaryfileoradevice(such
asatapedrive).Youcanuseahyphen()insteadofthefilenameto
refertostandardinputwhencreatinganarchiveandtostandard
outputwhenextractingfilesfromanarchive.Thefollowingtwo
commandsareequivalentwaysofcreatingacompressedarchive
ofthefilesunderthe/homedirectoryon/dev/st0:
$tar-zcf/dev/st0/home
$tar-cf-/home|gzip>/dev/st0
dereference hArchivesthefilesthatsymboliclinkspointto,notthelinks
themselves.
exclude=file
Doesnotprocessthefilenamedfile.Iffileisadirectory,nofiles
ordirectorieswithinthatdirectoryareprocessed.Thefilecanbe
anambiguousfilereference;quotespecialcharactersasneeded.
ignore-failed-read
Whencreatinganarchive,tarnormallyquitswithanonzeroexitstatus
ifanyofthefilesinfile-listisunreadable.Thisoptioncausestarto
continueprocessing,skippingunreadablefiles.
bzip jUsesbzip2(page56)tocompress/decompressfileswhencreatingan
archiveandextractingfilesfromanarchive.
one-file-system
l
(lowercase"l")Whenadirectorynameappearsinfile-listwhilecreating
anarchive,tarrecursivelyprocessesthefilesanddirectoriesbelowthe
nameddirectory.Withthisoptiontarstaysinthefilesystemthat
containsthenameddirectoryanddoesnotprocessdirectoriesinother
filesystems.
tapelength=n
Ln
Asksforanewtapeafterwritingn*1,024bytestothecurrenttape.
Thisfeatureisusefulwhenyouarebuildingarchivesthataretoobigto
fitonasingletape.
touch m
Setsthemodificationtimeofextractedfilestothetimeofextraction.
Withoutthisoptiontarattemptstomaintainthemodificationtimeofthe
originalfile.
absolute-paths
P
Thedefaultbehavioroftaristoforceallpathnamestoberelativepaths
bystrippingleadingslashes.Thisoptiondisablesthisfeature,soabsolute
pathnamesremainasabsolutepaths.
sparse S
Linuxallowsyoutohavesparsefilesthatis,large,mostlyemptyfileson
disk.Theemptysectionsofsparsefilesdonottakeupanydiskspace.
Whentarcopiesasparsefileoutofanarchive,itnormallyexpandsthe
filetoitsfullsize.Asaresult,whenyourestoreasparsefilefromatar
backup,thefiletakesupitsfullspaceandmaynolongerfitinthesame
diskspaceastheoriginal.Thisoptioncausestartohandlesparsefiles
efficientlysothattheydonottakeupunnecessaryspaceeitherinthe
archiveorwhentheyareextracted.
verbose v
Listseachfileastarreadsorwritesit.Whencombinedwiththet
option,vcausestartodisplayamoredetailedlistingofthefilesinthe
archive,showingtheirownership,permissions,size,andother
information.
interactiveor
confirmation w
Asksyouforconfirmationbeforereadingorwritingeachfile.Respond
withyifyouwanttartotaketheaction.Anyotherresponsecauses
tarnottotaketheaction.
exclude-from=filename
Xfilename
Similartotheexcludeoptionexceptthatfilenamespecifiesafilethat
containsalistoffilestoexcludefromprocessing.Eachfilelistedin
filenamemustappearonaseparateline.
gziporgunzip z
Causestartousegziptocompressanarchivewhileitisbeingcreated
andtodecompressanarchivewhenextractingfilesfromit.Thisoption
alsoworkstoextractfilesfromarchivesthathavebeencompressed
withthecompressutility.
compress
oruncompress ZUsescompresswhencreatinganarchiveanduncompresswhen
extractingfilesfromanarchive.
Notes
Thehelpoptiondisplaysallthetaroptionsandmodifiers.Theinfopageontarprovidesextensive
information,includingatutorial.
Youcanuseambiguousfilereferencesinfile-listwhenyoucreateanarchivebutnotwhenyouextract
filesfromanarchive.
Thenameofadirectoryfilewithinthefile-listreferencesallfilesandsubdirectorieswithinthat
directory.
Thefilethattarsendsitsoutputtobydefaultiscompilationspecific;typicallyitgoestostandard
output.Usethefoptiontospecifyadifferentfilenameordevicetoholdthearchive.
Whenyoucreateanarchiveusingasimplefilenameinfile-list,thefileappearsintheworkingdirectory
whenyouextractit.Ifyouusearelativepathnamewhenyoucreateanarchive,thefileappearswiththat
relativepathname,startingfromtheworkingdirectorywhenyouextractit.IfyouusethePoptionandan
absolutepathnamewhenyoucreateanarchive,tarextractsthefilewiththesamepathname.
Examples
Thefollowingexamplemakesacopyofthe/home/alexdirectoryhierarchyonafloppytapedevice.The
vmodifiercausesthecommandtolistthefilesitwritestothetape.Thiscommanderasesanythingthat
wasalreadyonthetape.Themessagefromtarexplainsthatthedefaultactionistostoreallpathnames
asrelativepathsinsteadofabsolutepaths,therebyallowingyoutoextractthefilesintoadifferent
directoryonthedisk.
$tar-cvf/dev/ftape/home/alex
tar:Removingleading'/'frommembernames.
home/alex/
home/alex/.bash_history
home/alex/.bash_profile
...
Inthenextexample,thesamedirectoryissavedonthetapedevice/dev/st0withablockingfactorof100.
Withoutthevmodifier,tardoesnotdisplaythelistoffilesitiswritingtothetape.Thecommandrunsin
thebackgroundanddisplaysanymessagesaftertheshellissuesanewprompt.
$tar-cb100-f/dev/st0/home/alex&
[1]4298
$tar:Removingleading'/'frommembernames.
Thenextcommanddisplaysthetableofcontentsofthearchiveontapedevice/dev/ftape:
$tar-tvf/dev/ftape
drwxrwxrwxalex/group0Jun3021:392004home/alex/
-rw-r--r--alex/group678Aug614:122005
home/alex/.bash_history
-rw-r--r--alex/group571Aug614:062005
home/alex/.bash_profile
drwx------alex/group0Nov622:342005home/alex/mail/
-rw-------alex/group2799Nov622:342005home/alex/mail/sent-
mail
...
Inthelastexample,Alexcreatesagzippedtararchivein/tmp/alex.tgz.Thisapproachisapopular
waytobundlefilesthatyouwanttotransferoveranetworkorotherwisesharewithothers.Endinga
filenamewith.tgzisoneconventionforidentifyinggzippedtararchives.Anotherconventionistoend
thefilenamewith.tar.z.
$tar-czf/tmp/alex.tgzliterature
Thenextcommandliststhefilesinthecompressedarchivealex.tgz:
$tar-tzvf/tmp/alex.tgz
...
tee:Copiesstandardinputtostandardoutputandoneor
morefiles
tee[options]file-list
Theteeutilitycopiesstandardinputtostandardoutputandtooneormorefiles.
Arguments
Thefile-listisalistofthepathnamesoffilesthatreceiveoutputfromtee.
Options
Withoutanyoptions,teeoverwritestheoutputfilesiftheyexistandrespondstointerrupts.Ifafilein
file-listdoesnotexist,teecreatesit.
append aAppendsoutputtoexistingfilesratherthanoverwritingthem.
ignore-interrupts
iCausesteenottorespondtointerrupts.
Examples
Inthefollowingexample,apipesendstheoutputfrommaketotee,whichcopiesittostandardoutput
andthefileaccounts.out.Thecopythatgoestostandardoutputappearsonthescreen.Thecatutility
displaysthecopythatwassenttothefile:
$makeaccounts|teeaccounts.out
cc-ctrans.c
cc-creports.c
...
$cataccounts.out
cc-ctrans.c
cc-creports.c
...
Refertopage787forasimilarexamplethatusestailfratherthantee.
telnet:Connectstoaremotesystemoveranetwork
telnet[options][remote-system]
ThetelnetutilityimplementstheTELNETprotocoltoconnecttoaremotesystemoveranetwork.
security:telnetisnotsecure
Thetelnetutilityisnotsecure.Itsendsyourusernameandpasswordoverthenetwork
ascleartext,whichisnotasecurepractice.Usessh(page773)whenitisavailable.
Arguments
Theremote-systemisthenameorIPaddressoftheremotesystemthattelnetconnectsto.Whenyou
donotspecifyaremote-system,telnetworksinteractivelyandpromptsyoutoenteroneofthe
commandsdescribedinthissection.
Options
ec
(escape)ChangestheescapecharacterfromCONTROL-]tothecharacterc.
KPreventsautomaticlogin.
lusername
Attemptsanautomaticloginontheremotesystemusingusername.Iftheremotesystem
understandshowtohandleautomaticloginwithtelnet,youarepromptedfora
password.
Discussion
Aftertelnetconnectstoaremotesystem,youcanputtelnetincommandmodebytypingtheescape
character(usuallyCONTROL-]).Aremotesystemshouldreporttheescapecharacteritrecognizes.To
leavecommandmode,typeRETURNonalinebyitself.
Incommandmodetelnetdisplaysthetelnet>prompt.Youcanusethefollowingcommandsin
commandmode:
?(help)Displaysalistofcommandsrecognizedbythetelnetutilityonthe
localsystem.
close
Closestheconnectiontotheremotesystem.Ifyouspecifiedthenameofa
systemonthecommandlinewhenyoustartedtelnet,closehasthesame
effectasquit:Thetelnetprogramquits,andtheshelldisplaysaprompt.
Ifyouusedtheopencommandinsteadofspecifyingaremotesystemon
thecommandline,closereturnstelnettocommandmode.
logout Logsyouoffoftheremotesystem;similartoclose.
openremote-computer
Ifyoudidnotspecifyaremotesystemonthecommandlineorifthe
attempttoconnecttothesystemfailed,youcanspecifythenameofa
remotesysteminteractivelywiththeopencommand.
quit Quitsthetelnetsession.
z
Suspendsthetelnetsession.Whenyoususpendasession,youreturnto
theloginshellonthelocalsystem.Toresumethesuspendedtelnet
session,typefgatashellprompt.
Notes
Manycomputers,includingnon-Linuxsystems,supporttheTELNETprotocol.Thetelnetutilityisa
userinterfacetothisprotocolforLinuxsystemsthatallowsyoutoconnecttomanydifferenttypesof
systems.Althoughyoutypicallyusetelnettologin,theremotecomputermayofferotherservices
throughtelnet,suchasaccesstospecialdatabases.
Examples
Inthefollowingexample,theuserconnectstotheremotesystemnamedbravo.Afterrunningafew
commands,theuserescapestocommandmodeandusesthezcommandtosuspendthetelnetsession
soastorunafewcommandsonthelocalsystem.Theusergivesanfgcommandtotheshelltoresume
usingtelnet.Thelogoutcommandontheremotesystemendsthetelnetsession,andthelocalshell
displaysaprompt.
kudos%telnetbravo
Trying192.168.0.55...
Connectedtobravo.
Escapecharacteris'^]'.
FedoraCoreRelease2(Tettnang)
Kernel2.6.5-1.358onani686
login:watson
Password:
Lastlogin:WedJul3110:37:16fromkudos
bravo$
...
bravo$CONTROL-]
telnet>z
[1]+Stoppedtelnetbravo
kudos$
...
kudos$fg
telnetbravo
bravo$logout
Connectionclosedbyforeignhost.
kudos$
test:Evaluatesanexpression
testexpression
[expression]
Thetestutilityevaluatesanexpressionandreturnsaconditioncodeindicatingthattheexpressionis
eithertrue(0)orfalse(not0).Youcanplacebrackets([])aroundtheexpressioninsteadofusingthe
wordtest(secondformat).
Arguments
Theexpressioncontainsoneormorecriteria(seethefollowinglist)thattestevaluates.Aaseparating

twocriteriaisaBooleanANDoperator:Bothcriteriamustbetruefortesttoreturnaconditioncode
oftrue.AoisaBooleanORoperator.Whenoseparatestwocriteria,oneortheother(orboth)ofthe
criteriamustbetruefortesttoreturnaconditioncodeoftrue.
Youcannegateanycriterionbyprecedingitwithanexclamationpoint(!).Youcangroupcriteriawith
parentheses.Iftherearenoparentheses,atakesprecedenceovero,andtestevaluatesoperatorsof
equalprecedencefromlefttoright.
Withintheexpressionyoumustquotespecialcharacters,suchasparentheses,sothattheshelldoesnot
interpretthembutratherpassesthemtotest.
Becauseeachelement,suchasacriterion,string,orvariablewithintheexpression,isaseparate
argument,youmustseparateeachelementfromotherelementswithaSPACE.TableV-25liststhecriteria
youcanusewithintheexpression.TableV-26liststest'srelationaloperators.
TableV-25.Criteria
Criterion Meaning
String Trueifstringisnotanullstring.
nstring Trueifstringhasalengthgreaterthanzero.
zstring Trueifstringhasalengthofzero.
string1=string2 Trueifstring1isequaltostring2.
string1!=string2 Trueifstring1isnotequaltostring2.
int1relopint2
Trueifintegerint1hasthespecifiedalgebraicrelationshiptointeger
int2.TherelopisarelationaloperatorfromTableV-26.Asaspecial
case,lstring,whichgivesthelengthofstring,maybeusedfor
int1orint2.
file1effile2 Trueiffile1andfile2havethesamedeviceandinodenumbers.
file1ntfile2 Trueiffile1wasmodifiedafterfile2(themodificationtimeoffile1
isnewerthanthatoffile2).
file1otfile2 Trueiffile1wasmodifiedbeforefile2(themodificationtimeof
file1isolderthanthatoffile2).
bfilename Trueifthefilenamedfilenameexistsandisablockspecialfile.
cfilename Trueifthefilenamedfilenameexistsandisacharacterspecialfile.
dfilename Trueifthefilenamedfilenameexistsandisadirectory.

efilename Trueifthefilenamedfilenameexists.
ffilename Trueifthefilenamedfilenameexistsandisanordinaryfile.
gfilename Trueifthefilenamedfilenameexistsanditssetgidbit(page94)is
set.
Gfilename
Trueifthefilenamedfilenameexistsandisassociatedwiththe
groupthatistheprimarygroupoftheuserrunningthecommand
(sameeffectivegroupID).
kfilename Trueifthefilenamedfilenameexistsanditsstickybit(page903)
isset.
Lfilename Trueifthefilenamedfilenameexistsandisasymboliclink.
Ofilename Trueifthefilenamedfilenameexistsandisownedbytheuser
runningthecommand(sameeffectiveuserID).
pfilename Trueifthefilenamedfilenameexistsandisanamedpipe.
rfilename Trueifthefilenamedfilenameexistsandyouhavereadpermission
forit.
sfilename Trueifthefilenamedfilenameexistsandcontainsinformation(has
asizegreaterthan0bytes).
tfile-descriptor
Trueiffile-descriptorisassociatedwiththescreen/keyboard.The
file-descriptorforstandardinputis0,forstandardoutputis1,and
forstandarderroris2.
ufilename Trueifthefilenamedfilenameexistsanditssetuidbit(page94)is
set.
wfilename Trueifthefilenamedfilenameexistsandyouhavewrite
permissionforit.
xfilename Trueifthefilenamedfilenameexistsandyouhaveexecute
permissionforit.
TableV-26.Relationaloperators
Relop Meaning
eq Equalto
ge Greaterthanorequalto

gt Greaterthan
le Lessthanorequalto
lt Lessthan
ne Notequalto
Notes
ThetestcommandisbuiltintotheBourneAgainandTCShells.
Examples
ThefollowingexamplesdemonstratetheuseofthetestutilityinBourneAgainShellscripts.Although
testworksfromacommandline,itismorecommonlyemployedinshellscriptstotestinputorverify
accesstoafile.
Thefirstexamplepromptstheuser,readsalineofinputintoavariable,andusesthesynonymfortest,[
],toseewhethertheuserenteredyes:
$catuser_in
echo-n"Inputyesorno:"
readuser_input
if["$user_input"="yes"]
then
echoYouinputyes.
fi
Thenextexamplepromptsforafilenameandthenusesthesynonymfortest,[],toseewhethertheuser
hasreadaccesspermission(r)forthefileand(a)whetherthefilecontainsinformation(s):
$catvalidate
echo-n"Enterfilename:"
readfilename
if[-r"$filename"-a-s"$filename"]
then
echoFile$filenameexistsandcontainsinformation.
echoYouhavereadaccesspermissiontothefile.
fi
Thet1criterioncheckswhethertheprocessrunningtestissendingstandardoutputtothescreen.Ifit
is,thetestutilityreturnsavalueoftrue(0).Theshellstorestheexitstatusofthelastcommanditranin
the$?variable.Thefollowingscripttestswhetheritsoutputisgoingtoaterminal:
$catterm
test-t1
echo"Thisprogramis(=0)orisnot(=1)
sendingitsoutputtoaterminal:"$?
Firsttermisrunwiththeoutputgoingtotheterminal:
$term
Thisprogramis(=0)orisnot(=1)
sendingitsoutputtoaterminal:0
Thenextexamplerunstermandredirectstheoutputtoafile.Thecontentsofthefiletempshowthat
testreturned1,indicatingthatitsoutputwasnotgoingtoaterminal.
$term>temp
$cattemp
Thisprogramis(=0)orisnot(=1)
sendingitsoutputtoaterminal:1
top:Dynamicallydisplaysprocessstatus
top[options]
Thetoputilitydisplaysinformationaboutthestatusofthelocalsystemincludinginformationabout
currentprocesses.
Options
Althoughtopdoesnotrequiretheuseofhyphenswithoptions,itisagoodideatoincludethemfor
clarityandconsistencywithotherutilities.Youcancausetoptorunasthoughyouhadspecifiedanyof
theoptionsbygivingcommandstotheutilitywhileitisrunning.See"Discussion"formoreinformation.
dss.tt
(delay)Specifiesss.ttasthenumberofsecondsandtenthsofsecondsofdelayfromone
displayupdatetothenext.Thedefaultis3seconds.
iIgnoresidleandzombieprocesses.(Azombieprocessisonewithoutaparent.)
nn
(number)Specifiesthenumberofiterations:topupdatesthedisplayntimesandexits.

pn
(PID)MonitorstheprocesswithaPIDofn.Youcanusethisoptionupto20timesona
commandlineorspecifynasacomma-separatedlistofupto20PIDnumbers.
s(secure)Runstopinsecuremode,restrictingcommandsthatyoucanusewhiletopis
runningtothosethatposelesssecurityrisk.
S
(sum)Causestoptorunincumulativemode.Incumulativemode,theCPUtimes
reportedforprocessesincludeCPUtimesaccumulatedbychildprocessesthatarenow
dead.
Discussion
Thefirstfewlinesthattopdisplayssummarizethestatusofthelocalsystem.Youcanturneachofthese
linesonoroffwiththetoggleswitches(interactivecommandkeys)specifiedinthefollowing
descriptions.Thefirstlineisthesameastheoutputoftheuptimeutilityandshowsthecurrenttime,the
amountoftimethelocalsystemhasbeenrunningsinceitwaslastbooted,thenumberofusersloggedin,
andtheloadaveragesfromthelast1,5,and15minutes(togglel[lowercase"l"]).Thesecondline
indicatesthenumberofprocessesthatarecurrentlyrunning(togglet).ThenextthreelinesreportonCPU
(alsotogglet),memory(togglem),andswapspace(alsotogglem)use.
Therestofthedisplayreportsonindividualprocesses,listedindescendingorderbycurrentCPUusage
(themostCPU-intensiveprocessislistedfirst).Bydefaulttopdisplaysthenumberofprocessesthatfit
onthescreen.
TableV-27describesthemeaningsofthefieldsdisplayedforeachprocess.
TableV-27.Fieldnames
Name Meaning
PID Processidentificationnumber
USER Usernameoftheowneroftheprocess
PR Priorityoftheprocess
NI nicevalue(seepage734)
VIRT Numberofkilobytesofvirtualmemoryusedbytheprocess
RES Numberofkilobytesofphysical(nonswapped)memoryusedbytheprocess

SHR Numberofkilobytesofsharedmemoryusedbytheprocess
SStatusoftheprocess(seeSTATonpage748)
%CPU PercentageofthetotalCPUtimethattheprocessisusing
%MEM Percentageofphysicalmemorythattheprocessisusing
TIME[+] TotalCPUtimeusedbytheprocess
COMMAND Commandlinethatstartedtheprocessornameoftheprogram(togglewith
c)
Whiletopisrunning,youcanusethefollowingcommandstomodifyitsbehavior.Someofthese
commandsaredisabledwhenyouruntopinsecuremode(soption).
h(help)Displaysasummaryofthecommandsyoucanusewhiletopisrunning.
k
(kill)Allowsyoutokillaprocess.UnlessyouareSuperuser,youcankillonlyprocesses
youown.Whenyouusethiscommand,toppromptsyouforthePIDoftheprocessand
thesignaltosendtotheprocess.Youcanentereitherasignalnumberorname.(See
Table11-5onpage494foralistofsignals.)Thiscommandisdisabledinsecuremode.
n
(number)Whenyougivethiscommand,topasksyoutoenterthenumberofprocesses
youwantittodisplay.Ifyouenter0(thedefault)topshowsasmanyprocessesasfit
onthescreen.
q(quit)Terminatestop.
r
(renice)Changesthepriorityofarunningprocess(refertoniceonpage734).Unless
youareSuperuser,youcanchangethepriorityofonlyyourownprocessesandeven
thenonlytolowertheprioritybyenteringapositivevalue.Superusercanenteranegative
value,increasingthepriorityoftheprocess.Thiscommandisdisabledinsecuremode.
s
(seconds)Promptsyouforthenumberofsecondstodelaybetweenupdatestothe
display(3isthedefault).Youmayenteraninteger,afraction,or0(forcontinuous
updates).Thiscommandisdisabledinsecuremode.
S(switch)Switchestopbackandforthbetweencumulativemodeandregularmode.See
theSoptionfordetails.
W(write)Writestop'scurrentconfigurationtoyourpersonalconfigurationfile(~/.toprc).
SPACE
Refreshesthescreen.
Notes
Thetoputilityissimilartopsbutperiodicallyupdatesthedisplay,enablingyoutowatchthebehavior
ofthelocalsystemovertime.
Thisutilityshowsonlyasmuchofthecommandlineforeachprocessasfitsonaline.Ifaprocessis
swappedout,topreplacesthecommandlinewiththenameofthecommandinparentheses.
Thetoputilityusestheprocfilesystem:Whenprocisnotmounted,topdoesnotwork.
Requestingcontinuousupdatesisalmostalwaysamistake.Thedisplayupdatestooquicklyandthe
systemloadincreasesdramatically.
Examples
Thefollowingdisplayistheresultofatypicalexecutionoftop:
top-23:30:31up18days,30min,6users,loadaverage:0.08,
0.07,0.01
Tasks:125total,1running,124sleeping,0stopped,0zombie
Cpu(s):0.9%us,0.7%sy,0.0%ni,98.4%id,0.0%wa,0.0%hi,
0.0%si
Mem:1037272ktotal,1023048kused,14224kfree,126684k
buffers
Swap:2048248ktotal,0kused,2048248kfree,382612k
cached
PIDUSERPRNIVIRTRESSHRS%CPU%MEMTIME+COMMAND
2029root150227m96m132mS0.49.5192:12.51X
2214sam1503472820m29mS0.42.0351:08.69kdeinit
14314sam1602273612m18mS0.21.30:07.83gaim
15476sam16027609321620R0.20.10:00.93top
1root16018364641316S0.00.00:06.74init
2root3419000S0.00.00:00.01
ksoftirqd/0
3root5-10000S0.00.00:00.65events/0
4root5-10000S0.00.00:00.01
kblockd/0
6root5-10000S0.00.00:00.06khelper
5root150000S0.00.00:00.00khubd
7root150000S0.00.00:03.36pdflush
10root11-10000S0.00.00:00.00aio/0
9root150000S0.00.00:17.85kswapd0
touch:Changesafile'saccessand/ormodificationtime
touch[options]file-list
Thetouchutilitychangestheaccessand/ormodificationtimeofafiletothecurrenttimeoratimeyou
specify.
Arguments
Thefile-listisalistofthepathnamesofthefilesthattouchwillupdate.
Options
Acceptsthecommonoptionsdescribedonpage587.Withoutanyoptionstouchchangestheaccessand
modificationtimestothecurrenttime.Whenyoudonotspecifytheno-createoption,touchcreates
filesthatdonotexist.
time=atimeor
time=access aUpdatestheaccesstimeonly,leavingthemodificationtime
unchanged.
nocreate cDoesnotcreatefilesthatdonotexist.
date=datestring
ddatestring
Updatestimeswiththedatespecifiedbydatestring.Mostfamiliar
formatsarepermittedfordatestring.Componentsofthedateandtime
notincludedindatestringareassumedtobethecurrentdateandtime.
Thisoptionmaynotbeusedwitht.
time=mtimeortime=modify
mUpdatesthemodificationtimeonly,leavingtheaccesstime
unchanged.
reference=file rfile
Updatestimeswiththetimesoffile.
t[[cc]yy]nnddhhmm[.ss]
Changestimestothedatespecifiedbytheargument.Thennisthe
numberofthemonth(0112),ddisthedayofthemonth(0131),hhis
thehourbasedona24-hourclock(0023),andmmistheminutes
(0059).Youmustspecifyatleastthesefields.Youcanspecifythe
numberofsecondspastthestartoftheminutewith.ss.
Theoptionalccspecifiesthefirsttwodigitsoftheyear(thevalueof
thecenturyminus1),andyyspecifiesthelasttwodigitsoftheyear.
Whenyoudonotspecifyayear,touchassumesthecurrentyear.
Whenyoudonotspecifycc,touchassumes20foryyintherange
068and19foryyintherange6999.
Thisoptionmaynotbeusedwithd.
Examples
Thefirstthreecommandsshowtouchupdatinganexistingfile.Thelsutilitywiththeloptiondisplays
themodificationtimeofthefile.Thelastthreecommandsshowtouchcreatingafile.
$ls-lprogram.c
-rw-r--r--1alexgroup5860Apr2109:54program.c
$touchprogram.c
$ls-lprogram.c
-rw-r--r--1alexgroup5860Aug1319:01program.c
$ls-lread.c
ls:read.c:Nosuchfileordirectory
$touchread.c
$ls-lread.c
-rw-rw-r--1alexgroup0Aug1319:01read.c
Thenextexampledemonstratestheuseoftheaoptiontochangetheaccesstimeonlyandthedoptionto
specifyadatefortouchtouseinsteadofthecurrentdateandtime.Thefirstlscommanddisplaysthe
filemodificationtimes;thesecondls(withthetime=atimeoption)displaysfileaccesstimes.Inthis
casethetouchcommanddoesnothavetheintendedeffect:Theaccesstimesofthefilescasesand
excerptsarechangedto7:00onthecurrentdateandthreeunwantedfilesarecreated.Becausethedate
wasnotquoted(bysurroundingitwithdoublequotationmarks),touchassumedthat7:00wentwiththe
doptionandcreatedthepm,Jul,and30files.
$ls-l
-rw-rw-r--1alexgroup45Nov302005cases
-rw-rw-rw-1alexgroup14Jan82006excerpts
$ls-l--time=atime
-rw-rw-r--1alexgroup45Jul1719:47cases
-rw-rw-rw-1alexgroup14Jul1719:47excerpts
$touch-a-d7:00pmJul30casesexcerpts
$ls-l
-rw-rw-r--1alexgroup0Aug1112:2330
-rw-rw-r--1alexgroup0Aug1112:23Jul
-rw-rw-r--1alexgroup45Nov302005cases
-rw-rw-rw-1alexgroup14Jan82006excerpts
-rw-rw-r--1alexgroup0Aug1112:23pm
$ls-l--time=atime
-rw-rw-r--1alexgroup0Aug1107:0030
-rw-rw-r--1alexgroup0Aug1107:00Jul
-rw-rw-r--1alexgroup45Aug1107:00cases
-rw-rw-rw-1alexgroup14Aug1107:00excerpts
-rw-rw-r--1alexgroup0Aug1107:00pm
Thefinalexampleisthesameastheprecedingonebutcorrectlyenclosesthedatewithindoublequotation
marks.Afterthetouchcommandisexecuted,lsshowsthattheaccesstimesofthefilescasesand
excerptshavebeenupdatedasexpected:
$ls-l
-rw-rw-r--1alexgroup45Nov302005cases
-rw-rw-rw-1alexgroup14Jan82006excerpts
$ls-l--time=atime
-rw-rw-r--1alexgroup45Jul1719:47cases
-rw-rw-rw-1alexgroup14Jul1719:47excerpts
$touch-a-d"7:00pmJul30"casesexcerpts
$ls-l
-rw-rw-r--1alexgroup45Nov302005cases
-rw-rw-rw-1alexgroup14Jan82006excerpts
$ls-l--time=atime
-rw-rw-r--1alexgroup45Jul3019:00cases
-rw-rw-rw-1alexgroup14Jul3019:00excerpts
tr:Replacesspecifiedcharacters
tr[options]string1[string2]

Thetrutilityreadsstandardinputand,foreachinputcharacter,mapsittoanalternatecharacter,deletes
thecharacter,orleavesthecharacteralone.Thisutilityreadsfromstandardinputandwritestostandard
output.
Arguments
Thetrutilityistypicallyusedwithtwoarguments,string1andstring2.Thepositionofeachcharacter
inthetwostringsisimportant:Eachtimetrfindsacharacterfromstring1initsinput,itreplacesthat
characterwiththecorrespondingcharacterfromstring2.
Withoneargument,string1,andthedeleteoption,trdeletesthecharactersspecifiedinstring1.The
optionsqueeze-repeatsreplacesmultiplesequentialoccurrencesofcharactersinstring1withsingle
occurrences(forexample,abbcbecomesabc).
Ranges
Arangeofcharactersissimilarinfunctiontoacharacterclasswithinaregularexpression(page829).
GNUTRdoesnotsupportranges(characterclasses)enclosedwithinbrackets.Youcanspecifyarangeof
charactersbyfollowingthecharacterthatappearsearlierinthecollatingsequencewithahyphenandthen
thecharacterthatcomeslaterinthecollatingsequence.Forexample,16expandsto123456.Althoughthe
rangeAZexpandsasyouwouldexpectinASCII,thisapproachdoesnotworkwhenyouusetheEBCDIC
collatingsequence,asthesecharactersarenotsequentialinEBCDIC.See"CharacterClasses"fora
solutiontothisissue.
CharacterClasses
ATRcharacterclassisnotthesameasdescribedelsewhereinthisbook.(GNUdocumentationusesthe
termlistoperatorforwhatthisbookcallsacharacterclass.)Youspecifyacharacterclassas
'[:class:]',whereclassisacharacterclassfromTableV-28.Youmustspecifyacharacterclassin
string1unlessyouareperformingcaseconversion(see"Examples"laterinthissection)orareusingthe
dandsoptionstogether.
TableV-28.Characterclasses
Class Meaning
alnum Lettersanddigits
alpha Letters
blank Whitespace

cntrl CONTROLcharacters
digit Digits
graph PrintablecharactersbutnotSPACEs
lower Lowercaseletters
print PrintablecharactersincludingSPACEs
punct Punctuationcharacters
space Horizontalorverticalwhitespace
upper Uppercaseletters
xdigit Hexadecimaldigits
Options
complement cComplementsstring1,causingTRtomatchall
charactersexceptthoseinstring1.
delete d
Deletescharactersthatmatchthosespecifiedinstring1.
Ifyouusethisoptionwiththesqueeze-repeatsoption,
youmustspecifybothstring1andstring2(see"Notes").
help SummarizeshowtouseTR,includingthespecial
symbolsyoucanuseinstring1andstring2.
squeeze-repeats
s
Replacesmultiplesequentialoccurrencesofacharacter
instring1withasingleoccurrenceofthecharacter
whenyoucallTRwithonlyonestringargument.Ifyou
usebothstring1andstring2,thetrutilityfirst
translatesthecharactersinstring1tothoseinstring2
andthenreducesmultiplesequentialoccurrencesof
charactersinstring2.
truncate-set1 t
Truncatesstring1soitisthesamelengthasstring2
beforeprocessinginput.
Notes
Whenstring1islongerthanstring2,theinitialportionofstring1(equalinlengthtostring2)isusedin
thetranslation.Whenstring1isshorterthanstring2,trusesthelastcharacterofstring1toextend
string1tothelengthofstring2.InthiscasetrdepartsfromthePOSIXstandard,whichdoesnotdefinea
result.
Ifyouusethedeleteandsqueeze-repeatsoptionsatthesametime,trdeletesthecharactersinstring1
andthenreducesmultiplesequentialoccurrencesofcharactersinstring2.
Examples
Youcanuseahyphentorepresentarangeofcharactersinstring1orstring2.Thetwocommandlinesin
thefollowingexampleproducethesameresult:
$echoabcdef|tr'abcdef''xyzabc'
xyzabc
$echoabcdef|tr'a-f''x-za-c'
xyzabc
Thenextexampledemonstratesapopularmethodfordisguisingtext,oftencalledROT13(rotate13)
becauseitreplacesthefirstletterofthealphabetwiththethirteenth,thesecondwiththefourteenth,andso
forth.
$echoThepunchlineofthejokeis...|
>tr'A-MN-Za-mn-z''N-ZA-Mn-za-m'
Gurchapuyvarbsgurwbxrvf...
Tomakethetextintelligibleagain,reversetheorderoftheargumentstotr:
$echoGurchapuyvarbsgurwbxrvf...|
>tr'N-ZA-Mn-za-m''A-MN-Za-mn-z'
Thepunchlineofthejokeis...
Thedeleteoptioncausestrtodeleteselectedcharacters:
$echoIfyoucanreadthis,youcanspotthemissingvowels!|
>tr--delete'aeiou'
Ifycnrdths,ycnsptthmssngvwls!
Inthefollowingexample,TRreplacescharactersandreducespairsofidenticalcharacterstosingle
characters:
$echotennessee|tr-s'tnse''srne'
serene
Thenextexamplereplaceseachsequenceofnonalphabeticcharacters(thecomplementofallthe
alphabeticcharactersasspecifiedbythecharacterclassalpha)inthefiledraft1withasingleNEWLINE
character.Theoutputisalistofwords,oneperline.
$tr--complement--squeeze-repeats'[:alpha:]''\n'<draft1
Thenextexampleusescharacterclassestoupshiftthestringhithere:
$echohithere|tr'[:lower:]''[:upper:]'
HITHERE
tty:Displaystheterminalpathname
tty[option]
Thettyutilitydisplaysthepathnameofstandardinputifitisaterminalanddisplaysnotattyifitisnot
aterminal.Theexitstatusis0ifstandardinputisaterminaland1ifitisnot.
Arguments
Therearenoarguments.
Options
Acceptsthecommonoptionsdescribedonpage587.
silentorquiet sCausesttynottoprintanything.Theexitstatusofttyis
set.
Notes
Thetermttyisshortforteletypewriter,theterminaldeviceonwhichUNIXwasfirstrun.Thiscommand
appearsinUNIX,andLinuxhaskeptitforthesakeofconsistencyandtradition.
Examples
Thefollowingexampleillustratestheuseoftty:
$tty
/dev/pts/11
$echo$?
0
$tty<memo
notatty
$echo$?
1
tune2fs:Changesparametersonanext2orext3filesystem
tune2fs[options]device
Thetune2fsutilitydisplaysandmodifiesfilesystemparametersonext2filesystemsandonext3
filesystems,whicharemodifiedext2filesystems.Thisutilitycanalsosetupjournalingonanext2
filesystem,turningitintoanext3filesystem.Withtypicalfilesystempermissions,tune2fsmustberun
asroot.
Arguments
Thedeviceisthenameofthedevice,suchas/dev/hda8,thatholdsthefilesystemwhoseparametersyou
wanttodisplayormodify.
Options
cn
(count)Setsthemaximumnumberoftimesthefilesystemcanbemountedbetween
filesystemcheckston.Setnto0(zero)todisregardthisparameter.
Cn
(count)Setsthenumberoftimesthefilesystemhasbeenmountedwithoutbeing
checkedton.Thisoptionisusefulforstaggeringfilesystemchecks(see
"Discussion")andforforcingacheckthenexttimethesystemboots.
ebehavior
(error)Specifieswhatthekernelwilldowhenitdetectsanerror.Setbehaviorto
continue(continuesexecution),remount-ro(remountsthefilesystemreadonly),or
panic(causesakernelpanic).Regardlessofhowyousetthisoption,anerrorwill
causefscktocheckthefilesystemnexttimethesystemboots.
in[u]
(interval)Setsthemaximumtimebetweenfilesystemcheckstontimeperiods.
Withoutuorwithusettod,thetimeperiodisdays.Setutowtosetthetimeperiod
toweeks;mformonths.Setnto0(zero)todisregardthisparameter.Becausea
filesystemcheckisforcedonlywhenthesystemisbootedthetimespecifiedbythis
optionmaybeexceeded.
j(journal)Addsanext3journaltoanext2filesystem.Formoreinformationreferto
"journalingfilesystem"onpage883.
l(list)Listsinformationaboutthefilesystem.
Tdate
(time)Setsthetimethefilesystemwaslastcheckedtodate.Thedateisthetimeand
dateintheformatyyymmdd[hh[mm]ss]]].Heremmisthenumberofthemonth
(0112)andddisthedayofthemonth(0131).Youmustspecifyatleastthesefields.
Thehhisthehourbasedona24-hourclock(0023),mmistheminutes(0059),and
.ssisthenumberofsecondspastthestartoftheminute.Youcanalsospecifydateas
now.
Discussion
Checkingalargefilesystemcantakealongtime.UsetheCand/orToptionstostaggerfilesystemchecks
sotheydonotallhappenatthesametime.Whenallthefilesystemchecksoccuratthesametimeitcan
takealongtimeforthesystemtoboot.
Examples
Followingistheoutputoftune2fsrunwiththeloptiononatypicalext3filesystem:
#/sbin/tune2fs-l/dev/hda2
tune2fs1.35(28-Feb-2004)
Filesystemvolumename:/p04
Lastmountedon:<notavailable>
FilesystemUUID:125be803-2f51-53ef-dfcf-292bf7e4ecc4
Filesystemmagicnumber:0xEF53
Filesystemrevision#:1(dynamic)
Filesystemfeatures:has_journalfiletypeneeds_recovery
sparse_super
Defaultmountoptions:(none)
Filesystemstate:clean
Errorsbehavior:Continue
FilesystemOStype:Linux
Inodecount:2562240
Blockcount:5120718
Reservedblockcount:256035
Freeblocks:3194303
Freeinodes:2554160
Firstblock:0
Blocksize:4096
Fragmentsize:4096
Blockspergroup:32768
Fragmentspergroup:32768
Inodespergroup:16320
Inodeblockspergroup:510
Filesystemcreated:SatMay1715:22:292003
Lastmounttime:SunJan3023:00:372005
Lastwritetime:SunJan3023:00:372005
Mountcount:5
Maximummountcount:30
Lastchecked:ThuDec201:02:462004
Checkinterval:15552000(6months)
Nextcheckafter:TueMay3102:02:462005
Reservedblocksuid:0(userroot)
Reservedblocksgid:0(grouproot)
Firstinode:11
Inodesize:128
Journalinode:8
Defaultdirectoryhash:tea
DirectoryHashSeed:81345bv8-740d-4af5-c5bc-12033ed7c121
Journalbackup:inodeblocks
umask:Establishesthefile-creationpermissionsmask
umask[mask]
Theumaskbuiltinspecifiesamaskthatthesystemusestosetaccesspermissionswhenyoucreateafile.
Thisbuiltinworksslightlydifferentlyineachoftheshells.
Arguments
Themaskcanbeathree-digitoctalnumber(bashandtcsh)orasymbolicvalue(bash)suchasyou
wouldusewithchmod(page604).Themaskspecifiesthepermissionsthatarenotallowed.
Whenmaskisanoctalnumber,thedigitscorrespondtothepermissionsfortheownerofthefile,
membersofthegroupthefileisassociatedwith,andeveryoneelse.Becausethemaskspecifiesthe
permissionsthatarenotallowed,thesystemsubtractseachofthesedigitsfrom7whenyoucreateafile.
Theresultingthreeoctalnumbersspecifytheaccesspermissionsforthefile(thenumbersyouwoulduse
withchmod).Amaskthatyougiveasasymbolicvaluealsospecifiesthepermissionsthatarenot
allowed.See"Notes."
Withoutanyarguments,umaskdisplaysthefile-creationpermissionsmask.
Notes
Mostutilitiesandapplicationsdonotattempttocreatefileswithexecutepermissions,regardlessofthe
valueofmask;theyassumethatyoudonotwantanexecutablefile.Asaresult,whenautilityor
applicationsuchastouchcreatesafile,thesystemsubtractseachofthedigitsinmaskfrom6.An
exceptionoccurswithmkdir,whichdoesassumethatyouwanttheexecute(accessinthecaseofa
directory)bitset.See"Examples."
Theumaskprogramisabuiltininbashandtcshandgenerallygoesintheinitializationfilefor
yourshell(~/.bash_profile[bash]or~/.login[tcsh]).
Underbashtheargumentg=r,o=rturnsonthewritebitinthemaskforgroupsandotherusers(themask
is0033),causingthosebitstobeoffinfilepermissions(744or644).Refertochmodonpage604for
moreinformationaboutsymbolicpermissions.
Examples
Thefollowingcommandssetthefile-creationpermissionsmaskanddisplaythemaskanditseffectwhen
youcreateafileandadirectory.Themaskof022,whensubtractedfrom777,givespermissionsof644
(rwrr)forafileand755(rwxrxrx)foradirectory:
$umask022
$umask
022
$touchafile
$mkdiradirectory
$ls-ldafileadirectory
drwxr-xr-x2maxmax4096Jul2411:25adirectory
-rw-r--r--1maxmax0Jul2411:25afile
Thenextexamplesetsthesamemaskvaluesymbolically:
$umaskg=rx,o=rx
$umask
022
uniq:Displaysuniquelines
uniq[options][input-file][output-file]
Theuniqutilitydisplaysitsinput,removingallbutonecopyofsuccessiverepeatedlines.Ifthefilehas
beensorted(seesortonpage762),uniqensuresthatnotwolinesthatitdisplaysarethesame.
Arguments
Whenyoudonotspecifytheinput-file,uniqreadsfromstandardinput.Whenyoudonotspecifythe
output-file,uniqwritestostandardoutput.
Options
Acceptsthecommonoptionsdescribedonpage587.Afieldisasequenceofcharactersboundedby
SPACEs,TABs,NEWLINEs,oracombinationofthesecharacters.
count cPrecedeseachlinewiththenumberofoccurrencesofthelineinthe
inputfile.
repeated dDisplaysonecopyoflinesthatarerepeated;doesnotdisplaylines
thatarenotrepeated.
skip-fields=nfield
fnfield
Ignoresthefirstnfieldblank-separatedfieldsofeachline.Theuniq
utilitybasesitscomparisonontheremainderoftheline,includingthe
leadingblanksofthenextfieldontheline(seetheskip-charsoption).
ignore-case iIgnorescasewhencomparinglines.
skip-chars=nchar
snchar
Ignoresthefirstncharcharactersofeachline.Ifyoualsousethe
skip-fieldsoption,uniqignoresthefirstnfieldfieldsfollowedby
ncharcharacters.Youcanusethisoptiontoskipoverleadingblanks
ofafield.
unique uDisplaysonlylinesthatarenotrepeated.
check-chars=nchar
wnchar
Comparesuptoncharscharactersonaline
afterhonoringtheskip-fieldsandskip-chars
options.Bydefaultuniqcomparestheentire
line.
Examples
Theseexamplesassumethatthefilenamedtestintheworkingdirectorycontainsthefollowingtext:
$cattest
boytookbathome
boytookbathome
girltookbathome
dogbroughthathome
dogbroughthathome
dogbroughthathome
Withoutanyoptions,uniqdisplaysonlyonecopyofsuccessiverepeatedlines:
$uniqtest
boytookbathome
girltookbathome
dogbroughthathome
Thecountoptiondisplaysthenumberofconsecutiveoccurrencesofeachlineinthefile:
$uniq--counttest
2boytookbathome
1girltookbathome
3dogbroughthathome
Therepeatedoptiondisplaysonlylinesthatareconsecutivelyrepeatedinthefile.
$uniq--repeatedtest
boytookbathome
dogbroughthathome
Theuniqueoptiondisplaysonlylinesthatarenotconsecutivelyrepeatedinthefile:
$uniq--uniquetest
girltookbathome
Nexttheskip-fieldsoptionskipsthefirstfieldineachline,causingthelinesthatbeginwithboyandthe
onethatbeginswithgirltoappeartobeconsecutiverepeatedlines.Theuniqutilitydisplaysonlyone
occurrenceoftheselines:
$uniq--skip-fields=1test
boytookbathome
dogbroughthathome
Thenextexampleusesboththef(skip-fields)ands(skip-chars)argumentsfirsttoskiptwofieldsand
thentoskiptwocharacters.ThetwocharactersthiscommandskipsincludetheSPACEthatseparatesthe
secondandthirdfieldsandthefirstcharacterofthethirdfield.Ignoringthesecharacters,allthelines
appeartobeconsecutiverepeatedlinescontainingthestringathome.Theuniqutilitydisplaysonlythe
firstoftheselines:
$uniq-f2-s2test
boytookbathome
w:Displaysinformationaboutsystemusers
w[options][username]
Thewutilitydisplaysthenamesofuserswhoarecurrentlyloggedin,togetherwiththeirterminaldevice
numbers,thetimestheyloggedin,thecommandstheyarerunning,andotherinformation.
Options
f(from)RemovestheFROMcolumn.Foruserswhoaredirectlyconnected,thisfield
containsahyphen.
h(noheader)Suppressestheheaderline.
s(short)Displayslessinformation:username,terminaldevice,idletime,and
command.
Arguments
Theusernamerestrictsthedisplaytoinformationaboutthatuser.
Discussion
Thefirstlinethatwdisplaysisthesameasthatdisplayedbyuptime.Thislineincludesthetimeofday,
howlongthesystemhasbeenrunning(indays,hours,andminutes),howmanyusersareloggedin,and
howbusythesystemis(loadaverage).Fromlefttoright,theloadaveragesindicatethenumberof
processesthathavebeenwaitingtoruninthepast1minute,5minutes,and15minutes.
Thecolumnsofinformationthatwdisplayshavethefollowingheadings:
USERTTYFROMLOGIN@IDLEJCPUPCPUWHAT
TheUSERistheusernameoftheuser.TheTTYisthedevicenameforthelinethattheuserison.The
FROMisthesystemnamethataremoteuserisloggedinfrom;itisahyphenforalocaluser.The
LOGIN@givesthedateandtimetheuserloggedin.TheIDLEindicateshowmanyminuteshave
elapsedsincetheuserlastusedthekeyboard.TheJCPUistheCPUtimeusedbyallprocessesattached
totheuser'stty,notincludingcompletedbackgroundjobs.ThePCPUisthetimeusedbytheprocess
namedintheWHATcolumn.TheWHATisthecommandthatuserisrunning.
Examples
Thefirstexampleshowsthefulllistproducedbythewutility:
$w
10:26amup1day,55min,6users,loadaverage:0.15,0.03,0.01
USERTTYFROMLOGIN@IDLEJCPUPCPUWHAT
alextty1-Fri9am20:39m0.22s0.01svim
td
alextty2-Fri5pm17:16m0.07s0.07s-
bash
rootpts/1-Fri4pm14:28m0.20s0.07s-
bash
jennypts/2-Fri5pm3:230.08s0.08s
/bin/bash
hlspts/3potato10:07am0.00s0.08s0.02sw
Thenextexampleshowsthesoptionproducinganabbreviatedlisting:
$w-s
10:30amup1day,58min,6users,loadaverage:0.15,0.03,0.01
USERTTYFROMIDLEWHAT
alextty1-20:43mvimtd
alextty2-17:19m-bash
rootpts/1-14:31m-bash
jennypts/2-0.20svimmemo.030125
hlspts/3potato0.00sw-s
ThefinalexamplerequestsinformationonlyaboutAlex:
$walex
10:35amup1day,1:04,6users,loadaverage:0.06,0.01,0.00
USERTTYFROMLOGIN@IDLEJCPUPCPUWHAT
alextty1-Fri9am20:48m0.22s0.01svim
td
alextty2-Fri5pm17:25m0.07s0.07s-
bash
wc:Displaysthenumberoflines,words,andbytes
wc[options][file-list]
Thewcutilitydisplaysthenumberoflines,words,andbytesinitsinput.Whenyouspecifymorethanone
fileonthecommandline,wcdisplaystotalsforeachfileaswellastotalsforthegroupoffiles.
Arguments
Thefile-listisalistofthepathnamesofoneormorefilesthatwcanalyzes.Whenyouomitfile-list,the
wcutilitytakesitsinputfromstandardinput.
Options
Acceptsthecommonoptionsdescribedonpage587.
bytes cDisplaysonlythenumberofbytesintheinput.
lines l(lowercase"l")Displaysonlythenumberoflines(thatis,NEWLINE
characters)intheinput.
max-line-length
LDisplaysthelengthofthelongestlineintheinput.
chars mDisplaysonlythenumberofcharactersintheinput.
words wDisplaysonlythenumberofwordsintheinput.
Notes
AwordisasequenceofcharactersboundedbySPACEs,TABs,NEWLINEs,oracombinationofthese
characters.
Examples
Thefollowingcommandanalyzesthefilenamedmemo.Thenumbersintheoutputrepresentthenumber
oflines,words,andbytesinthefile:
$wcmemo
531146memo
Thenextcommanddisplaysthenumberoflinesandwordsinthreefiles.Thelineatthebottom,withthe
wordtotalintherightcolumn,containsthesumofeachcolumn.
$wc-lwmemo1memo2memo3
1062memo1
1274memo2
1268memo3
34204total
which:ShowswhereinPATHacommandislocated
whichcommand-list
Foreachcommandincommand-list,thewhichutilitysearchesthedirectoriesinthePATHvariable
(page284)anddisplaystheabsolutepathnameofthefirstfileitfindswhosesimplefilenameisthesame
asthecommand.
Arguments
Thecommand-listisalistofoneormorecommands(utilities)thatwhichsearchesfor.Foreach
commandwhichsearchesthedirectorieslistedinthePATHenvironmentvariable,inorder,and
displaysthefullpathnameofthefirstcommand(executablefile)itfinds.Ifwhichdoesnotlocatea
command,itdisplaysamessage.
Options
all aDisplaysallmatchingexecutablefilesinPATH,notjustthefirst.
read-alias iReadsaliasesfromstandardinputandreportsonmatchingaliasesin
additiontoexecutablefilesinPATH(turnoffwithskip-alias).
read-functions
Readsshellfunctionsfromstandardinputandreportsonmatching
functionsinadditiontoexecutablefilesinPATH(turnoffwithskip-
functions).
show-dot
Displays./inplaceoftheabsolutepathnamewhenadirectoryinPATH
startswithaperiodandamatchingexecutablefileisinthatdirectory
(turnoffwithskip-dot).
show-tilde
Displaysatilde(~)inplaceoftheabsolutepathnameoftheuser'shome
directorywhereappropriate.ThisoptionisignoredwhenSuperuserruns
which.
tty-only Donotprocessmoreoptions(totherightofthisoption)iftheprocess
runningwhichisnotattachedtoaterminal.
Notes
Manydistributionsdefineanaliasforwhichsuchasthefollowing:
$aliaswhich
aliaswhich='alias|/usr/bin/which--tty-only--read-alias--show-
dot--show-tilde'
Ifwhichisnotbehavingasyouwouldexpect,verifythatyouarenotrunninganalias.Thepreceding
aliascauseswhichtobeeffectiveonlywhenitisruninteractively(tty-only)andtodisplayaliases,
displaytheworkingdirectoryasaperiodwhenappropriate,anddisplaythenameoftheuser'shome
directoryasatilde.
TheTCShellincludesawhichbuiltin(seethetcshmanpage)thatworksslightlydifferentlyfromthe
whichutility(/usr/bin/which).Withoutanyoptionsthewhichutilitydoesnotlocatealiases,functions,
andshellbuiltinsbecausethesedonotappearinPATH.Incontrastthetcshwhichbuiltinlocates
aliases,functions,andshellbuiltins.
Examples
Thefirstexamplequotesthefirstletterofthecommand(\which)topreventtheshellfrominvokingthe
alias(page313)forwhich:
$\whichvimdirwhich
/usr/bin/vim
/usr/bin/dir
/usr/bin/which
Thenextexampleisthesameasthefirstbutusesthealiasforwhich(whichitdisplays):
$whichvimdirwhich
aliaswhich='alias|/usr/bin/which--tty-only--read-alias--show-
dot--show-tilde'
/usr/bin/which
/usr/bin/vim
/usr/bin/dir
Thefinalexampleisthesameasthepreviousoneexceptthatitisrunfromtcsh.Thetcshwhich
builtinisusedinsteadofthewhichutility:
tcsh$whichvimdirwhich
/usr/bin/vim
/usr/bin/dir
which:shellbuilt-incommand.
who:Displaysinformationaboutlogged-inusers
who[options]
whoami
Thewhoutilitydisplaysinformationaboutuserswhoareloggedinonthelocalsystem.Thisinformation
includeseachuser'susername,terminaldevice,logintime,and,ifapplicable,thecorrespondingremote
hostnameorXdisplay.
Arguments
Whengiventwoarguments(traditionally,ami),whodisplaysinformationabouttheusergivingthe
command.Ifapplicable,theusernameisprecededbythehostnameofthesystemrunningwho(asin
kudos!alex).
Options
Acceptsthecommonoptionsdescribedonpage587.
all aDisplaysalotofinformation.
boot bDisplaysthedateandtimethesystemwaslastbooted.
heading HDisplaysaheader.
login l(lowercase"l")Listsdeviceswaitingforausertologin.
count q(quick)Liststheusernamesonly,followedbythenumberofuserslogged
inonthesystem.
messageor
mesg T
Appendsaftereachuser'susernameacharacterthatshowswhetherthat
userhasmessagesenabled.Aplus(+)meansthatmessagesareenabled,a
hyphen()meansthattheyaredisabled,andaquestionmark(?)indicates
thatwhocannotfindthedevice.Ifmessagesareenabled,youcanuse
writetocommunicatewiththeuser.Referto"mesg:DeniesorAccepts
Messages"onpage68.
users u
Includeseachuser'sidletimeinthedisplay.Iftheuserhastypedonher
terminalinthepastminute,aperiod(.)appearsinthisfield.Ifnoinputhas
occurredformorethanaday,thewordoldappears.Inaddition,thisoption
includesthePIDnumberandcommentfields.See"Discussion."
Discussion
Thelinethatwhodisplayshasthefollowingsyntax:
user[messages]linelogin-time[idle][PID]comment
Theuseristheusernameoftheuser.Themessagesindicateswhethermessagesareenabledordisabled
(seethemessageoption).Thelineisthedevicenameassociatedwiththelinetheuserisloggedinon.
Thelogin-timeisthedateandtimethattheuserloggedin.Theidleisthelengthoftimesincetheterminal
waslastused(theidletime;seetheidleoption).ThePIDistheprocessidentificationnumber.The
commentistheremotesystemorXdisplaythattheuserisloggedinfrom(blankforlocalusers).
Notes
Thefingerutility(page661)providesinformationsimilartothatgivenbywho.
Examples
Thefollowingexamplesdemonstratetheuseofthewhoutility:
$who
hlstty1Jul3006:01
jennytty2Jul3006:02
alexttyp3Jul3014:56(bravo)
$whoami
bravo!alexttyp3Jul3014:56(bravo)
$who--heading--users-T
USERLINETIMEIDLEPIDCOMMENT
hls-tty1Jul3006:0103:531821
jenny+tty2Jul3006:0214:472235
alex+ttyp3Jul3014:56.14777(bravo)
xargs:Convertsstandardinputintocommandlines
xargs[options][command]
Thexargsutilityisaconvenient,efficientwaytoconvertstandardoutputofonecommandinto
argumentsforanothercommand.Thisutilityreadsfromstandardinput,keepstrackofthemaximum
allowablelengthofacommandline,andavoidsexceedingthatlimitbyrepeatingcommandasneeded.
Finallyxargsexecutestheconstructedcommandline.
Arguments
Thecommandisthecommandlineyouwantxargstouseasabaseforthecommanditconstructs.If
youomitcommand,itdefaultstoecho.Thexargsutilityappendstocommandtheargumentsit
receivesfromstandardinput.Ifanyargumentsshouldprecedetheargumentsfromstandardinput,you
mustincludethemaspartofcommand.
Options
replace[=marker]
i[marker]
Allowsyoutoplaceargumentsfromstandardinputanywherewithin
command.Alloccurrencesofmarkerincommandforxargsare
replacedbytheargumentsgeneratedfromstandardinputofxargs.If
youomitmarker,itdefaultstothestring{},whichmatchesthe
syntaxusedinthefindcommandexecoption.Withthisoption
commandisexecutedforeachinputline;themax-linesoptionis
ignoredwhenyouusereplace.
maxlines[=num]
l[num]
(lowercase"l")Executescommandonceforeverynumlinesofinput
(numdefaultsto1).
maxargs=num
nnum
Executescommandonceforeverynumargumentsintheinputline.
interactive pPromptstheuserpriortoeachexecutionofcommand.
maxprocs=num
Pnum
Allowsxargstorunuptomaxprocsinstancesofcommand
simultaneously.(Thedefaultis1,whichrunscommandssequentially.)
ThisoptionmayimprovethethroughputifyouarerunningLinuxona
multiprocessorsystem.
norunifempty
r
Causesxargsnottoexecutecommandifstandardinputisempty.
Ordinarilyxargsexecutescommandatleastonce,evenifstandard
inputincludesonlyblanks.
Discussion
Thexargsutilityreadsargumentstocommandfromstandardinput,interpretingeachwhitespace-
delimitedstringasaseparateargument.Itthenconstructsacommandlinefromcommandandaseriesof
arguments.Whenthemaximumcommandlinelengthwouldbeexceededbyaddinganotherargument,
xargsrunsthecommandlineithasbuilt.Ifthereismoreinput,xargsrepeatstheprocessofbuildinga
commandlineandrunningit.Thisprocesscontinuesuntilallinputhasbeenread.
Notes
Onecommonuseofxargsisasanefficientalternativetotheexecoptionoffind(page656).Ifyou
callfindwiththeexecoptiontorunacommand,itrunsthecommandonceforeachfileitprocesses.
Eachexecutionofthecommandcreatesanewprocess,whichcandrainsystemresourceswhenyouare
processingmanyfiles.Byaccumulatingasmanyargumentsaspossible,xargscangreatlyreducethe
numberofprocessesneeded.Thefirstexampleinthe"Examples"sectionshowshowtousexargswith
find.
Thereplaceoptionchangeshowxargshandleswhitespaceinstandardinput.Withoutthisoption
xargstreatssequencesofblanks,TABS,andNEWLINESasequivalent.Withthisoptionxargs
TReatsNEWLINEcharactersinaspecialway.IfitencountersaNEWLINEinstandardinputwhenusing
thereplaceoption,xargsrunscommandusingtheargumentlistthathasbeenbuiltuptothatpoint.
Examples
Tolocateandremoveallfileswhosenamesendin.ofromtheworkingdirectoryanditssubdirectories,
youcanusethefindexecoption:
$find.-name\*.o-execrm--force{}\;
Thisapproachcallsthermutilityonceforeach.ofilethatfindlocates.Eachinvocationofrmrequires
anewprocess.Ifalotof.ofilesexist,asignificantamountoftimeisspentcreating,starting,andthen
cleaninguptheseprocesses.Youcanreducethenumberofprocessesbyallowingxargstoaccumulate
asmanyfilenamesaspossiblebeforecallingrm:
$find.-name\*.o-print|xargsrm--force
Inthenextexample,thecontentsofall*.txtfileslocatedbyfindaresearchedforlinescontainingthe
wordlogin.Allfilenamesthatcontainloginaredisplayedbygrep.
$find.-name\*.txt-print|xargsgrep-w-llogin
Thenextexampleshowshowyoucanusethereplaceoptiontocausexargstoembedstandardinput
withincommandinsteadofappendingittocommand.Thisoptionalsocausescommandtobeexecuted
eachtimeaNEWLINEcharacterisencounteredinstandardinput;max-linesdoesnotoverridethis
behavior.
$catnames
Tom,
Dick,
andHarry
$xargsecho"Hello,"<names
Hello,Tom,Dick,andHarry
$xargs--replaceecho"Hello{}.Joinmeforlunch?"<names
HelloTom,.Joinmeforlunch?
HelloDick,.Joinmeforlunch?
HelloandHarry.Joinmeforlunch?
Thefinalexampleusesthesameinputfileasthepreviousexampleaswellasthemax-argsandmax-
linesoptions:
$xargsecho"Hithere"<names
HithereTom,Dick,andHarry
$xargs--max-args=1echo"Hithere"<names
HithereTom,
HithereDick,
Hithereand
HithereHarry
$xargs--max-lines=2echo"Hithere"<names
HithereTom,Dick,
HithereandHarry
AppendixA.RegularExpressions
INTHISAPPENDIX
Characters828
Delimiters828
SimpleStrings828
SpecialCharacters828
Rules831
BracketingExpressions832
TheReplacementString833
ExtendedRegularExpressions834
Aregularexpressiondefinesasetofoneormorestringsofcharacters.Asimplestringofcharactersisa
regularexpressionthatdefinesonestringofcharacters:itself.Amorecomplexregularexpressionuses
letters,numbers,andspecialcharacterstodefinemanydifferentstringsofcharacters.Aregular
expressionissaidtomatchanystringitdefines.
Thisappendixdescribestheregularexpressionsusedbyed,vim,emacs,grep,gawk,sed,andother
utilities.Theregularexpressionsusedinshellambiguousfilereferencesaredifferentandaredescribed
in"FilenameGeneration/PathnameExpansion"onpage127.
Characters
Asusedinthisappendix,acharacterisanycharacterexceptaNEWLINE.Mostcharactersrepresent
themselveswithinaregularexpression.Aspecialcharacterisonethatdoesnotrepresentitself.Ifyou
needtouseaspecialcharactertorepresentitself,youmustquoteitasexplainedonpage831.
Delimiters
Acharactercalledadelimiterusuallymarksthebeginningandendofaregularexpression.Thedelimiter
isalwaysaspecialcharacterfortheregularexpressionitdelimits(thatis,itdoesnotrepresentitselfbut
marksthebeginningandendoftheexpression).Althoughvimpermitstheuseofothercharactersasa
delimiterandgrepdoesnotusedelimitersatall,theregularexpressionsinthisappendixuseaforward
slash(/)asadelimiter.Insomeunambiguouscases,theseconddelimiterisnotrequired.Forexample,
youcansometimesomittheseconddelimiterwhenitwouldbefollowedimmediatelybyRETURN.

SimpleStrings
Themostbasicregularexpressionisasimplestringthatcontainsnospecialcharactersexceptthe
delimiters.Asimplestringmatchesonlyitself(TableA-1).Intheexamplesinthisappendix,thestrings
thatarematchedareunderlinedandlooklikethis.
TableA-1.Simplestrings
Regularexpression Matches Examples
/ring/ ring ring,spring,ringing,stringing
/Thursday/ Thursday Thursday,Thursday's
/ornot/ ornot ornot,poornothing

SpecialCharacters
Youcanusespecialcharacterswithinaregularexpressiontocausetheregularexpressiontomatchmore
thanonestring.Aregularexpressionthatincludesaspecialcharacteralwaysmatchesthelongestpossible
string,startingasfartowardthebeginning(left)ofthelineaspossible.
Periods
Aperiod(.)matchesanycharacter(TableA-2).
TableA-2.Period
Regularexpression Matches Examples
/.alk/ AllstringsconsistingofaSPACEfollowed
byanycharacterfollowedbyalk willtalk,maybalk
/.ing/ Allstringsconsistingofanycharacter
precedinging
singsong,ping,
beforeinglenook
Brackets
Brackets([])defineacharacterclass[1]thatmatchesanysinglecharacterwithinthebrackets(TableA-
3).Ifthefirstcharacterfollowingtheleftbracketisacaret(^),thebracketsdefineacharacterclassthat
matchesanysinglecharacternotwithinthebrackets.Youcanuseahyphentoindicatearangeof
characters.Withinacharacter-classdefinition,backslashesandasterisks(describedinthefollowing
sections)losetheirspecialmeanings.Arightbracket(appearingasamemberofthecharacterclass)can
appearonlyasthefirstcharacterfollowingtheleftbracket.Acaretisspecialonlyifitisthefirst
characterfollowingtheleftbracket.Adollarsignisspecialonlyifitisfollowedimmediatelybytheright
bracket.
[1]GNUdocumentationcallstheseListOperatorsanddefinesCharacterClassoperatorsasexpressionsthatmatchapredefined
groupofcharacters,suchasallnumbers(seeTableV-28onpage804).
TableA-3.Brackets
Regularexpression Matches Examples
/[bB]ill/ MemberofthecharacterclassbandBfollowed
byill bill,Bill,billed

/t[aeiou].k/ tfollowedbyalowercasevowel,anycharacter,
andak
talkative,stink,teak,
tanker
/#[69]/ #followedbyaSPACEandamemberofthe
characterclass6through9 #60,#8:,get#9
/[^azAZ]/ Anycharacterthatisnotaletter(ASCII
charactersetonly) 1,7,@,.,},Stop!
Asterisks
Anasteriskcanfollowaregularexpressionthatrepresentsasinglecharacter(TableA-4).Theasterisk
representszeroormoreoccurrencesofamatchoftheregularexpression.Anasteriskfollowingaperiod
matchesanystringofcharacters.(Aperiodmatchesanycharacter,andanasteriskmatcheszeroormore
occurrencesoftheprecedingregularexpression.)Acharacter-classdefinitionfollowedbyanasterisk
matchesanystringofcharactersthataremembersofthecharacterclass.
TableA-4.Asterisks
Regularexpression Matches Examples
/ab*c/ afollowedbyzeroormoreb'sfollowedby
ac
ac,abc,abbc,
debbcaabbbc
/ab.*c/ abfollowedbyzeroormorecharacters
followedbyc
abc,abxc,ab45c,
xab756.345xcat
/t.*ing/ tfollowedbyzeroormorecharacters
followedbying
thing,ting,Ithought
ofgoing
/[azAZ]*/Astringcomposedonlyoflettersand
SPACEs
1.anystringwithout
numbersor
punctuation!
/(.*)/ Aslongastringaspossiblebetween(and) Get(this)and(that);
/([^)]*)/ Theshorteststringpossiblethatstartswith
(andendswith)
(this),Get(thisand
that)
CaretsandDollarSigns

Aregularexpressionthatbeginswithacaret(^)canmatchastringonlyatthebeginningofaline.Ina
similarmanner,adollarsign($)attheendofaregularexpressionmatchestheendofaline.Thecaret
anddollarsignarecalledanchorsbecausetheyforce(anchor)amatchtothebeginningorendofaline
(TableA-5).
TableA-5.Caretsanddollarsigns
Regularexpression Matches Examples
/^T/ ATatthebeginningofaline
Thisline...,
ThatTime...,
InTime
/^+[09]/ Aplussignfollowedbyadigitatthe
beginningofaline
+5+45.72,
+759Keepthis...
/:$/ Acolonthatendsaline ...below:
QuotingSpecialCharacters
Youcanquoteanyspecialcharacter(butnotadigitoraparenthesis)byprecedingitwithabackslash
(TableA-6).Quotingaspecialcharactermakesitrepresentitself.
TableA-6.Quotedspecialcharacters
Regularexpression Matches Examples
/end\./ Allstringsthatcontainend
followedbyaperiod Theend.,send.,pretend.mail
/\\/ Asinglebackslash \
/\*/ Anasterisk *.c,anasterisk(*)
/\[5\]/ [5] itwasfive[5]
/and\/or/ and/or and/or
Rules
Thefollowingrulesgoverntheapplicationofregularexpressions.
LongestMatchPossible
Aregularexpressionalwaysmatchesthelongestpossiblestring,startingasfartowardthebeginningof
thelineaspossible.Forexample,giventhestring
This(rug)isnotwhatitoncewas(alongtimeago),isit?
theexpression/Th.*is/matches
This(rug)isnotwhatitoncewas(alongtimeago),is
and/(.*)/matches
(rug)isnotwhatitoncewas(alongtimeago)
However,/([^)]*)/matches
(rug)
Giventhestring
singingsongs,singingmoreandmore
theexpression/s.*ing/matches
singingsongs,singing
and/s.*ingsong/matches
singingsong
EmptyRegularExpressions
Withinsomeutilities,suchasvimandless(butnotgrep),anemptyregularexpressionrepresentsthe
lastregularexpressionthatyouused.Forexample,supposeyougivevimthefollowingSubstitute
command:
:s/mike/robert/
Ifyouthenwanttomakethesamesubstitutionagain,youcanusethefollowingcommand:
:s//robert/
Alternatively,youcanusethefollowingcommandstosearchforthestringmikeandthenmakethe
substitution
/mike/
:s//robert/
Theemptyregularexpression(//)representsthelastregularexpressionyouused(/mike/).
BracketingExpressions
Youcanusequotedparentheses,\(and\),tobracketaregularexpression.Thestringthatthebracketed
regularexpressionmatchescanberecalled,asexplainedin"QuotedDigit."Aregularexpressiondoes
notattempttomatchquotedparentheses.Thusaregularexpressionenclosedwithinquotedparentheses
matcheswhatthesameregularexpressionwithouttheparentheseswouldmatch.Theexpression/\(rexp\)/
matcheswhat/rexp/wouldmatch;/a\(b*\)c/matcheswhat/ab*c/wouldmatch.
Youcannestquotedparentheses.Thebracketedexpressionsareidentifiedonlybytheopening\(,sono
ambiguityarisesinidentifyingthem.Theexpression/\([az]\([AZ]*\)x\)/consistsoftwobracketed
expressions,onenestedwithintheother.Inthestring3tdMNORx7lu,theprecedingregularexpression
matchesdMNORx,withthefirstbracketedexpressionmatchingdMNORxandthesecondmatching
MNOR.
TheReplacementString
ThevimandsededitorsuseregularexpressionsassearchstringswithinSubstitutecommands.Youcan
usetheampersand(&)andquoteddigits(\n)specialcharacterstorepresentthematchedstringswithin
thecorrespondingreplacementstring.
Ampersand
Withinareplacementstring,anampersand(&)takesonthevalueofthestringthatthesearchstring
(regularexpression)matched.Forexample,thefollowingvimSubstitutecommandsurroundsastringof
oneormoredigitswithNN.Theampersandinthereplacementstringmatcheswhateverstringofdigits
theregularexpression(searchstring)matched:
:s/[0-9][0-9]*/NN&NN/
Twocharacter-classdefinitionsarerequiredbecausetheregularexpression[09]*matcheszeroormore
occurrencesofadigit,andanycharacterstringconstituteszeroormoreoccurrencesofadigit.
QuotedDigit
Withinthesearchstring,abracketedregularexpression,\(xxx\),matcheswhattheregularexpression
wouldhavematchedwithoutthequotedparentheses,xxx.Withinthereplacementstring,aquoteddigit,
\n,representsthestringthatthebracketedregularexpression(portionofthesearchstring)beginningwith
thenth\(matched.Forexample,youcantakealistofpeopleintheform
last-name,first-nameinitial
andputitintheform
first-nameinitiallast-name
withthefollowingvimcommand:
:1,$s/\([^,]*\),\(.*\)/\2\1/
Thiscommandaddressesallthelinesinthefile(1,$).TheSubstitutecommand(s)usesasearchstring
andareplacementstringdelimitedbyforwardslashes.Thefirstbracketedregularexpressionwithinthe
searchstring,\([^,]*\),matcheswhatthesameunbracketedregularexpression,[^,]*,wouldmatch:zero
ormorecharactersnotcontainingacomma(thelast-name).Followingthefirstbracketedregular
expressionareacommaandaSPACEthatmatchthemselves.Thesecondbracketedexpression,\(.*\),
matchesanystringofcharacters(thefirst-nameandinitial).
Thereplacementstringconsistsofwhatthesecondbracketedregularexpressionmatched(\2),followed
byaSPACEandwhatthefirstbracketedregularexpressionmatched(\1).

ExtendedRegularExpressions
Thethreeutilitiesegrep,grepwhenrunwiththeEoption(similartoegrep),andgawkprovideall
thespecialcharactersthatareincludedinordinaryregularexpressions,exceptfor\(and\),aswellas
severalothers.Thevimeditorincludestheadditionalcharactersaswellas\(and\).Patternsusingthe
extendedsetofspecialcharactersarecalledfullregularexpressionsorextendedregularexpressions.
Twooftheadditionalspecialcharactersaretheplussign(+)andthequestionmark(?).Theyaresimilar
to*,whichmatcheszeroormoreoccurrencesofthepreviouscharacter.Theplussignmatchesoneor
moreoccurrencesofthepreviouscharacter,whereasthequestionmarkmatcheszerooroneoccurrence.
Youcanuseanyoneofthespecialcharacters*,+,and?followingparentheses,causingthespecial
charactertoapplytothestringsurroundedbytheparentheses.Unliketheparenthesesinbracketedregular
expressions,theseparenthesesarenotquoted(TableA-7).
TableA-7.Extendedregularexpressions
Regularexpression Matches Examples
/ab+c/ afollowedbyoneormoreb's
followedbyac yabcw,abbc57
/ab?c/ afollowedbyzerooronebfollowed
byc back,abcdef
/(ab)+c/ Oneormoreoccurrencesofthe
stringabfollowedbyc zabcd,ababc!
/(ab)?c/ Zerooroneoccurrenceofthestring
abfollowedbyc xc,abcc
Infullregularexpressions,theverticalbar(|)specialcharacterisaBooleanORoperator.Withinvim,
youmustquotetheverticalbarbyprecedingitwithabackslashtomakeitspecial(\|).Averticalbar
betweentworegularexpressionscausesamatchwithstringsthatmatchthefirstexpression,thesecond
expression,orboth.Youcanusetheverticalbarwithparenthesestoseparatefromtherestoftheregular
expressionthetwoexpressionsthatarebeingORed(TableA-8).
TableA-8.Fullregularexpressions
Regularexpression Meaning Examples
/ab|ac/ Eitheraborac
ab,ac,abac(abacis
twomatchesofthe
regularexpression)

/^Exit|^Quit/ LinesthatbeginwithExitor
Quit
Exit,
Quit,
NoExit
/(D|N)\.Jones/ D.JonesorN.Jones P.D.Jones,N.Jones

AppendixSummary
Aregularexpressiondefinesasetofoneormorestringsofcharacters.Aregularexpressionissaidto
matchanystringitdefines.
Inaregularexpression,aspecialcharacterisonethatdoesnotrepresentitself.TableA-9listsspecial
characters.
TableA-9.Specialcharacters
Character Meaning
. Matchesanysinglecharacter
*Matcheszeroormoreoccurrencesofamatchofthepreceding
character
^Forcesamatchtothebeginningofaline
$Amatchtotheendofaline
\Usedtoquotespecialcharacters
\< Forcesamatchtothebeginningofaword
\> Forcesamatchtotheendofaword
TableA-10listswaysofrepresentingcharacterclassesandbracketedregularexpressions.
TableA-10.Characterclassesandbracketedregularexpressions
Class Defines
[xyz] Definesacharacterclassthatmatchesx,y,orz
[^xyz] Definesacharacterclassthatmatchesanycharacterexceptx,y,orz
[xz] Definesacharacterclassthatmatchesanycharacterxthroughz
inclusive
\(xyz\) Matcheswhatxyzmatches(abracketedregularexpression)

Inadditiontotheprecedingspecialcharactersandstrings(excludingquotedparentheses,exceptinvim),
thecharactersgiveninTableA-11arespecialwithinfull,orextended,regularexpressions.
TableA-11.Extendedregularexpressions
Expression Matches
+Matchesoneormoreoccurrencesoftheprecedingcharacter
?Matcheszerooroneoccurrenceoftheprecedingcharacter
(xyz)+ Oneormoreoccurrencesofwhatxyzmatches
(xyz)? Zerooroneoccurrenceofwhatxyzmatches
(xyz)* Zeroormoreoccurrencesofwhatxyzmatches
xyz|abc Eitherwhatxyzorwhatabcmatches(use\|in)
(xy|ab)c Eitherwhatxycorwhatabcmatches(use\|invim)
TableA-12listscharactersthatarespecialwithinareplacementstringinsedandvim.
TableA-12.Replacementstrings
String Represents
&Representswhattheregularexpression(searchstring)matched
\n Aquotednumber,n,representswhatthenthbracketedregular
expressioninthesearchstringmatched
AppendixB.Help
INTHISAPPENDIX
SolvingaProblem838
FindingLinux-RelatedInformation839
Documentation839
UsefulLinuxSites840
LinuxNewsgroups841
MailingLists841
Words841
Software842
OfficeSuitesandWordProcessors844
SpecifyingaTerminal844
Youneednotactasauserorsystemadministratorinisolation.AlargecommunityofLinuxexpertsis
willingtoassistyouinlearningabout,helpingyousolveyourproblemswith,andgettingthemostoutof
yourLinuxsystem.Beforeyouaskforhelp,however,makesureyouhavedoneeverythingyoucanto
solvetheproblembyyourself.Nodoubt,someonehasexperiencedthesameproblembeforeyouandthe
answertoyourquestioncanbefoundsomewhereontheInternet.Yourjobistofindit.Thisappendixlists
resourcesanddescribesmethodsthatcanhelpyouinthattask.

SolvingAProblem
Followingisalistofstepsthatcanhelpyousolveaproblemwithoutaskingsomeoneelseforhelp.
Dependingonyourunderstandingofandexperiencewiththehardwareandsoftwareinvolved,thesesteps
mayleadtoasolution.
1.
MostLinuxdistributionscomewithextensivedocumentation.Readthedocumentationonthespecific
hardwareorsoftwareyouarehavingaproblemwith.IfitisaGNUproduct,useinfo;otherwise,
usemantofindlocalinformation.Formoreinformationreferto"GettingtheFacts:WheretoFind
Documentation"onpage29.
2.
Whentheprobleminvolvessometypeoferrororothermessage,useasearchengine,suchasGoogle
(www.google.com)orGoogleGroups(groups.google.com),tolookupthemessageontheInternet.If
themessageislong,pickauniquepartofthemessagetosearchfor;10to20charactersshouldbe
enough.Enclosethesearchstringwithindoublequotationmarks.
3.
CheckwhethertheLinuxDocumentationProject(www.tldp.org)hasaHOWTOormini-HOWTOon
thesubjectinquestion.Searchonkeywordsthatrelatedirectlytotheproductandyourproblem.
ReadtheFAQs.
SeeTableB-1forothersourcesofdocumentation.
TableB-1.Documentation
Site Aboutthesite URL
freedesktop.org
Createsstandards
forinteroperability
betweenopen
sourcedesktop
environments.
freedesktop.org
GNOME GNOMEhome
page. www.gnome.org
GNUManuals
GNUmanuals.
GNUmanualon
info.
www.gnu.org/manual
www.gnu.org/software/texinfo/manual/info

4.
InternetFAQ
Archives
SearchableFAQ
archives.
www.faqs.org
Info
Instructionsfor
usingtheinfo
utility.
www.gnu.org/software/texinfo/manual/info
RedHat
Documentation
andSupport
Thissitehasa
searchenginethat
looksthroughthe
RedHat
Knowledgebaseto
helpansweryour
questions.Thesite
alsohaslinksto
online
documentationfor
RedHatproducts
andasection
namedQuickhelp
thatlinksto
commontopicsof
interest.
www.redhat.com/apps/support
KDE
Documentation
KDE
documentation. kde.org/documentation
KDENews KDEnews. dot.kde.org
RFCs
Requestfor
Comments;see
RFC(page898).
www.rfc-editor.org
System
Administrators
Guild(SAGE)
SAGEisagroup
forsystem
administrators.
www.sage.org
Allthingsrelated
toLinux
documentation(in
manylanguages):

TheLinux
Documentation
Project
HOWTOs,guides,
FAQs,manpages,
andmagazines.
Thisisthebest
overallsourcefor
Linux
documentation.
Makesuretovisit
itsLinkspage.
www.tldp.org
5.
UseGoogleorGoogleGroupstosearchonkeywordsthatrelatedirectlytotheproductandyour
problem.
6.
Whenallelsefails(orperhapsbeforeyoutryanythingelse)examinethesystemlogsin/var/log.
RunningasSuperuser,firstlookattheendofthemessagesfileusingthefollowingcommand:
#tail-20/var/log/messages
Ifmessagescontainsnothinguseful,runthefollowingcommand.Itdisplaysthenamesofthelogfiles
inchronologicalorder,withthemostrecentlymodifiedfilesappearingatthebottomofthelist:
$ls-ltr/var/log
Ifyourprobleminvolvesanetworkconnection,reviewthesecurelogfile(somesystemsmayusea
differentname)onthelocalandremotesystems.Alsolookatmessagesontheremotesystem.
7.
The/var/spooldirectorycontainssubdirectorieswithusefulinformation:cupsholdstheprintqueues,
mailholdstheuser'smailfiles,andsoon.
Ifyouareunabletosolveaproblemyourself,athoughtfulquestiontoanappropriatenewsgroup(page
841)ormailinglist(page841)canelicitusefulinformation.Whenyousendorpostaquestion,makesure
youdescribetheproblemandidentifythelocalsystemcarefully.Includetheversionnumbersofthe
operatingsystemandanysoftwarepackagesthatrelatetotheproblem.Describeyourhardware,if
appropriate.
Theauthor'shomepage(www.sobell.com)containscorrectionstothisbook,answerstoselectedchapter
exercises,andpointerstootherLinuxsites.

FindingLinux-RelatedInformation
DistributionsofLinuxcomewithreferencepagesstoredonline.Youcanreadthesedocumentsbyusing
theinfo(page32)orman(page30)utilities.Youcanreadmanandinfopagestogetmore
informationaboutspecifictopicswhilereadingthisbookortodeterminewhichfeaturesareavailable
withLinux.Youcansearchfortopicsbyusingapropos(seepage62orgivethecommandman
apropos).
Documentation
GoodbooksareavailableonvariousaspectsofusingandadministratingUNIXsystemsingeneraland
Linuxsystemsinparticular.Inaddition,youmayfindthesiteslistedinTableB-1useful.[1]
[1]Theright-handcolumnsofmostofthetablesinthisappendixshowInternetaddresses(URLs).Allsiteshaveanimplicithttp://
prefixunlessftp://orhttps://isshown.Referto"URLs(Webaddresses)"onpage23.
UsefulLinuxSites
SometimesthesiteslistedinTableB-2aresobusythatyoucannotlogin.Whenthishappens,youare
usuallygivenalistofalternative,ormirror,sitestotry.
TableB-2.UsefulLinuxsites
Site Aboutthesite URL
GNU GNUProjectWebserver. www.gnu.org
ibiblio Alargelibraryanddigitalarchive.Formerly
Metalab;formerlySunsite.
www.ibiblio.org
www.ibiblio.org/pub/linux
www.ibiblio.org/pub/historic-
linux
LinuxKnowledge
Portal
Aconfigurablesitethatgathersinformation
fromothersitesandsourcesandpresentsit
inawell-organizedformat.Sourcesinclude
KDENews,GNOMENews,Slashdot,and
manymore.InEnglishandGerman.
www.linux-knowledge-
portal.org
LinuxStandardBase
(LSB) AgroupdedicatedtostandardizingLinux. www.linuxbase.org
Sobell
Theauthor'shomepagecontainsuseful
links,errataforthisbook,codeformany www.sobell.com

oftheexamplesinthisbook,andanswers
toselectedexercises.
USENIX
Alarge,well-establishedUNIXgroup.This
sitehasmanylinks,includingalistof
conferences.
www.usenix.org
X.Org TheXWindowSystemhome. www.x.org
LinuxNewsgroups
Oneofthebestwaysofgettingspecificinformationisthroughanewsgroup.Frequentlyyoucanfindthe
answertoyourquestionbyreadingpostingstothenewsgroup.TryusingGoogleGroups
(groups.google.com)tosearchthroughnewsgroupstoseewhetheryourquestionhasalreadybeenasked
andanswered.Oropenanewsreaderprogramandsubscribetoappropriatenewsgroups.Ifnecessary,you
canpostyourquestionforsomeonetoanswer.Beforeyoudoso,makesureyouarepostingtothecorrect
groupandthatyourquestionhasnotbeenanswered.Thereisanetiquettetopostingquestionssee
www.catb.org/~esr/faqs/smart-questions.htmlforagoodpaperbyEricS.RaymondandRickMoentitled
"HowToAskQuestionstheSmartWay."
Thenewsgroupcomp.os.linux.answersprovidespostingsofsolutionstocommonproblemsandperiodic
postingsofthemostup-to-dateversionsoftheFAQandHOWTOdocuments.Thecomp.os.linux.misc
newsgrouphasanswerstomiscellaneousLinux-relatedquestions.
MailingLists
Subscribingtoamailinglistallowsyoutoparticipateinanelectronicdiscussion.Withmostlists,youcan
sendandreceiveemaildedicatedtoaspecifictopictoandfromagroupofusers.Moderatedlistsdonot
tendtostrayasmuchasunmoderatedlists,assumingthelisthasagoodmoderator.Thedisadvantageofa
moderatedlististhatsomediscussionsmaybecutoffwhentheygetinterestingifthemoderatordeems
thatthediscussionhasgoneonfortoolong.Mailinglistsdescribedasbulletinsarestrictly
unidirectional:Youcannotpostinformationtotheselistsbutcanonlyreceiveperiodicbulletins.Ifyou
havethesubscriptionaddressforamailinglistbutarenotsurehowtosubscribe,putthewordhelpinthe
bodyand/orheaderofemailthatyousendtotheaddress.Youwillusuallyreceiveinstructionsviareturn
email.Youcanalsouseasearchenginetosearchformailinglistlinux.
Words
Manydictionaries,thesauruses,andglossariesareavailableonline.TableB-3listsafewofthem.

TableB-3.Lookingupwords
Site Aboutthesite URL
Apt Aptinstalls,removes,andupdates
systemsoftwarepackages apt.freshrpms.net
ARTFL
Project:
ROGET'S
Thesaurus
Thesaurus humanities.uchicago.edu/forms_unrest/ROGET.html
BitTorrent BitTorrentefficientlydistributeslarge
amountsofstaticdata www.bittorrent.com
DICT.org Multipledatabasesearchforwords www.dict.org
Dictionary.com Everythingrelatedtowords www.dictionary.com
DNSGlossary DNSGlossary www.menandmice.com/online_docs_and_faq/glossary/glossarytoc.htm
FOLDOC(The
FreeOn-Line
Dictionaryof
Computing)
Computerterms www.foldoc.org
Merriam-
Webster Englishlanguage www.m-w.com
OneLook Multiple-sitewordsearchwitha
singlequery www.onelook.com
TheJargon
File
AnonlineversionofTheNew
Hacker'sDictionary www.catb.org/~esr/jargon
Webopedia Commercialtechnicaldictionary www.webopedia.com
Wikipedia Anopen-source(user-contributed)
encyclopediaproject wikipedia.org
Wordsmyth Dictionaryandthesaurus www.wordsmyth.net
Yahoo
Reference
Searchmultiplesourcesatthesame
time education.yahoo.com/reference
yum Theyumutilityinstalls,removes,and
updatessystemsoftwarepackages
linux.duke.edu/projects/yum
apt.freshrpms.net

Software
Therearemanywaystolearnaboutinterestingsoftwarepackagesandwheretheyareavailableonthe
Internet.TableB-4listssitesthatyoucandownloadsoftwarefrom.Anotherwaytolearnaboutsoftware
packagesisthroughanewsgroup(page841).
TableB-4.Software
Site Aboutthesite URL
CVS CVS(ConcurrentVersionsSystem)isaversion
controlsystem www.cvshome.org
ddd Thedddutilityisagraphicalfrontendfor
commandlinedebuggerssuchasgdb www.gnu.org/software/ddd
FreeSoftware
Directory Categorized,searchablelistsoffreesoftware
www.gnu.org/directory
savannah.gnu.org
Freshmeat AlargeindexofUNIXandcross-platform
software,themes,andPalmOSsoftware freshmeat.net
gdb Thegdbutilityisacommandlinedebugger www.gnu.org/software/gdb
GNOMEProject LinkstoallGNOMEprojects www.gnome.org/projects
IceWALKERS Categorized,searchablelistsoffreesoftware www.icewalkers.com
kdbg Thekdbgutilityisagraphicaluserinterfaceto
gdb freshmeat.net/projects/kdbg
LinuxSoftware
Map
Adatabaseofpackageswrittenfor,portedto,or
compiledforLinux www.boutell.com/lsm
linuxapps Categorized,searchablelistoffreesoftware www.linuxapps.com
Mtools
AcollectionofutilitiestoaccessDOSfloppy
diskettesfromLinuxwithoutmountingthe
diskettes
mtools.linux.lu
Network
Calculators Subnetmaskcalculator www.subnetmask.info
rpmfind.net SearchablelistofrpmfilesforvariousLinux
distributionsandversions rpmfind.net/linux/RPM
SourceForge AdevelopmentWebsitewithalargerepository
ofopen-sourcecodeandapplications sourceforge.net

strace Thestraceutilityisasystemcalltrace
debuggingtool
www.liacs.nl/~wichert/strace
sourceforge.net/projects/strace
Tucows-Linux Commercial,categorized,searchablelistof
software linux.tucows.com
ups Theupsutilityisagraphicalsource-level
debugger ups.sourceforge.net
OfficeSuitesandWordProcessors
SeveralofficesuitesandmanywordprocessorsareavailableforLinux.TableB-5listsafewofthem.If
youareexchangingdocumentswithpeopleusingWindows,makesuretheimportfrom/exporttoMSWord
functionalitycoversyourneeds.
TableB-5.Officesuitesandwordprocessors
Product
name Whatitdoes URL
AbiWord Wordprocessor(free) www.abisource.com
KOffice Integratedsuiteofofficeapplicationsincludingthe
Kwordwordprocessingprogram(free,KDE-based) www.koffice.org
OpenOffice Anopen-sourceversionofStarOffice
www.openoffice.org
www.gnome.org/projects/ooo
Xcoral Aprogrammer'smultiwindowmouse-basededitorthat
runsunderX(free) xcoral.free.fr
SpecifyingaTerminal
Becausevim,emacs,konsole,andotherprogramstakeadvantageoffeaturesthatarespecificto
variouskindsofterminalsandterminalemulators,youmusttelltheseprogramsthenameoftheterminal
youareusingortheterminalthatyourterminalemulatorisemulating.Onmanysystemsyourterminal
nameissetforyou.Ifyourterminalnameisnotspecifiedorisnotspecifiedcorrectly,yourscreenwill
lookgarbledor,whenyoustartaprogram,theprogramwillaskwhattypeofterminalyouareusing.
Terminalnamesdescribethefunctionalcharacteristicsofyourterminalorterminalemulatortoprograms
thatrequirethisinformation.AlthoughterminalnamesarereferredtoaseitherTerminfoorTermcap
names,thedifferencerelatestothemethodthateachsystemusestostoretheterminalcharacteristics
internally,notinthemannerthatyouspecifythenameofaterminal.Terminalnamesthatareoftenused
withLinuxterminalemulatorsandwithgraphicalmonitorswhiletheyarerunintextmodeareansi,linux,
vt100,vt102,vt220,andxterm.
Whenyouarerunningaterminalemulator,youcanspecifythetypeofterminalyouwanttoemulate.Set
theemulatortoeithervt100orvt220,andsetTERMtothesamevalue.
Whenyoulogin,youmaybepromptedtoidentifythetypeofterminalyouareusing:
TERM=(vt100)
Therearetwowaystorespondtothisprompt.YoucanpressRETURNtosetyourterminaltypetothe
nameinparentheses.Whenthatnamedoesnotdescribetheterminalyouareusing,youcanenterthe
correctnameandthenpressRETURN.
TERM=(vt100)ansi
Youmayalsoreceivethefollowingprompt:
TERM=(unknown)
Thispromptindicatesthatthesystemdoesnotknowwhattypeofterminalyouareusing.Ifyouplantorun
programsthatrequirethisinformation,enterthenameoftheterminalorterminalemulatoryouareusing
beforeyoupressRETURN.
TERM
Ifyoudonotreceiveaprompt,youcangivethefollowingcommandtodisplaythevalueoftheTERM
variableandcheckwhetheryourterminaltypehasbeenset:
$echo$TERM
Ifthesystemrespondswiththewrongname,ablankline,oranerrormessage,setorchangetheterminal
name.FromtheBourneAgainShell(bash),enteracommandsimilartothefollowingtosettheTERM
variablesothatthesystemknowsthetypeofterminalyouareusing:
exportTERM=name
Replacenamewiththeterminalnamefortheterminalyouareusing,makingsurethatyoudonotputa
SPACEbeforeoraftertheequalsign.Ifyoualwaysusethesametypeofterminal,youcanplacethis
commandinyour~/.bashrcfile(page257),causingtheshelltosettheterminaltypeeachtimeyoulogin.
Forexample,givethefollowingcommandtosetyourterminalnametovt100:
$exportTERM=vt100
UsethefollowingformatundertheTCShell(tcsh).
setenvTERMname
Againreplacenamewiththeterminalnamefortheterminalyouareusing.Undertcshyoucanplace
thiscommandinyour~/.loginfile(page342).Forexample,undertcshyoucangivethiscommandto
setyourterminalnametovt100:
$setenvTERMvt100
AppendixC.KeepingTheSystemUp-To-Date
INTHISAPPENDIX
yum:UpdatesandInstallsPackages848
Apt:AnAlternativetoyum850
BitTorrent855
Aptandyumbothfillthesamerole:Theyinstallandupdatesoftwarepackages.Bothutilitiescompare
thefilesinarepository(generallyontheInternet)withthoseonthelocalsystemandupdatethefileson
thelocalsystemaccordingtoyourinstructions.Bothutilitiesautomaticallyinstallandupdateany
additionalfilesthatapackageisdependenton.Aptisslightlyfaster,especiallyoverslowconnections,
anditsupportsafewmorefeatures,suchasundoingupgrades.Theyumutilityiseasiertoconfigureand
usethanApt.IfyouarefamiliarwithDebiansystemsorfindthatyumlackssomefeaturesyouneed,try
usingApt;otherwiseuseyum.TheexamplesinthissectionarefromaFedoraCoresystem;althoughthe
files,input,andoutputonyoursystemmaylookdifferent,howyouusethetoolsandtheresultswillbethe
same.
ContrastedwithAptandyum,BitTorrentefficientlydistributeslargeamountsofstaticdata,suchas
installationISOimages.Itdoesnotcheckfilesonthelocalsystemanddoesnodependencychecking.
yum:UpdatesAndInstallsPackages
EarlyreleasesofLinuxdidnotincludeatoolformanagingupdates.TheRPMtoolcouldinstallor
upgradeindividualsoftwarepackages,butitwasuptotheusertolocatethepackagesandthepackages
theyweredependenton.WhenTerraSoftproduceditsLinuxdistributionforthePowerPC,thecompany
createdtheYellowDogUpdatertofillthisgap.Thisprogramhassincebeenportedtootherarchitectures
anddistributions.Theresult,namedYellowDogUpdater,Modified(yum),isincludedwithmanyLinux
distributions.Theyumhomepageislinux.duke.edu/projects/yumandmoreinformationisavailableat
apt.freshrpms.net.
Configuringyum
Theyumutilityisdesignedtobeeasytouse.Theconfigurationfile,/etc/yum.conf,hastwoparts:The
[main]sectioncontainsgeneralsettingsandtherestofthefileholdsalistofservers.
The[main]sectionmustbepresentforyumtofunction.Thecachedirspecifiesthedirectoryyumusesto
storedownloadedpackagesandlogfilespecifieswhereyumkeepsitslog.Theamountofinformation
loggedisspecifiedbydebuglevel,withavalueof10producingthemostinformation.
$cat/etc/yum.conf
[main]
cachedir=/var/cache/yum
debuglevel=2
logfile=/var/log/yum.log
pkgpolicy=newest
distroverpkg=fedora-release
tolerant=1
exactarch=1
...
Thepkgpolicydefineswhichversionofasoftwarepackageyuminstalls;alwayssetittonewestto
installthenewestversionofapackage.Youcanalsoconfigureyumtotrytoinstallfromaspecific
server,fallingbacktootherserversonfailureandignoringpackageversions.Thedistroverpkgspecifies
whichdistributionthesystemisrunning.
Withtolerantsetto1,yumautomaticallycorrectssimplecommandlineerrors,suchasattemptingto
installapackagealreadyonthesystem.Settingtolerantto0turnsthisfeatureoff.Settingexactarchto1
causesyumtoupdatepackagesonlywithpackagesofthesamearchitecturepreventingani686package
fromreplacingani386one,forexample.
Thelastsectionscontainlistsofserversholdingupdates.Theyaremarkedwith[core],[updates],or
othersimilarlabels.Frequentlythelastsectioncontainsupdatesthatarenotreadyforreleaseandis
commentedout;donotuncommentitunlessyouaretestingunstablepackages.Neveruncommentthis
sectiononproductionsystems.Eachserversectioncontainsaname,baseurl,andgpgcheckflag:
$cat/etc/yum.conf
...
[core]
name=FedoraLinux$releasever-$basearch-core
baseurl=http://ayo.freshrpms.net/fedora/linux/$releasever/$basearch/core
gpgcheck=1
...
Thenameprovidesafriendlynamefortheserver.Thebaseurlindicatesthelocationoftheserver.Set
gpgcheckto1ifyouwantyumtocheckthegpgsignaturesofthepackagesitdownloads.Setitto0
otherwise.Thesedefinitionsusetwovariables:yumsets$basearchtothearchitectureofthesystemand
$releasevertotheversionoftherelease.Refertotheyum.confmanpageformoreoptions.
Usingyum
Workingasroot,youcanrunyumfromacommandline.Itsbehaviordependsontheoptionsyouspecify.
Theupdateoptionupdatesallinstalledpackages:Itdownloadspackageheadersforinstalledpackages,
promptsyoutoproceed,anddownloadsandinstallstheupdatedpackages.
#yumupdate
Gatheringheaderinformationfile(s)fromserver(s)
Server:FedoraCore3-i386-Base
Server:FedoraCore3-i386-ReleasedUpdates
Findingupdatedpackages
Downloadingneededheaders
getting/var/cache/yum/updates-released/headers/pango-0-
1.6.07.i386.hdr
pango-0-1.6.0-7.i386.hdr100%|=========================|6.5kB
00:00
...
[update:rhn-applet2.1.4-3.i386]
Isthisok[y/N]:y
Gettingpango-1.6.0-7.i386.rpm
pango-1.6.0-7.i386.rpm100%|=========================|341kB
00:06
...
Youcanupdateindividualpackagesbyspecifyingthenamesofthepackagesonthecommandline
followingthewordupdate.
Toinstallanewpackagetogetherwiththepackagesitisdependenton,givethecommandyuminstall
followedbythenameofthepackageasshownonthenextpage.
#yuminstalltcsh
Gatheringheaderinformationfile(s)fromserver(s)
Server:FedoraCore3-i386-Base
Server:FedoraCore3-i386-ReleasedUpdates
Findingupdatedpackages
Downloadingneededheaders
getting/var/cache/yum/base/headers/tcsh-0-6.13-9.i386.hdr
tcsh-0-6.13-9.i386.hdr100%|=======================|3.8kB
00:00
Resolvingdependencies
Dependenciesresolved
Iwilldothefollowing:
[install:tcsh6.13-9.i386]
Isthisok[y/N]:y
Gettingtcsh-6.13-9.i386.rpm
tcsh-6.13-9.i386.rpm100%|=======================|443kB
00:10
Runningtesttransaction:
Testtransactioncomplete,Success!
tcsh100%done1/1
Installed:tcsh6.13-9.i386
Transaction(s)Complete
Youcanalsouseyumtoremovepackages,usingasimilarsyntax:
#yumremovetcsh
Gatheringheaderinformationfile(s)fromserver(s)
Server:FedoraCore3-i386-Base
Server:FedoraCore3-i386-ReleasedUpdates
Findingupdatedpackages
Downloadingneededheaders
Resolvingdependencies
Dependenciesresolved
Iwilldothefollowing:
[erase:tcsh6.13-9.i386]
Isthisok[y/N]:y
Runningtesttransaction:
Testtransactioncomplete,Success!
Erasing:tcsh1/1
Erased:tcsh6.13-9.i386
Transaction(s)Complete
APT:AnAlternativeToyum
TheApt(AdvancedPackageTool)utilitycanhelpwiththeissueofdependencies:Apttriestoresolve
packagedependenciesautomaticallybylookingforthepackagesthatthepackageyouareinstallingis
dependenton.SincestartinglifeaspartoftheDebianLinuxdistributionusingDebian's.debpackage
format,Apthasbeenportedtorpm-baseddistributions.Formoreinformationgotoapt.freshrpms.net.
TheAptutilityusesrepositoriesofrpmfilesasthebasisforitsactions.Tomakethingsquicker,Apt
keepslocallyalistofpackagesthatareheldineachoftherepositoriesituses.Anysoftwareyouwantto
installorupdatemustresideinarepository.
WhenyougiveAptacommandtoinstallapackage,Aptlooksforthepackageinitslocalpackagelist.If
thepackageappearsinthelist,Aptfetchesboththatpackageandanypackagesthatthepackageyouare
installingisdependentonandcallsrpmtoinstallthepackages.BecauseAptusesrpm,itmaintainsthe
rpmdatabase.
UsingApt
ThissectiondescribeshowtoconfigureApt.
INSTALLINGANDSETTINGUPAPT
Onceyouhavedownloadedtheapt*.rpmfile,youmustinstallit(yourAptversionnumberwillbe
different):
#rpm-Uvhapt-0.5.15cnc6-1.1.fc3.fr.i386.rpm
Preparing...###########################################
[100%]
1:apt###########################################
[100%]
Updatethelocalpackagelist
TheprimaryAptcommandisapt-get;itsargumentsdeterminewhatthecommanddoes.Afteryou
installApt,givethecommandapt-getupdatetoupdatethelocalpackagelist:
#apt-getupdate
Get:1http://ayo.freshrpms.netfedora/linux/3/i386release[1991B]
Fetched1991Bin0s(4922B/s)
Get:1http://ayo.freshrpms.netfedora/linux/3/i386/corepkglist
[1445kB]
Get:2http://ayo.freshrpms.netfedora/linux/3/i386/corerelease
[151B]
Get:3http://ayo.freshrpms.netfedora/linux/3/i386/updatespkglist
[251kB]
Get:4http://ayo.freshrpms.netfedora/linux/3/i386/updatesrelease
[157B]
Get:5http://ayo.freshrpms.netfedora/linux/3/i386/freshrpmspkglist
[98kB]
Get:6http://ayo.freshrpms.netfedora/linux/3/i386/freshrpmsrelease
[161B]
Fetched1847kBin28s(64.7kB/s)
ReadingPackageLists...Done
BuildingDependencyTree...Done
Becausetheavailablepackageschangefrequently,itisagoodideatocreateacronjobtoupdatethe
localpackagelistautomatically.Createthefollowingfiletoperformthistaskdaily:
$cat/etc/cron.daily/apt-update
apt-getupdate
Checkthedependencytree
TheAptutilitydoesnottolerateabrokenrpmdependencytree.Tocheckthestatusofthelocal
dependencytree,runapt-getcheck:
#apt-getcheck
ReadingPackageLists...Done
BuildingDependencyTree...Done
Theeasiestwaytofixerrorsthatapt-getrevealsistoerasetheoffendingpackagesandthenreinstall
themusingApt.
Atthetimethisbookwaswritten,AptwasincompatiblewiththeXimianDesktop.
Updatethesystem
Twoargumentstoapt-getcauseitupgradeallpackagesonthesystem:upgradeupgradesallpackages
onthesystemthatdonotrequirenewpackagestobeinstalledanddist-upgradeupgradesallpackageson
thesystem,installingnewpackagesasneeded.
Thefollowingcommandupdatesallrpm-basedpackagesonthesystemthatdependonlyonpackagesthat
arealreadyinstalled:
#apt-getupgrade
ReadingPackageLists...Done
BuildingDependencyTree...Done
Thefollowingpackageswillbeupgraded
bashbinutilsdiaetherealfoomaticgaimgdmghostscriptgimp-print
...
rhn-appletrsyncsedslocatestracevnc-serveryum
Thefollowingpackageshavebeenkeptback
gstreamer-pluginsgthumbrhythmbox
57upgraded,0newlyinstalled,0removedand3notupgraded.
Needtoget59.7MB/87.9MBofarchives.
Afterunpacking11.8MBofadditionaldiskspacewillbeused.
Doyouwanttocontinue?[Y/n]
EnterYtoupgradethelistedpackages;otherwise,enterN.Packagesthatarenotupgradedbecausethey
dependonpackagesthatarenotalreadyinstalledarelistedaskeptback.
Usedist-upgradetoupgradeallpackages,includingpackagesthataredependentonpackagesthatarenot
installed.Thiscommandalsoinstallsdependencies.
#apt-getdist-upgrade
ReadingPackageLists...Done
BuildingDependencyTree...Done
CalculatingUpgrade...Done
Thefollowingpackageswillbeupgraded
gstreamer-pluginsgthumbrhythmbox
ThefollowingNEWpackageswillbeinstalled:
Hermesflaclibexiflibid3tag
3upgraded,4newlyinstalled,0removedand0notupgraded.
Needtoget4510kBofarchives.
Afterunpacking6527kBofadditionaldiskspacewillbeused.
Doyouwanttocontinue?[Y/n]
AddingAndRemovingIndividualPackages
Theformatofacommandtoinstallaspecificsoftwarepackageandthepackagesitisdependentonis
apt-getinstallpackage
wherepackageisthenameofthepackage,suchaszsh,andnotthenameoftherpm,whichusually
includesversionandarchitectureinformation(forexample,zsh-1.2.i386.rpm).
#apt-getinstallzsh
ReadingPackageLists...Done
BuildingDependencyTree...Done
ThefollowingNEWpackageswillbeinstalled:
zsh
0upgraded,1newlyinstalled,0removedand0notupgraded.
Needtoget1435kBofarchives.
Afterunpacking2831kBofadditionaldiskspacewillbeused.
Get:1http://ayo.freshrpms.netfedora/linux/3/i386/corezsh4.2.0-3
[1435kB]
Fetched1435kBin21s(66.0kB/s)
Committingchanges...
Preparing...
###########################################[100%]
1:zsh
###########################################[100%]
Done.
Removeapackagethesamewayyouinstallapackage,substitutingremoveforinstall:
#apt-getremovezsh
ReadingPackageLists...Done
BuildingDependencyTree...Done
ThefollowingpackageswillbeREMOVED:
zsh
0upgraded,0newlyinstalled,1removedand0notupgraded.
Needtoget0Bofarchives.
Afterunpacking2831kBdiskspacewillbefreed.
Doyouwanttocontinue?[Y/n]y
Committingchanges...
Preparing...
###########################################[100%]
Done.
Toensurethatyoucanlaterreinstallapackagewiththesameconfiguration,theapt-getremove
commanddoesnotremoveconfigurationfilesfromthe/etcdirectoryhierarchy.Althoughitisnot
recommended,youcanusethepurgeoptiontoremoveallofthesefiles,includingconfigurationfiles.
Alternatively,youcanmovethesefilestoanarchivesoyoucanrestorethemlaterifnecessary.
apt.conf:ConfiguringApt
The/etc/apt/apt.conffilecontainsAptconfigurationinformationandissplitintothreesections:APT,
whichcontainsglobalsettingsfortheApttools;Acquire,whichdescribessettingsrelatedtothepackage-
fetchingmechanism;andRPM,whichcontainsrpm-specificsettings.Inthisfilesemicolons(;)separate
statementsanddoubleforwardslashes(//)introducecomments.
APTsection
TheAPTsectionisshownfollowing:
$cat/etc/apt/apt.conf
APT{
Clean-Installed"false";
Get{
Assume-Yes"false";
Download-Only"false";
Show-Upgraded"true";
Fix-Broken"false";
Ignore-Missing"false";
Compile"false";
};
};
...
WhenyousetClean-InstalledtoTRUE,Aptremovespackagesthatarenolongerintherepository.
TheoptionsintheGetsubsectionlistedhereapplytotheapt-getutility(theapt-getutilityhas
commandlineargumentswiththesamenamesastheseoptions):
Assume-Yes TRUErunsapt-getinbatchmode,automaticallyansweringYES
wheneveritwouldotherwisepromptyouforinput.
Download-Only TRUEretrievespackagesfromtherepositorybutdoesnotinstallthem.
FALSEretrievesandinstallsthepackages.
Show-Upgraded TRUEdisplaysalistofupgradedpackages.
Fix-Broken TRUEattemptstofixdependencytreeproblemswithvaryingdegreesof
success.FALSEquitsifitfindsadependencytreeproblem.
Ignore-Missing
TRUEholdsbackmissingorcorruptpackagesandcontinuestoinstall
otherpackages.FALSEabortstheentireinstallorupgradeuponfindinga
missingorcorruptpackage.
Compile
TRUEcompilesandinstallssourcerpm(SRPM)packagesthatyouask
apt-gettoretrieve.FALSEdownloadsthesefileswithoutcompilingor
installingthem.
Acquiresection TheAcquiresectioncontrolsoptionsrelatedtofetchingpackages.
$cat/etc/apt/apt.conf
...
Acquire{
Retries"0";
Http{
Proxy"";//http://user:pass@host:port/
}
};
...
TheRetriesoptionspecifiesthenumberoftimesAptattemptstofetchapackagewhenanattemptfails.
TheHttpProxysettingspecifiestheproxytousewhenfetchingpackagesusingHTTP.Theargumentto
thisoptionisblankbydefault,indicatingthatAptshouldnotuseaproxy.Anexampleproxyisshownasa
comment.
RPMsection
FollowingistheRPMsectionofapt.conf:
$cat/etc/apt/apt.conf
...
RPM{
Ignore{};
Hold{};
Allow-Duplicated{"^kernel$";"^kernel-";"^kmodule-";"^gpg-
pukey$"
};
Options{};
Install-Options"";
Erase-Options"";
Source{
Build-Command"rpmbuild--rebuild";
};
};
TheIgnoreandHoldoptionsperformsimilarfunctionsandcontainlistsofpackagesthatAptignoresor
holds(doesnotupgrade).Theyareusuallyblank.
TheAllow-Duplicatedsectionlistspackagesthatcanhavemorethanoneversiononthesystematone
time.Ingeneralyoudonotwanttohavemultipleversionsofthesamepackageonasystem.Thekernelis
anexception:Itisgoodpracticetoleavetheoldkernelinstalledwhenyouinstallanewkernelincase
youareunabletobootthenewone.
TheOptionssectioncontainsoptionsthatarepassedtorpm.TheInstall-OptionsandErase-Options
sectionscontainoptionsthatarepassedtorpmwheneveritisusedtoinstalloreraseapackage.
TheSourceBuild-CommandoptionspecifiesthecommandthatAptusestobuildasourcerpmfile.
BitTorrent
TheBitTorrentprotocolimplementsahybridclient/serverandP2P(page891)filetransfermechanism.
BitTorrentefficientlydistributeslargeamountsofstaticdata,suchasinstallationISOimages.Itcan
replaceprotocolssuchasanonymousFTP,whereclientauthenticationisnotrequired.EachBitTorrent
clientthatdownloadsafileprovidesadditionalbandwidthforuploadingthefile,reducingtheloadonthe
initialsource.IngeneralBitTorrentdownloadsproceedmorerapidlythanFTPdownloads.
UnlikeprotocolssuchasFTP,BitTorrentgroupsmultiplefilesintoasinglepackagecalledatorrent.For
example,youcantypicallydownloadseveralinstallationISOimagesasasingletorrent.
LikeotherP2Psystems,BitTorrentdoesnotuseadedicatedserver.Instead,thefunctionsofaserverare
performedbythetracker,peers,andseeds.Thetrackerallowsclientstocommunicatewitheachother.A
clientcalledapeerwhenithasdownloadedpartofthetorrentandaseedonceithasdownloadedthe
entiretorrentactsasanadditionalsourceforthetorrent.AswithaP2Pnetwork,eachpeerandseedthat
downloadsatorrentuploadstootherclientsthesectionsofthetorrentitalreadyhas.Thereisnothing
specialaboutaseed:Itcanberemovedatanytimeoncethetorrentisavailablefordownloadfromother
seeds.
TheBitTorrentprogramisavailablefromwww.bittorrent.com.Afteryoudownloadandinstall
BitTorrent,thefirststepindownloadingatorrentusingBitTorrentistolocateoracquirea.torrentfile.
A.torrentfilecontainstheinformationaboutthetorrent,suchasitssizeandthelocationofthetracker.
Youcanusea.torrentfileusingitsURI(908)oryoucanacquireitviatheWeb,anemailattachment,or
othermeans.ThenextstepisfortheBitTorrentclienttoconnecttothetrackertolearnthelocationsof
otherclientsthatitcandownloadthetorrentfrom.
Onceyouhavedownloadedatorrent,itisgoodmannerstoallowBitTorrenttocontinuetorunsoother
clientscanuploadatleastasmuchinformationasyouhavedownloaded.
Prerequisites
IfnoBitTorrentrpmfileexistsforyourversionofLinux,useanrpmfileforasimilarversion.Because
BitTorrentiswritteninPythonandrunsonanyplatformwithaPythoninterpreter,itisnotdependenton
systemarchitecture.Thenoarchinthenameoftherpmfilestandsfornoarchitecture.
Torun,BitTorrentrequiresPython,whichisinstalledas/usr/bin/pythononmanysystems.Pythonis
availableinthepythonrpmpackage.
HowBittorrentWorks
TheofficialBitTorrentdistributionincludesthreeclientapplications.Youcanuseanyofthese

applicationstodownloadBitTorrentfiles:
btdownloadheadless.pyAtext-basedclientthatwritesthestatustostandardoutput.Goodfor
unattendeddownloadswheretheoutputisredirectedtoafile.
btdownloadcurses.pyAtext-basedclientthatprovidesapseudographicalinterface.Goodfor
attendeddownloadstomachinesnotrunningaGUI.
btdownloadgui.pyAgraphicalclient.
Inadditiontotheofficialclients,severalotherclientsprovideextrafeatures.Someoftheseclientsare
availableonsourceforge.net.
UsingBittorrent
TouseBitTorrent,firstlocatethe.torrentfileforthetorrentyouwanttodownload.Youcancopythe
.torrentfiletotheworkingdirectory(thefirstformatshownbelow)orspecifyitwithaurloption
(secondformat).ThesimplestBitTorrentcommandlineshavethefollowingformats:
$btdownloadheadless.pyresponsefiletfile.torrent[saveas
savefile]
or
$btdownloadheadless.pyurlhttp://domain/tfile.torrent[saveas
savefile]
wheretfile.torrentisthenameof,orhttp://domain/tfile.torrentistheURIfor,the.torrentfile,and
savefileisthelocationtosavethetorrentin.Inthecaseoftorrentscontainingasinglefile,thefileis
savedassavefile.Fortorrentscontainingmultiplefiles,thefilesaresavedinadirectorynamedsavefile.
Ifyouomitthesaveasargument,thefilesaresavedinthenamespecifiedinthe.torrentfile.Because
eachofthebtdownload*.pyapplicationstakesthesamearguments,theprecedingformatsworkforall
threeapplications.
ThenextexampleshowshowtodownloadFedoraCore3ISOimages.Theselargefilestake
considerabletimetodownload.Tostartthedownload,givethefollowingcommand.Becausethe
commandlineislong,itisbrokenbyabackslash(\).Makesurenocharacterfollowsthebackslash,or
elsethebackslashwillnotquotethefollowingRETURNandthecommandwillfail.(Theshellsupplies
the>onthesecondline.)
$btdownloadheadless.py--max_upload_rate8\
>--urlhttp://torrent.dulug.duke.edu/heidelberg-binary-i386.torrent
TheprecedingcommandusesaURItospecifya.torrentfileandsavesthedownloadedfilesina
directorynamedheidelberg(thenameoftheFedorarelease)asspecifiedbythe.torrentfile.
Themax_upload_rate8optionpreventsBitTorrentfromusingmorethan8kilobytespersecondof
upstreambandwidth.BitTorrentusuallygiveshigherdownloadratestoclientsthatuploadmore,sofeel
freetoincreasethisvalueifyouhavesparebandwidth.Youneedtoleaveenoughfreeupstream
bandwidthfortheacknowledgmentpacketsfromyourdownloadtogetthroughoryourdownloadwillbe
veryslow.Bydefaulttheclientuploadstoamaximumofsevenotherclientsatonce.Youcanchangethis
valuebyspecifyingthemax_uploadsargument,followedbythemaximumnumberofconcurrentuploads
youwishtopermit.Thedefaultvalueof7isusuallyappropriatefortypicalbroadbandconnections.
Afteryougivetheprecedingcommand,thescreenquicklyfillswithoutputthatlookssimilartothe
following:
saving:heidelberg-binary-i386
percentdone:0.0
timeleft:finishingin27:09:04
downloadto:/home/max/heidelberg-binary-i386
_
uploadrate:0.0KB/s
sharerating:0.000(0.0MBup/1.2MBdown)
seedstatus:30seennow,plus1distributedcopies(2:81.5%,
3:23.0%,4:2.1%)
peerstatus:5seennow
Thefilesizeisthatofallthefilesyouaredownloading:fourISOimagesandseveralsmallerfiles.To
abortthedownload,pressCONTROL-C.Thedownloadwillautomaticallyresumefromwhereitleftoff
whenyoudownloadthesametorrenttothesamelocationagain.
Usethefollowingcommandtoperformthesamedownloadasinthepreviousexample,thistimethrottling
therateandnumberofuploadstovaluessensibleformodemusers.(Theshellsuppliesthe>onthe
secondline,youdonotenterit.)
$btdownloadcurses.py--max_upload_rate3--max_uploads2\
>--urlhttp://torrent.dulug.duke.edu/heidelberg-binary-i386.torrent
Theprecedingcommanddisplaysoutputsimilartothefollowing:
--------------------------------------------------------------------
----------
|file:heidelberg-binary-i386
|
|size:2,467,681,047(2GiB)
|
|dest:/home/max/heidelberg-binary-i386
|
|progress:
__________________________________________________________________|
|status:finishingin6:40:42(1.0%)
|
|dlspeed:285.6KB/s
|
|ulspeed:2.6KB/s
|
|sharing:0.009(0.1MBup/15.1MBdown)
|
|seeds:29seennow,plus0distributedcopies(1:0.8%,2:0.0%,
3:0.0%)|
|peers:1seennow
|
|
|
--------------------------------------------------------------------
----------
Glossary
AllentriesmarkedwithFOLDOCarebasedondefinitionsintheFreeOnlineDictionaryofComputing
(www.foldoc.org),DenisHowe,editor.Usedwithpermission.
10.0.0.0
See[privateaddressspace]
172.16.0.0
See[privateaddressspace]
192.168.0.0
See[privateaddressspace]
802.11
AfamilyofspecificationsdevelopedbyIEEEforwirelessLANtechnology,including802.11(12
megabitspersecond),802.11a(54megabitspersecond),802.11b(11megabitspersecond),and
802.11g(20+megabitspersecond).
absolutepathname
Apathnamethatstartswiththerootdirectory(/).Anabsolutepathnamelocatesafilewithoutregard
totheworkingdirectory.
access
Incomputerjargon,averbmeaningtouse,readfrom,orwriteto.Toaccessafilemeanstoread
fromorwritetothefile.
AccessControlList
See[ACL]
accesspermission
Permissiontoreadfrom,writeto,orexecuteafile.Ifyouhavewriteaccesspermissiontoafile,you
canwritetothefile.Alsoaccessprivilege.
ACL
AccessControlList.Asystemthatperformsafunctionsimilartofilepermissionsbutwithmuch
finer-graincontrol.
activewindow
Onadesktop,thewindowthatreceivesthecharactersyoutypeonthekeyboard.Sameasfocus,
desktop(page875).
addressmask
See[subnetmask]
alias
Amechanismofashellthatenablesyoutodefinenewcommands.
alphanumericcharacter
Oneofthecharacters,eitheruppercaseorlowercase,fromAtoZand0to9,inclusive.
ambiguousfilereference
Areferencetoafilethatdoesnotnecessarilyspecifyanyonefilebutcanbeusedtospecifyagroup
offiles.Theshellexpandsanambiguousfilereferenceintoalistoffilenames.Specialcharacters
representsinglecharacters(?),stringsofzeroormorecharacters(*),andcharacterclasses([])
withinambiguousfilereferences.Anambiguousfilereferenceisatypeofregularexpression(page
897).
anglebracket
Aleftanglebracket(<)andarightanglebracket(>).Theshelluses<toredirectacommand's
standardinputtocomefromafileand>toredirectthestandardoutput.Theshellusesthecharacters
<<tosignifythestartofaHeredocumentand>>toappendoutputtoafile.
animate
Whenreferringtoawindowaction,meansthattheactionissloweddownsotheusercanviewit.
Forexample,whenyouminimizeawindow,itcandisappearallatonce(notanimated)oritcan
slowlytelescopeintothepanelsoyoucangetavisualfeelforwhatishappening(animated).
anti-aliasing
Addinggraypixelsattheedgeofadiagonallinetogetridofthejaggedappearanceandthereby
makethelinelooksmoother.Anti-aliasingsometimesmakestypeonascreenlookbetterand
sometimesworse;itworksbestonsmallandlargefontsandislesseffectiveonfontsfrom8to15
points.
Seealso[subpixelhinting]
API
ApplicationProgramInterface.Theinterface(callingconventions)bywhichanapplicationprogram
accessesanoperatingsystemandotherservices.AnAPIisdefinedatthesourcecodeleveland
providesalevelofabstractionbetweentheapplicationandthekernel(orotherprivilegedutilities)
toensuretheportabilityofthecode.FOLDOC
append
Toaddsomethingtotheendofsomethingelse.Toappendtexttoafilemeanstoaddthetexttothe
endofthefile.Theshelluses>>toappendacommand'soutputtoafile.
applet
Asmallprogramthatrunswithinalargerprogram.ExamplesareJavaappletsthatruninabrowser
andpanelappletsthatrunfromadesktoppanel.
argument
Anumber,letter,filename,oranotherstringthatgivessomeinformationtoacommandandispassed
tothecommandwhenitiscalled.Acommandlineargumentisanythingonacommandline
followingthecommandnamethatispassedtothecommand.Anoptionisakindofargument.
arithmeticexpression
Agroupofnumbers,operators,andparenthesesthatcanbeevaluated.Whenyouevaluatean
arithmeticexpression,youendupwithanumber.TheBourneAgainShellusestheexprcommand
toevaluatearithmeticexpressions;theTCShelluses@;andtheZShelluseslet.
array
Anarrangementofelements(numbersorstringsofcharacters)inoneormoredimensions.TheTC
andZShellsandgawkcanstoreandprocessarrays.
ASCII
AmericanStandardCodeforInformationInterchange.Acodethatusessevenbitstorepresentboth
graphic(letters,numbers,andpunctuation)andcontrolcharacters.Youcanrepresenttextual
information,includingprogramsourcecodeandEnglishtext,inASCIIcode.BecauseASCIIisa
standard,itisfrequentlyusedwhenexchanginginformationbetweencomputers.Seethefile
/usr/pub/asciiorgivethecommandmanasciitoseealistofASCIIcodes.
ExtensionsoftheASCIIcharactersetuseeightbits.Theseven-bitsetiscommon;theeight-bit
extensionsarestillcomingintopopularuse.Theeighthbitissometimesreferredtoasthemetabit.
ASCIIterminal
Atext-basedterminal.Contrastwithgraphicaldisplay(page877).
ASP
ApplicationServiceProvider.AcompanythatprovidesapplicationsovertheInternet.
asynchronousevent
Aneventthatdoesnotoccurregularlyorsynchronouslywithanotherevent.Linuxsystemsignalsare
asynchronous;theycanoccuratanytimebecausetheycanbeinitiatedbyanynumberofnonregular
events.
attachment
Afilethatisattachedto,butisnotpartof,apieceofemail.Attachmentsarefrequentlyopenedby
programs(includingyourInternetbrowser)thatarecalledbyyourmailprogramsoyoumaynotbe
awarethattheyarenotanintegralpartofanemailmessage.
authentication
Theverificationoftheidentityofapersonorprocess.Inacommunicationsystem,authentication
verifiesthatamessagecomesfromitsstatedsource.MethodsofauthenticationonaLinuxsystem
includethe/etc/passwdand/etc/shadowfiles,LDAP,Kerberos5,andSMBauthentication.FOLDOC
automaticmounting
Awayofdemandmountingdirectoriesfromremotehostswithouthavingthemhardconfiguredinto
/etc/fstab.Alsocalledautomounting.
avoided
Anobject,suchasapanel,thatshouldnotnormallybecoveredbyanotherobject,suchasawindow.
backdoor
Asecurityholedeliberatelyleftinplacebythedesignersormaintainersofasystem.Themotivation
forcreatingsuchholesisnotalwayssinister;someoperatingsystems,forexample,comeoutofthe
boxwithprivilegedaccountsintendedforusebyfieldservicetechniciansorthevendor's
maintenanceprogrammers.
KenThompson's1983TuringAwardlecturetotheACMrevealedtheexistence,inearlyUNIX
versions,ofabackdoorthatmaybethemostfiendishlycleversecurityhackofalltime.TheC
compilercontainedcodethatwouldrecognizewhenthelogincommandwasbeingrecompiledand
wouldinsertsomecoderecognizingapasswordchosenbyThompson,givinghimentrytothesystem
whetherornotanaccounthadbeencreatedforhim.
Normallysuchabackdoorcouldberemovedbyremovingitfromthesourcecodeforthecompiler
andrecompilingthecompiler.Buttorecompilethecompiler,youhavetousethecompiler,so
Thompsonarrangedthatthecompilerwouldrecognizewhenitwascompilingaversionofitself.It
wouldinsertintotherecompiledcompilerthecodetoinsertintotherecompiledloginthecodeto
allowThompsonentry,and,ofcourse,thecodetorecognizeitselfanddothewholethingagainthe
nexttimearound.Havingdonethisonce,hewasthenabletorecompilethecompilerfromthe
originalsources;thehackperpetuateditselfinvisibly,leavingthebackdoorinplaceandactivebut
withnotraceinthesources.
Sometimescalledawormhole.Alsotrapdoor.FOLDOC
backgroundprocess
Aprocessthatisnotrunintheforeground.Alsocalledadetachedprocess,abackgroundprocessis
initiatedbyacommandlinethatendswithanampersand(&).Youdonothavetowaitfora
backgroundprocesstoruntocompletionbeforegivingtheshelladditionalcommands.Ifyouhave
jobcontrol,youcanmovebackgroundprocessestotheforeground,andviceversa.
basename
Thenameofafilethat,incontrastwithapathname,doesnotmentionanyofthedirectories
containingthefile(andthereforedoesnotcontainanyslashes[/]).Forexample,hostsisthe
basenameof/etc/hosts.FOLDOC
baud
Themaximuminformation-carryingcapacityofacommunicationchannelinsymbols(state
transitionsorleveltransitions)persecond.Itcoincideswithbitspersecondonlyfortwo-level
modulationwithnoframingorstopbits.Asymbolisauniquestateofthecommunicationchannel,
distinguishablebythereceiverfromallotherpossiblestates.Forexample,itmaybeoneoftwo
voltagelevelsonawireforadirectdigitalconnection,oritmightbethephaseorfrequencyofa
carrier.FOLDOC
Baudisoftenmistakenlyusedasasynonymforbitspersecond.
baudrate
Transmissionspeed.Usuallyusedtomeasureterminalormodemspeed.Commonbaudratesrange
from110to38,400baud.
Seealso[baud]
BerkeleyUNIX
OneofthetwomajorversionsoftheUNIXoperatingsystem.BerkeleyUNIXwasdevelopedatthe
UniversityofCaliforniaatBerkeleybytheComputerSystemsResearchGroupandisoftenreferred
toasBSD(BerkeleySoftwareDistribution).
BIND
BerkeleyInternetNameDomain.AnimplementationofaDNS(page872)serverdevelopedand
distributedbytheUniversityofCaliforniaatBerkeley
BIOS
BasicInput/OutputSystem.OnPCs,EEPROM-based(page873)systemsoftwarethatprovidesthe
lowest-levelinterfacetoperipheraldevicesandcontrolsthefirststageofthebootstrap(page864)
process,whichloadstheoperatingsystem.TheBIOScanbestoredindifferenttypesofmemory.
Thememorymustbenonvolatilesothatitremembersthesystem'ssettingsevenwhenthesystemis
turnedoff.AlsoBIOSROM.
bit
Thesmallestpieceofinformationacomputercanhandle.Abitisabinarydigit:either1or0(onor
off).
bitdepth
Sameascolordepth(page868).
bit-mappeddisplay
Agraphicaldisplaydeviceinwhicheachpixelonthescreeniscontrolledbyanunderlying
representationofzerosandones.
blankcharacter
EitheraSPACEoraTABcharacter,alsocalledwhitespace(page909).Insomecontexts,
NEWLINEsareconsideredblankcharacters.
block
Asectionofadiskortape(usually1,024byteslongbutshorterorlongeronsomesystems)thatis
writtenatonetime.
blockdevice
Adiskortapedrive.Ablockdevicestoresinformationinblocksofcharacters.Ablockdeviceis
representedbyablockdevice(blockspecial)file.Contrastwithcharacterdevice(page866).
blocknumber
DiskandtapeblocksarenumberedsothatLinuxcankeeptrackofthedataonthedevice.
blockingfactor
Thenumberoflogicalblocksthatmakeupaphysicalblockonatapeordisk.Whenyouwrite1K
logicalblockstoatapewithaphysicalblocksizeof30K,theblockingfactoris30.
boot
See[bootstrap]
bootloader
Averysmallprogramthattakesitsplaceinthebootstrapprocessthatbringsacomputerfromoffor
resettoafullyfunctionalstate.
bootstrap
Derivedfrom"Pulloneselfupbyone'sownbootstraps,"theincrementalprocessofloadingan
operatingsystemkernelintomemoryandstartingitrunningwithoutanyoutsideassistance.
Frequentlyshortenedtoboot.
BourneAgainShell
bash.GNU'scommandinterpreterforUNIX,bashisaPOSIX-compliantshellwithfullBourne
ShellsyntaxandsomeCShellcommandsbuiltin.TheBourneAgainShellsupportsemacs-style
commandlineediting,jobcontrol,functions,andonlinehelp.FOLDOC
BourneShell
sh.ThisUNIXcommandprocessorwasdevelopedbySteveBourneatAT&TBellLaboratories.
brace
Aleftbrace({)andarightbrace(}).Braceshavespecialmeaningstotheshell.
bracket
Asquarebracket(page902)orananglebracket(page860).
branch
Inatreestructure,abranchconnectsnodes,leaves,andtheroot.TheLinuxfilesystemhierarchyis
oftenconceptualizedasanupside-downtree.Thebranchesconnectfilesanddirectories.Inasource
codecontrolsystem,suchasSCCSorRCS,abranchoccurswhenarevisionismadetoafileandis
notincludedinsubsequentrevisionstothefile.
bridge
Typicallyatwo-portdeviceoriginallyusedforextendingnetworksatlayer2(datalink)ofthe
InternetProtocolmodel.
broadcast
Atransmissiontomultiple,unspecifiedrecipients.OnEthernetabroadcastpacketisaspecialtype
ofmulticastpacketthathasaspecialaddressindicatingthatalldevicesthatreceiveitshould
processit.Broadcasttrafficexistsatseverallayersofthenetworkstack,includingEthernetandIP.
Broadcasttraffichasonesourcebutindeterminatedestinations(allhostsonthelocalnetwork).
broadcastaddress
Thelastaddressonasubnet(usually255),reservedasshorthandtomeanallhosts.
broadcastnetwork
Atypeofnetwork,suchasEthernet,inwhichanysystemcantransmitinformationatanytime,andall
systemsreceiveeverymessage.
BSD
See[BerkeleyUNIX]
buffer
Anareaofmemorythatstoresdatauntilitcanbeused.Whenyouwriteinformationtoafileona
disk,Linuxstorestheinformationinadiskbufferuntilthereisenoughtowritetothediskoruntilthe
diskisreadytoreceivetheinformation.
bug
Anunwantedandunintendedprogramproperty,especiallyonethatcausestheprogramto
malfunction.FOLDOC
builtin(command)
Acommandthatisbuiltintoashell.EachofthethreemajorshellstheBourneAgain,TC,andZ
Shellshasitsownsetofbuiltins.Referto"Builtins"onpage132.
byte
Acomponentinthemachinedatahierarchy,usuallylargerthanabitandsmallerthanaword;now
mostofteneightbitsandthesmallestaddressableunitofstorage.Abytetypicallyholdsone
character.FOLDOC
Cprogramminglanguage
Amodernsystemslanguagethathashigh-levelfeaturesforefficient,modularprogrammingaswell
aslower-levelfeaturesthatmakeitsuitableforuseasasystemsprogramminglanguage.Itis
machineindependentsothatcarefullywrittenCprogramscanbeeasilytransportedtorunon
differentmachines.MostoftheLinuxoperatingsystemiswritteninC,andLinuxprovidesanideal
environmentforprogramminginC.
CShell
csh.TheCShellcommandprocessorwasdevelopedbyBillJoyforBSDUNIX.Itwasnamedfor
theCprogramminglanguagebecauseitsprogrammingconstructsaresimilartothoseofC.
Seealso[shell]
cablemodem
AtypeofmodemthatallowsyoutoaccesstheInternetbyusingyourcabletelevisionconnection.
cache
Holdingrecentlyaccesseddata,asmall,fastmemorydesignedtospeedupsubsequentaccesstothe
samedata.Mostoftenappliedtoprocessor-memoryaccessbutalsousedforalocalcopyofdata
accessibleoveranetwork,fromaharddisk,andsoon.FOLDOC
callingenvironment
Alistofvariablesandtheirvaluesthatismadeavailabletoacalledprogram.Referto"Executinga
Command"onpage294.
cascadingstylesheet
See[CSS]
cascadingwindows
Anarrangementofwindowssuchthattheyoverlap,generallywithatleastpartofthetitlebar
visible.Oppositeoftiledwindows(page906).
casesensitive
Abletodistinguishbetweenuppercaseandlowercasecharacters.Unlessyousettheignorecase
parameter,vimperformscase-sensitivesearches.Thegreputilityperformscase-sensitive
searchesunlessyouusetheioption.
catenate
Tojoinsequentially,orendtoend.TheLinuxcatutilitycatenatesfiles:Itdisplaysthemoneafter
theother.Alsoconcatenate.
chainloading
Thetechniqueusedbyabootloadertoloadunsupportedoperatingsystems.Usedforloadingsuch
operatingsystemsasDOSorWindows,itworksbyloadinganotherbootloader.
character-based
Aprogram,utility,orinterfacethatworksonlywithASCII(page861)characters.Thissetof
charactersincludessomesimplegraphics,suchaslinesandcorners,andcandisplaycolored
characters.Itcannotdisplaytruegraphics.ContrastwithGUI(page877).
character-basedterminal
Aterminalthatdisplaysonlycharactersandverylimitedgraphics.
Seealso[character-based]
characterclass
Inaregularexpression,agroupofcharactersthatdefineswhichcharacterscanoccupyasingle
characterposition.Acharacter-classdefinitionisusuallysurroundedbysquarebrackets.The
characterclassdefinedby[abcr]representsacharacterpositionthatcanbeoccupiedbya,b,c,or
r.Alsolistoperator.
characterdevice
Aterminal,printer,ormodem.Acharacterdevicestoresordisplayscharactersoneatatime.A
characterdeviceisrepresentedbyacharacterdevice(characterspecial)file.Contrastwithblock
device(page864).
checksum
Acomputedvaluethatdependsonthecontentsofablockofdataandistransmittedorstoredalong
withthedatatodetectcorruptionofthedata.Thereceivingsystemrecomputesthechecksumbased
onthereceiveddataandcomparesthisvaluewiththeonesentwiththedata.Ifthetwovaluesarethe
same,thereceiverhassomeconfidencethatthedatawasreceivedcorrectly.
Thechecksummaybe8,16,or32bits,orsomeothersize.Itiscomputedbysummingthebytesor
wordsofthedatablock,ignoringoverflow.Thechecksummaybenegatedsothatthetotalofthedata
wordsplusthechecksumiszero.
Internetpacketsusea32-bitchecksum.FOLDOC
childprocess
Aprocessthatiscreatedbyanotherprocess,theparentprocess.Everyprocessisachildprocess
exceptforthefirstprocess,whichisstartedwhenLinuxbeginsexecution.Whenyourunacommand
fromtheshell,theshellspawnsachildprocesstorunthecommand.
Seealso[process]
CIDR
ClasslessInter-DomainRouting.AschemethatallocatesblocksofInternetaddressesinawaythat
allowssummarizationintoasmallernumberofroutingtableentries.ACIDRblockisablockof
InternetaddressesassignedtoanISPbytheInternic.FOLDOC
CIFS
CommonInternetFileSystem.AnInternetfilesystemprotocolbasedonSMB(page901).CIFSruns
ontopofTCP/IP,usesDNS,andisoptimizedtosupportslowerdial-upInternetconnections.SMB
andCIFSareusedinterchangeably.FOLDOC
CIPE
CryptoIPEncapsulation(page874).Thisprotocol(page895)tunnels(page907)IPpacketswithin
encryptedUDP(page907)packets,islightweightandsimple,andworksoverdynamicaddresses,
NAT(page889),andSOCKS(page901)proxies(page895).
cipher(cypher)
Acryptographicsystemthatusesakeytotranspose/substitutecharacterswithinamessage,thekey
itself,orthemessage.
ciphertext
Textthatisencrypted.Contrastwithplaintext(page893).
ClasslessInter-DomainRouting
See[CIDR]
cleartext
Textthatisnotencrypted;alsoplaintext.Contrastwithciphertext.
CLI
Commandlineinterface.
Seealso[character-based]
client
Acomputerorprogramthatrequestsoneormoreservicesfromaserver.
CODEC
Coder/decoderorcompressor/decompressor.Ahardwareand/orsoftwaretechnologythatcodesand
decodesdata.MPEGisapopularCODECforcomputervideo.
colordepth
Thenumberofbitsusedtogenerateapixelusually8,16,24,or32.Thecolordepthisdirectly
relatedtothenumberofcolorsthatcanbegenerated.Thenumberofcolorsthatcanbegeneratedis2
raisedtothecolor-depthpower.Thusthata24-bitvideoadaptercangenerateabout16.7million
colors.
colorquality
See[colordepth]
combobox
Acombinationofalistandtextentrybox.Ausercaneitherselectanoptionfromaprovidedlistor
enterhisownoption.
command
Whatyougivetheshellinresponsetoaprompt.Whenyougivetheshellacommand,itexecutesa
utility,anotherprogram,abuiltincommand,orashellscript.Utilitiesareoftenreferredtoas
commands.Whenyouareusinganinteractiveutility,suchasvimormail,youusecommandsthat
areappropriatetothatutility.
commandline
Alinecontaininginstructionsandargumentsthatexecutesacommand.Thistermusuallyreferstoa
linethatyouenterinresponsetoashellpromptonacharacter-basedterminalorterminalemulator.
commandsubstitution
Replacingacommandwithitsoutput.Theshellsperformcommandsubstitutionwhenyouenclosea
commandbetween$(and)orbetweenapairofbackticks(''),alsocalledgraveaccentmarks.
componentarchitecture
Anotioninobject-orientedprogrammingwhere"components"ofaprogramarecompletelygeneric.
Insteadofhavingaspecializedsetofmethodsandfields,theyhavegenericmethodsthroughwhich
thecomponentcanadvertisethefunctionalityitsupportstothesystemintowhichitisloaded.This
strategyenablescompletelydynamicloadingofobjects.JavaBeansisanexampleofacomponent
architecture.FOLDOC
concatenate
See[catenate]
conditioncode
See[exitstatus]
connection-orientedprotocol
Atypeoftransportlayerdatacommunicationservicethatallowsahosttosenddatainacontinuous
streamtoanotherhost.Thetransportserviceguaranteesthatalldatawillbedeliveredtotheother
endinthesameorderassentandwithoutduplication.Communicationproceedsthroughthreewell-
definedphases:connectionestablishment,datatransfer,andconnectionrelease.Themostcommon
exampleisTCP(page905).
Alsocalledconnection-basedprotocolandstream-orientedprotocol.Contrastwithconnectionless
protocolanddatagram(page870).FOLDOC
connectionlessprotocol
Thedatacommunicationmethodinwhichcommunicationoccursbetweenhostswithnoprevious
setup.Packetssentbetweentwohostsmaytakedifferentroutes.Thereisnoguaranteethatpackets
willarriveastransmittedoreventhattheywillarriveatthedestinationatall.UDP(page907)isa
connectionlessprotocol.Alsocalledpacketswitching.Contrastwithcircuitswitchingand
connection-orientedprotocol.FOLDOC
console
See[systemconsole]
consoleterminal
See[systemconsole]
controlcharacter
Acharacterthatisnotagraphiccharacter,suchasaletter,number,orpunctuationmark.Such
charactersarecalledcontrolcharactersbecausetheyfrequentlyacttocontrolaperipheraldevice.
RETURNandFORMFEEDarecontrolcharactersthatcontrolaterminalorprinter.
ThewordCONTROLisshowninthisbookinTHISFONTbecauseitisakeythatappearsonmost
terminalkeyboards.ControlcharactersarerepresentedbyASCIIcodeslessthan32(decimal).
Seealso[nonprintingcharacter]
controlstructure
Astatementusedtochangetheorderofexecutionofcommandsinashellscriptorotherprogram.
Eachshellprovidescontrolstructures(forexample,IfandWhile)aswellasothercommandsthat
altertheorderofexecution(forexample,exec).Alsocontrolflowcommands.
cookie
Datastoredonaclientsystembyaserver.Theclientsystembrowsersendsthecookiebacktothe
servereachtimeitaccessesthatserver.Forexample,acatalogshoppingservicemaystoreacookie
onyoursystemwhenyouplaceyourfirstorder.Whenyoureturntothesite,itknowswhoyouare
andcansupplyyournameandaddressforsubsequentorders.Youmayconsidercookiestobean
invasionofprivacy.
CPU
Centralprocessingunit.Thepartofacomputerthatcontrolsalltheotherparts.TheCPUincludes
thecontrolunitandthearithmeticandlogicunit(ALU).Thecontrolunitfetchesinstructionsfrom
memoryanddecodesthemtoproducesignalsthatcontroltheotherpartsofthecomputer.These
signalscancausedatatobetransferredbetweenmemoryandALUorperipheralstoperforminputor
output.ACPUthatishousedonasinglechipiscalledamicroprocessor.Alsoprocessorand
centralprocessor.
cracker
Anindividualwhoattemptstogainunauthorizedaccesstoacomputersystem.Theseindividualsare
oftenmaliciousandhavemanymeansattheirdisposalforbreakingintoasystem.Contrastwith
hacker(page877).FOLDOC
crash
Thesystemsuddenlyandunexpectedlystopsorfails.Derivedfromtheactionoftheharddiskheads
onthesurfaceofthediskwhentheairgapbetweenthetwocollapses.
cryptography
Thepracticeandstudyofencryptionanddecryptionencodingdatasothatonlyaspecificindividual
ormachinecandecodeit.Asystemforencryptinganddecryptingdataisacryptosystem.Such
systemsusuallyrelyonanalgorithmforcombiningtheoriginaldata(plaintext)withoneormore
keysnumbersorstringsofcharactersknownonlytothesenderand/orrecipient.Theresultingoutput
iscalledciphertext(page867).
Thesecurityofacryptosystemusuallydependsonthesecrecyofkeysratherthanonthesupposed
secrecyofanalgorithm.Becauseastrongcryptosystemhasalargerangeofkeys,itisnotpossibleto
tryallofthem.Ciphertextappearsrandomtostandardstatisticaltestsandresistsknownmethodsfor
breakingcodes.FOLDOC
.cshrcfile
Inyourhomedirectory,afilethattheTCShellexecuteseachtimeyouinvokeanewTCShell.You
canusethisfiletoestablishvariablesandaliases.
CSS
Cascadingstylesheet.Describeshowdocumentsarepresentedonscreenandinprint.Attachinga
stylesheettoastructureddocumentcanaffectthewayitlookswithoutaddingnewHTML(orother)
tagsandwithoutgivingupdeviceindependence.Alsostylesheet.
current(process,line,character,directory,event,andsoon)
Theitemthatisimmediatelyavailable,working,orbeingused.Thecurrentprocesscontrolsthe
programyouarerunning,thecurrentlineorcharacteristheonethecursorison,andthecurrent
directoryistheworkingdirectory.
cursor
Asmalllightedrectangle,underscore,orverticalbarthatappearsontheterminalscreenand
indicateswherethenextcharacterwillappear.Differsfromthemousepointer(page888).
daemon
Aprogramthatisnotinvokedexplicitlybutliesdormant,waitingforsomecondition(s)tooccur.
Theperpetratoroftheconditionneednotbeawarethatadaemonislurking(althoughoftena
programwillcommitanactiononlybecauseitknowsthatitwillimplicitlyinvokeadaemon).From
themythologicalmeaning,laterrationalizedastheacronymDiskAndExecutionMONitor.FOLDOC
datastructure
Aparticularformatforstoring,organizing,workingwith,andretrievingdata.Frequently,data
structuresaredesignedtoworkwithspecificalgorithmsthatfacilitatethesetasks.Commondata
structuresincludetrees,files,records,tables,arrays,andsoon.
datagram
Aself-contained,independententityofdatacarryingsufficientinformationtoberoutedfromthe
sourcetothedestinationcomputerwithoutrelianceonearlierexchangesbetweenthissourceand
destinationcomputerandthetransportingnetwork.UDP(page907)usesdatagrams;IP(page882)
usespackets(page892).Packetsareindivisibleatthenetworklayer;datagramsarenot.FOLDOC
Seealso[frame]
dataless
Acomputer,usuallyaworkstation,thatusesalocaldisktobootacopyoftheoperatingsystemand
accesssystemfilesbutdoesnotusealocaldisktostoreuserfiles.
dbm
Astandard,simpledatabasemanager.Implementedasgdbm(GNUdatabasemanager),ituses
hashestospeedsearching.Themostcommonversionsofthedbmdatabasearedbm,ndbm,and
gdbm.
DDoSattack
Distributeddenialofserviceattack.ADoSattack(page873)frommanysystemsthatdonotbelong
totheperpetratoroftheattack.
debug
Tocorrectaprogrambyremovingitsbugs(thatis,errors).
default
Somethingthatisselectedwithoutbeingexplicitlyspecified.Forexample,whenusedwithoutan
argument,lsdisplaysalistofthefilesintheworkingdirectorybydefault.
delta
AsetofchangesmadetoafilethathasbeenencodedbytheSourceCodeControlSystem(SCCS).
denialofservice
See[DoSattack]
dereference
Whenspeakingofsymboliclinks,followthelinkratherthanworkingwiththereferencetothelink.
Forexample,theLordereferenceoptioncauseslstolisttheentrythatasymboliclinkpointsto
ratherthanthesymboliclink(thereference)itself.
desktop
Acollectionofwindows,toolbars,icons,andbuttons,someorallofwhichappearonyourdisplay.
Adesktopcomprisesoneormoreworkspaces(page910).
desktopmanager
Anicon-andmenu-baseduserinterfacetosystemservicesthatallowsyoutorunapplicationsand
usethefilesystemwithoutusingthesystem'scommandlineinterface.
detachedprocess
See[backgroundprocess]
device
Adiskdrive,printer,terminal,plotter,orotherinput/outputunitthatcanbeattachedtothecomputer.
devicedriver
PartoftheLinuxkernelthatcontrolsadevice,suchasaterminal,diskdrive,orprinter.
devicefile
Afilethatrepresentsadevice.Alsospecialfile.
devicefilename
Thepathnameofadevicefile.AllLinuxsystemshavetwokindsofdevicefiles:blockandcharacter
devicefiles.LinuxalsohasFIFOs(namedpipes)andsockets.Devicefilesaretraditionallylocated
inthe/devdirectory.
devicenumber
Seealso[majordevicenumber]
Seealso[minordevicenumber]
DHCP
DynamicHostConfigurationProtocol.AprotocolthatdynamicallyallocatesIPaddressesto
computersonaLAN.FOLDOC
directory
Shortfordirectoryfile.Afilethatcontainsalistofotherfiles.
directoryhierarchy
Adirectory,calledtherootofthedirectoryhierarchy,andallthedirectoryandordinaryfilesbelow
it(itschildren).
directoryservice
Astructuredrepositoryofinformationonpeopleandresourceswithinanorganization,facilitating
managementandcommunication.FOLDOC
diskpartition
See[partition]
diskless
Acomputer,usuallyaworkstation,thathasnodiskandmustcontactanothercomputer(aserver)to
bootacopyoftheoperatingsystemandaccessthenecessarysystemfiles.
distributedcomputing
Astyleofcomputinginwhichtasksorservicesareperformedbyanetworkofcooperatingsystems,
someofwhichmaybespecialized.
DMZ
Demilitarizedzone.AhostorsmallnetworkthatisaneutralzonebetweenaLANandtheInternet.It
canserveWebpagesandotherdatatotheInternetandallowlocalsystemsaccesstotheInternet
whilepreventingLANaccesstounauthorizedInternetusers.EvenifaDMZiscompromised,it
holdsnodatathatisprivateandnonethatcannotbeeasilyreproduced.
DNS
DomainNameService.Adistributedservicethatmanagesthecorrespondenceoffullhostnames
(thosethatincludeadomainname)toIPaddressesandothersystemcharacteristics.
DNSdomainname
See[domainname]
documentobjectmodel
See[DOM]
DOM
DocumentObjectModel.Aplatform-/language-independentinterfacethatenablesaprogramto
updatethecontent,structure,andstyleofadocumentdynamically.Thechangescanthenbemade
partofthedisplayeddocument.Gotowww.w3.org/DOMformoreinformation.
domainname
Anameassociatedwithanorganization,orpartofanorganization,tohelpidentifysystemsuniquely.
Technically,thepartoftheFQDN(page876)totherightoftheleftmostperiod.Domainnamesare
assignedhierarchically.Thedomainberkeley.edureferstotheUniversityofCaliforniaatBerkeley,
forexample;itispartofthetop-leveledu(education)domain.AlsoDNSdomainname.Different
thanNISdomainname(page890).
DomainNameService
See[DNS]
door
Anevolvingfilesystem-basedRPC(page899)mechanism.
DoSattack
Denialofserviceattack.Anattackthatattemptstomakethetargethostornetworkunusableby
floodingitwithspurioustraffic.
DPMS
DisplayPowerManagementSignaling.AstandardthatcanextendthelifeofCRTmonitorsand
conserveenergy.DPMSsupportsfourmodesforamonitor:Normal,Standby(powersupplyon,
monitorreadytocometodisplayimagesalmostinstantly),Suspend(powersupplyoff,monitortakes
uptotensecondstodisplayanimage),andOff.
drag
Tomoveaniconfromonepositionorapplicationtoanother,usuallyinthecontextofawindow
manager.Themotionpartofdrag-and-drop.
druid
Inrole-playinggames,acharacterthatrepresentsamagicaluser.RedHatusesthetermdruidatthe
endsofnamesofprogramsthatguideyouthroughatask-drivenchainofsteps.Otheroperating
systemscallthesetypesofprogramswizards.
DSA
DigitalSignatureAlgorithm.Apublickeycipherusedtogeneratedigitalsignatures.
DSL
DigitalSubscriberLine/Loop.Provideshigh-speeddigitalcommunicationoveraspecialized,
conditionedtelephoneline.
Seealso[xDSL]
DynamicHostConfigurationProtocol
See[DHCP]
editor
Autility,suchasvimoremacs,thatcreatesandmodifiestextfiles.
EEPROM
Electricallyerasable,programmable,readonlymemory.APROM(page895)thatcanbewrittento.
effectiveuserID
TheuserIDthataprocessappearstohave;usuallythesameastheuserID.Forexample,whileyou
arerunningasetuidprogram,theeffectiveuserIDoftheprocessrunningtheprogramisthatofthe
owneroftheprogram.
element
Onething;usuallyabasicpartofagroupofthings.Anelementofanumericarrayisoneofthe
numbersstoredinthearray.
emoticon
See[smiley]
encapsulation
See[tunneling]
environment
See[callingenvironment]
EOF
Endoffile.
EPROM
Erasable,programmable,readonlymemory.APROM(page895)thatcanbewrittentobyapplyinga
higherthannormalvoltage.
escape
See[quote]
Ethernet
AtypeofLAN(page884)capableoftransferratesashighas1,000megabitspersecond.
event
Anoccurrence,orhappening,ofsignificancetoataskorprogramforexample,thecompletionofan
asynchronousinput/outputoperation,suchasakeypressormouseclick.FOLDOC
exabyte
260bytesorabout1018bytes.
Seealso[largenumber]
exitstatus
Thestatusreturnedbyaprocess;eithersuccessful(usually0)orunsuccessful(usually1).
exploit
Asecurityholeoraninstanceoftakingadvantageofasecurityhole.FOLDOC
expression
Seealso[logicalexpression]
Seealso[arithmeticexpression]
extranet
Anetworkextensionforasubsetofusers(suchasstudentsataparticularschoolorengineers
workingforthesamecompany).Anextranetlimitsaccesstoprivateinformationeventhoughit
travelsonthepublicInternet.
failsafesession
Asessionthatallowsyoutologinonaminimaldesktopincaseyourstandardlogindoesnotwork
wellenoughtoallowyoutologintofixaloginproblem.
FDDI
FiberDistributedDataInterface.AtypeofLAN(page884)designedtotransportdataattherateof
100millionbitspersecondoverfiberopticcable.
file
Acollectionofrelatedinformationreferredtowithafilenameandfrequentlystoredonadisk.Text
filestypicallycontainmemos,reports,messages,programsourcecode,lists,ormanuscripts.Binary
orexecutablefilescontainutilitiesorprogramsthatyoucanrun.Referto"DirectoryandOrdinary
Files"onpage77.
filename
Thenameofafile.Afilenamereferstoafile.
filenamecompletion
Automaticcompletionofafilenameafteryouspecifyauniqueprefix.
filenameextension
Thepartofafilenamefollowingaperiod.
filenamegeneration
Whatoccurswhentheshellexpandsambiguousfilereferences.
Seealso[ambiguousfilereference]
filesystem
Adatastructure(page870)thatusuallyresidesonpartofadisk.AllLinuxsystemshavearoot
filesystem,andmosthaveatleastafewotherfilesystems.Eachfilesystemiscomposedofsome
numberofblocks,dependingonthesizeofthediskpartitionthathasbeenassignedtothefilesystem.
Eachfilesystemhasacontrolblock,namedthesuperblock,thatcontainsinformationaboutthe
filesystem.Theotherblocksinafilesystemareinodes,whichcontaincontrolinformationabout
individualfiles,anddatablocks,whichcontaintheinformationinthefiles.
filling
Avariantofmaximizinginwhichwindowedgesarepushedoutasfarastheycangowithout
overlappinganotherwindow.
filter
Acommandthatcantakeitsinputfromstandardinputandsenditsoutputtostandardoutput.Afilter
transformstheinputstreamofdataandsendsittostandardoutput.Apipeusuallyconnectsafilter's
inputtostandardoutputofonecommand,andasecondpipeconnectsthefilter'soutputtostandard
inputofanothercommand.Thegrepandsortutilitiesarecommonlyusedasfilters.
firewall
Adeviceforpolicy-basedtrafficmanagementusedtokeepanetworksecure.Afirewallcanbe
implementedinasinglerouterthatfiltersoutunwantedpackets,oritcanrelyonacombinationof
routers,proxyservers,andotherdevices.Firewallsarewidelyusedtogiveusersaccesstothe
Internetinasecurefashionandtoseparateacompany'spublicWWWserverfromitsinternal
network.Theyarealsoemployedtokeepinternalnetworksegmentsmoresecure.
Recentlythetermhascometobedefinedmorelooselytoincludeasimplepacketfilterrunningonan
endpointmachine.
Seealso[proxyserver]
focus,desktop
Onadesktopthewindowthatisactive.Thewindowwiththedesktopfocusreceivesthecharacters
youtypeonthekeyboard.Sameasactivewindow(page860).
footer
Thepartofaformatthatgoesatthebottom(orfoot)ofapage.Contrastwithheader(page878).
foregroundprocess
Whenyourunacommandintheforeground,theshellwaitsforthecommandtofinishbeforegiving
youanotherprompt.Youmustwaitforaforegroundprocesstoruntocompletionbeforeyoucangive
theshellanothercommand.Ifyouhavejobcontrol,youcanmovebackgroundprocessestothe
foreground,andviceversa.Contrastwithbackgroundprocess(page863).
Seealso[jobcontrol]
fork
Tocreateaprocess.Whenoneprocesscreatesanotherprocess,itforksaprocess.Alsospawn.
FQDN
Fullyqualifieddomainname.Thefullnameofasystem,consistingofitshostnameanditsdomain
name,includingthetop-leveldomain.Technicallythenamethatgethostbyname(2)returnsforthe
hostnamedbygethostname(2).Forexample,speedyisahostnameandspeedy.example.comisan
FQDN.AnFQDNissufficienttodetermineauniqueInternetaddressforamachineonthe
Internet.FOLDOC
frame
Adatalinklayerpacketthatcontains,inadditiontodata,theheaderandtrailerinformationrequired
bythephysicalmedium.Networklayerpacketsareencapsulatedtobecomeframes.FOLDOC
Seealso[datagram]
Seealso[packet]
freelist
Inafilesystem,thelistofblocksthatareavailableforuse.Informationaboutthefreelistiskeptin
thesuperblockofthefilesystem.
freespace
Theportionofaharddiskthatisnotwithinapartition.Anewharddiskhasnopartitionsand
containsallfreespace.
fullduplex
Theabilitytoreceiveandtransmitdatasimultaneously.Anetworkswitch(page890)istypicallya
full-duplexdevice.Contrastwithhalf-duplex(page877).
fullyqualifieddomainname
See[FQDN]
function
See[shellfunction]
gateway
Agenerictermforacomputeroraspecialdeviceconnectedtomorethanonedissimilartypeof
networktopassdatabetweenthem.Unlikearouter,agatewayoftenmustconverttheinformation
intoadifferentformatbeforepassingiton.Thehistoricalusageofgatewaytodesignatearouteris
deprecated.
GCOS
See[GECOS]
GECOS
GeneralElectricComprehensiveOperatingSystem.Forhistoricalreasons,theuserinformationfield
inthe/etc/passwdfileiscalledtheGECOSfield.AlsoGCOS.
giga-
Inthebinarysystem,theprefixgiga-multipliesby230(i.e.,1,073,741,824).Gigabitandgigabyte
arecommonusesofthisprefix.AbbreviatedasG.
Seealso[largenumber]
glyph
Asymbolthatcommunicatesaspecificpieceofinformationnonverbally.Asmiley(page901)isa
glyph.
GMT
GreenwichMeanTime.
Seealso[UTC]
graphicaldisplay
Abitmappedmonitorthatcandisplaygraphicalimages.ContrastwithASCIIterminal(page861).
graphicaluserinterface
See[GUI]
group(ofusers)
Acollectionofusers.Groupsareusedasabasisfordeterminingfileaccesspermissions.Ifyouare
nottheownerofafileandyoubelongtothegroupthefileisassignedto,youaresubjecttothegroup
accesspermissionsforthefile.Ausercansimultaneouslybelongtoseveralgroups.
group(ofwindows)
Awaytoidentifysimilarwindowssotheycanbedisplayedandactedonsimilarly.Typically
windowsstartedbyagivenapplicationbelongtothesamegroup.
groupID
Auniquenumberthatidentifiesasetofusers.Itisstoredinthepasswordandgroupdatabases
(/etc/passwdand/etc/groupfilesortheirNISequivalents).Thegroupdatabaseassociatesgroup
IDswithgroupnames.
GUI
Graphicaluserinterface.AGUIprovidesawaytointeractwithacomputersystembychoosing
itemsfrommenusormanipulatingpicturesdrawnonadisplayscreeninsteadofbytypingcommand
lines.UnderLinux,theXWindowSystemprovidesagraphicaldisplayandmouse/keyboardinput.
GNOMEandKDEaretwopopulardesktopmanagersthatrununderX.Contrastwithcharacter-
based(page866).
hacker
Apersonwhoenjoysexploringthedetailsofprogrammablesystemsandlearninghowtostretch
theircapabilities,asopposedtousers,whoprefertolearnonlytheminimumnecessary.Onewho
programsenthusiastically(evenobsessively)orwhoenjoysprogrammingratherthanjusttheorizing
aboutprogramming.FOLDOCContrastwithcracker(page869).
half-duplex
Ahalf-duplexdevicecanonlyreceiveortransmitatagivenmoment;itcannotdoboth.Ahub(page
880)istypicallyahalf-duplexdevice.Contrastwithfullduplex(page876).
hardlink
Adirectoryentrythatcontainsthefilenameandinodenumberforafile.Theinodenumberidentifies
thelocationofcontrolinformationforthefileonthedisk,whichinturnidentifiesthelocationofthe
file'scontentsonthedisk.Everyfilehasatleastonehardlink,whichlocatesthefileinadirectory.
Whenyouremovethelasthardlinktoafile,youcannolongeraccessthefile.
Seealso[link]
Seealso[symboliclink]
hash
Astringthatisgeneratedfromanotherstring.Whenusedforsecurity,ahashcanprove,almosttoa
certainty,thatamessagehasnotbeentamperedwithduringtransmission:Thesendergeneratesa
hashofamessage,encryptsthemessageandhash,andsendstheencryptedmessageandhashtothe
recipient.Therecipientdecryptsthemessageandhash,generatesasecondhashfromthemessage,
andcomparesthehashthatthesendergeneratedtothenewhash.Whentheyarethesame,the
messagehasprobablynotbeentamperedwith.Ahashcanalsobeusedtocreateanindexcalleda
hashtable.Alsohashvalue.
Seealso[one-wayhashfunction]
hashtable
Anindexcreatedfromhashesoftheitemstobeindexed.Thehashfunctionmakesithighlyunlikely
thattwoitemswillcreatethesamehash.Tolookupanitemintheindex,createahashoftheitem
andsearchforthehash.Becausethehashistypicallyshorterthantheitem,thesearchismore
efficient.
header
Whenyouareformattingadocument,theheadergoesatthetop,orhead,ofapage.Inelectronicmail
theheaderidentifieswhosentthemessage,whenitwassent,whatthesubjectofthemessageis,and
soforth.
Heredocument
Ashellscriptthattakesitsinputfromthefilethatcontainsthescript.
hesiod
ThenameserverofprojectAthena.HesiodisanameservicelibrarythatisderivedfromBIND
(page863)andleveragesaDNSinfrastructure.
heterogeneous
Consistingofdifferentparts.Aheterogeneousnetworkincludessystemsproducedbydifferent
manufacturersand/orrunningdifferentoperatingsystems.
hexadecimalnumber

TableG-1.Decimal,octal,andhexadecimalnumbers
Decimal Octal Hex Decimal Octal Hex
1 1 1 17 21 11
2 2 2 18 22 12
3 3 3 19 23 13
4 4 4 20 24 14
5 5 5 21 25 15
6 6 6 31 37 1F
7 7 7 32 40 20
8 10 8 33 41 21
9 11 9 64 100 40
10 12 A 96 140 60
11 13 B 100 144 64
12 14 C 128 200 80
13 15 D 254 376 FE
14 16 E 255 377 FF

15 17 F 256 400 100
16 20 10 257 401 101
hiddenfile
See[invisiblefile]
hierarchy
Anorganizationwithafewthings,orthingoneatthetopandwithseveralthingsbeloweachother
thing.Aninvertedtreestructure.Examplesincomputingincludeafiletreewhereeachdirectorymay
containfilesorotherdirectories,ahierarchicalnetwork,andaclasshierarchyinobject-oriented
programming.FOLDOCReferto"TheHierarchicalFilesystem"onpage76.
history
Ashellmechanismthatenablesyoutomodifyandreexecuterecentcommands.
homedirectory
Thedirectorythatisyourworkingdirectorywhenyoufirstlogin.Thepathnameofthisdirectoryis
storedintheHOMEshellvariable.
hover
Toleavethemousepointerstationaryforamomentoveranobject.Inmanycaseshoveringdisplays
atooltip(page906).
HTML
HypertextMarkupLanguage.Ahypertext(page880)documentformatusedontheWorldWideWeb.
Tags,whichareembeddedinthetext,consistofalessthansign(<),adirective,zeroormore
parameters,andagreaterthansign(>).Matchedpairsofdirectives,suchas<TITLE>and
</TITLE>,delimittextthatistoappearinaspecialplaceorstyle.FOLDOCFormoreinformationon
HTML,gotowww.htmlhelp.com/faq/html/all.html.
HTTP
HypertextTransferProtocol.Theclient/serverTCP/IPprotocolusedontheWorldWideWebforthe
exchangeofHTMLdocuments.
hub
Amultiportrepeater.Ahubrebroadcastsallpacketsitreceivesonallports.Thistermisfrequently
usedtorefertosmallhubsandswitches,regardlessofthedevice'sintelligence.Itisagenericterm
foralayer2shared-medianetworkingdevice.Todaythetermhubissometimesusedtoreferto
smallintelligentdevices,althoughthatwasnotitsoriginalmeaning.Contrastwithnetworkswitch
(page890).
hypertext
Acollectionofdocuments/nodescontaining(usuallyhighlightedorunderlined)cross-referencesor
links,which,withtheaidofaninteractivebrowserprogram,allowthereadertomoveeasilyfrom
onedocumenttoanother.FOLDOC
HypertextMarkupLanguage
See[HTML]
HypertextTransferProtocol
See[HTTP]
i/odevice
Input/outputdevice.
Seealso[device]
IANA
InternetAssignedNumbersAuthority.Agroupthatmaintainsadatabaseofallpermanent,registered
systemservices(www.iana.org).
ICMP
InternetControlMessageProtocol.Atypeofnetworkpacketthatcarriesonlymessages,nodata.
icon
InaGUI,asmallpicturerepresentingafile,directory,action,program,andsoon.Whenyouclick
anicon,anaction,suchasopeningawindowandstartingaprogramordisplayingadirectoryor
Website,takesplace.Fromminiaturereligiousstatues.FOLDOC
iconify
Theprocessofchangingawindowintoanicon.Contrastwithrestore(page897).
ignoredwindow
Astateinwhichawindowhasnodecorationandthereforenobuttonsortitlebartocontrolitwith.
indentation
See[indention]
indention
Theblankspacebetweenthemarginandthebeginningofalinethatissetinfromthemargin.
inode
Adatastructure(page870)thatcontainsinformationaboutafile.Aninodeforafilecontainsthe
file'slength,thetimesthefilewaslastaccessedandmodified,thetimetheinodewaslastmodified,
ownerandgroupIDs,accessprivileges,numberoflinks,andpointerstothedatablocksthatcontain
thefileitself.Eachdirectoryentryassociatesafilenamewithaninode.Althoughasinglefilemay
haveseveralfilenames(oneforeachlink),ithasonlyoneinode.
input
Informationthatisfedtoaprogramfromaterminalorotherfile.
Seealso[standardinput]
installation
Acomputerataspecificlocation.SomeaspectsoftheLinuxsystemareinstallationdependent.Also
site.
interactive
Aprogramthatallowsongoingdialogwiththeuser.Whenyougivecommandsinresponsetoshell
prompts,youareusingtheshellinteractively.Also,whenyougivecommandstoutilities,suchas
vimandmail,youareusingtheutilitiesinteractively.
interface
Themeetingpointoftwosubsystems.Whentwoprogramsworktogether,theirinterfaceincludes
everyaspectofeitherprogramthattheotherdealswith.Theuserinterface(page908)ofaprogram
includeseveryprogramaspecttheusercomesintocontactwith:thesyntaxandsemanticsinvolvedin
invokingtheprogram,theinputandoutputoftheprogram,anditserrorandinformationalmessages.
Theshellandeachoftheutilitiesandbuilt-incommandshaveauserinterface.
InternationalOrganizationforStandardization
See[ISO]
internet
Alargenetworkthatencompassesother,smallernetworks.
Internet
Thelargestinternetintheworld.TheInternet(uppercase"I")isamultilevelhierarchycomposedof
backbonenetworks(ARPANET,NSFnet,MILNET,andothers),midlevelnetworks,andstub
networks.Theseincludecommercial(.comor.co),university(.acor.edu),research(.orgor.net),
andmilitary(.mil)networksandspanmanydifferentphysicalnetworksaroundtheworldwith
variousprotocols,includingtheInternetProtocol(IP).OutsidetheUnitedStates,countrycode
domainsarepopular(.us,.es,.mx,.de,andsoforth),althoughyouwillseethemusedwithinthe
UnitedStatesaswell.
InternetProtocol
See[IP]
InternetServiceProvider
See[ISP]
intranet
Aninhousenetworkdesignedtoserveagroupofpeoplesuchasacorporationorschool.The
generalpublicontheInternetdoesnothaveaccesstotheintranet.
invisiblefile
Afilewhosefilenamestartswithaperiod.Thesefilesarecalledinvisiblebecausethelsutility
doesnotnormallylistthem.Usetheaoptionoflstolistallfiles,includinginvisibleones.The
shelldoesnotexpandaleadingasterisk(*)inanambiguousfilereferencetomatchthefilenameof
aninvisiblefile.Alsohiddenfile.
IP
InternetProtocol.ThenetworklayerforTCP/IP.IPisabest-effort,packet-switching,connectionless
protocol(page869)thatprovidespacketrouting,fragmentation,andreassemblythroughthedatalink
layer.IPv4isslowlygivingwaytoIPv6.FOLDOC
IPaddress
InternetProtocoladdress.Afour-partaddressassociatedwithaparticularnetworkconnectionfora
systemusingtheInternetProtocol(IP).AsystemthatisattachedtomultiplenetworksthatusetheIP
willhaveadifferentIPaddressforeachnetworkinterface.
IPmulticast
See[multicast]
IPspoofing
Atechniqueusedtogainunauthorizedaccesstoacomputer.Thewould-beintrudersendsmessages
tothetargetmachine.ThesemessagescontainanIPaddressindicatingthatthemessagesarecoming
fromatrustedhost.Thetargetmachinerespondstothemessages,givingtheintruder(privileged)
accesstothetarget.
IPC
Interprocesscommunication.Amethodtocommunicatespecificinformationbetweenprograms.
IPv4
IPversion4.
Seealso[IP]
Seealso[IPv6]
IPv6
IPversion6.ThenextgenerationofInternetProtocol,whichprovidesamuchlargeraddressspace
(2128bitsversus232bitsforIPv4)thatisdesignedtoaccommodatetherapidlygrowingnumberof
Internetaddressabledevices.IPv6alsohasbuilt-inautoconfiguration,enhancedsecurity,better
multicastsupport,andmanyotherfeatures.
ISDN
IntegratedServicesDigitalNetwork.Asetofcommunicationsstandardsthatallowsasinglepairof
digitalorstandardtelephonewirestocarryvoice,data,andvideoatarateof64kilobitsper
second.
ISO
InternationalOrganizationforStandardization.Avoluntary,nontreatyorganizationfoundedin1946.
Itisresponsibleforcreatinginternationalstandardsinmanyareas,includingcomputersand
communications.Itsmembersarethenationalstandardsorganizationsof89countries,includingthe
AmericanNationalStandardsInstitute.FOLDOC
ISO9660
TheISOstandarddefiningafilesystemforCD-ROMs.
ISP
Internetserviceprovider.ProvidesInternetaccesstoitscustomers.
jobcontrol
Afacilitythatenablesyoutomovecommandsfromtheforegroundtothebackgroundandviceversa.
Jobcontrolenablesyoutostopcommandstemporarily.
journalingfilesystem
Afilesystemthatmaintainsanoncachedlogfile,orjournal,whichrecordsalltransactionsinvolving
thefilesystem.Whenatransactioniscomplete,itismarkedascompleteinthelogfile.
Thelogfileresultsingreatlyreducedtimespentrecoveringafilesystemafteracrash,makingit
particularlyvaluableinsystemswherehighavailabilityisanissue.
JPEG
JointPhotographicExpertsGroup.Thiscommitteedesignedthestandardimage-compression
algorithm.JPEGisintendedforcompressingeitherfull-colororgray-scaledigitalimagesofnatural,
real-worldscenesanddoesnotworkaswellonnonrealisticimages,suchascartoonsorline
drawings.Filenameextensions:.jpg,.jpeg.FOLDOC
justify
Toexpandalineoftypeintheprocessofformattingtext.Ajustifiedlinehasevenmargins.Alineis
justifiedbyincreasingthespacebetweenwordsandsometimesbetweenlettersontheline.
Kerberos
AnMIT-developedsecuritysystemthatauthenticatesusersandmachines.Itdoesnotprovide
authorizationtoservicesordatabases;itestablishesidentityatlogon,whichisusedthroughoutthe
session.Onceyouareauthenticated,youcanopenasmanyterminals,windows,services,orother
networkaccessesasyoulikeuntilyoursessionexpires.
kernel
Thepartoftheoperatingsystemthatallocatesmachineresources,includingmemory,diskspace,and
CPU(page869)cycles,toallotherprogramsthatrunonacomputer.Thekernelincludesthelow-
levelhardwareinterfaces(drivers)andmanagesprocesses(page894),themeansbywhichLinux
executesprograms.ThekernelisthepartoftheLinuxsystemthatLinusTorvaldsoriginallywrote
(seethebeginningofChapter1).
kernelspace
Thepartofmemory(RAM)wherethekernelresides.Coderunninginkernelspacehasfullaccessto
hardwareandallotherprocessesinmemory.SeetheKernelAnalysis-HOWTO.
keybinding
Akeyboardkeyissaidtobeboundtotheactionthatresultsfrompressingit.Typicallykeysare
boundtothelettersthatappearonthekeycaps:WhenyoupressA,anAappearsonthescreen.Key
bindingusuallyreferstowhathappenswhenyoupressacombinationofkeys,oneofwhichis
CONTROL,ALT,META,orSHIFT,orwhenyoupressaseriesofkeys,thefirstofwhichis
typicallyESCAPE.
keyboard
Ahardwareinputdeviceconsistingofanumberofmechanicalbuttons(keys)thattheuserpressesto
inputcharacterstoacomputer.Bydefaultakeyboardisconnectedtostandardinputofashell.FOLDOC
kilo-
Inthebinarysystem,theprefixkilo-multipliesby210(i.e.,1,024).Kilobitandkilobytearecommon
usesofthisprefix.Abbreviatedask.
KornShell
ksh.Acommandprocessor,developedbyDavidKornatAT&TBellLaboratories,thatis
compatiblewiththeBourneShellbutincludesmanyextensions.
Seealso[shell]
LAN
Localareanetwork.Anetworkthatconnectscomputerswithinalocalizedarea(suchasasinglesite,
building,ordepartment).
largenumber
Gotomathworld.wolfram.com/LargeNumber.htmlforacomprehensivelist.
LDAP
LightweightDirectoryAccessProtocol.Asimpleprotocolforaccessingonlinedirectoryservices.
TraditionallyLDAPhasbeenusedtoaccessinformationsuchasemaildirectories;insomecases,it
canbeusedasanalternativeforservicessuchasNIS.Givenaname,manymailclientscanuse
LDAPtodiscoverthecorrespondingemailaddress.
Seealso[directoryservice]
leaf
Inatreestructure,theendofabranchthatcannotsupportotherbranches.WhentheLinuxfilesystem
hierarchyisconceptualizedasatree,filesthatarenotdirectoriesareleaves.
Seealso[node]
leastprivilege,conceptof
MistakesthatSuperusermakescanbemuchmoredevastatingthanthosemadebyanordinaryuser.
Whenyouareworkingonthecomputer,especiallywhenyouareworkingasthesystem
administrator,alwaysperformanytaskusingtheleastprivilegepossible.Ifyoucanperformatask
loggedinasanordinaryuser,doso.IfyoumustbeloggedinasSuperuser,doasmuchasyoucanas
anordinaryuser,loginassusothatyouareSuperuser,doasmuchofthetaskthathastobedoneas
Superuser,andreverttobeinganordinaryuserassoonasyoucan.
Becauseyouaremorelikelytomakeamistakewhenyouarerushing,thisconceptbecomesmore
importantwhenyouhavelesstimetoapplyit.Alsorootuserorjustroot.
LightweightDirectoryAccessProtocol
See[LDAP]
link
Apointertoafile.Twokindsoflinksexist:hardlinksandsymbolic(soft)links.Ahardlink
associatesafilenamewithaplaceonthediskwherethecontentsofthefileislocated.Asymbolic
linkassociatesafilenamewiththepathnameofahardlinktoafile.
Seealso[hardlink]
Seealso[symboliclink]
Linux-PAM
See[PAM]
Linux-PluggableAuthenticationModules
See[PAM]
loadablekernelmodule
See[loadablemodule]
loadablemodule
Aportionoftheoperatingsystemthatcontrolsaspecialdeviceandthatcanbeloadedautomatically
intoarunningkernelasneededtoaccessthatdevice.
localareanetwork
See[LAN]
locale
Thelanguage;date,time,andcurrencyformats;charactersets;andsoforththatpertaintoa
geopoliticalplaceorarea.Forexample,en_USspecifiesEnglishasspokenintheUnitedStatesand
dollars;en_UKspecifiesEnglishasspokenintheUnitedKingdomandpounds.Seethelocale(5)
manpageformoreinformation.Alsothelocaleutility.
login
Togainaccesstoacomputersystembyrespondingcorrectlytothelogin:andPassword:prompts.
Alsologon,login.
logout
Toendyoursessionbyexitingfromyourloginshell.Alsologoff.
logicalexpression
Acollectionofstringsseparatedbylogicaloperators(>,>=,=,!=,<=,and<)thatcanbeevaluated
astrueorfalse.AlsoBooleanexpression.
.loginfile
Afileinauser'shomedirectorythattheTCShellexecuteswhenyoulogin.Youcanusethisfileto
setenvironmentvariablesandtoruncommandsthatyouwantexecutedatthebeginningofeach
session.
loginname
Thenameyouenterinresponsetothelogin:prompt.Otherusersuseyourloginnamewhentheysend
youmailorwritetoyou.EachloginnamehasacorrespondinguserID,whichisthenumeric
identifierfortheuser.BoththeloginnameandtheuserIDarestoredinthepasswddatabase
(/etc/passwdortheNISequivalent).
loginshell
Theshellthatyouareusingwhenyoulogin.Theloginshellcanforkotherprocessesthatcanrun
othershells,utilities,andprograms.
logoutfile
Afileinauser'shomedirectorythattheTCShellexecuteswhenyoulogout,assumingthattheTC
Shellisyourloginshell.Youcanputinthe.logoutfilecommandsthatyouwantruneachtimeyou
logout.
MACaddress
MediaAccessControladdress.Theuniquehardwareaddressofadeviceconnectedtoashared
networkmedium.EachEthernetadapterhasagloballyuniqueMACaddressinROM.MAC
addressesare6byteslong,enabling2566(about300trillion)possibleaddressesor65,536
addressesforeachpossibleIPv4address.
AMACaddressperformsthesameroleforEthernetthatanIPaddressperformsforTCP/IP:It
providesauniquewaytoidentifyahost.
machinecollatingsequence
Thesequenceinwhichthecomputerorderscharacters.Themachinecollatingsequenceaffectsthe
outcomeofsortsandotherproceduresthatputlistsinalphabeticalorder.ManycomputersuseASCII
codessotheirmachinecollatingsequencescorrespondtotheorderingoftheASCIIcodesfor
characters.
macro
Asingleinstructionthataprogramreplacesbyseveral(usuallymorecomplex)instructions.TheC
compilerrecognizesmacros,whicharedefinedusinga#defineinstructiontothepreprocessor.
magicnumber
Amagicnumber,whichoccursinthefirst512bytesofabinaryfile,isa1-,2-,or4-bytenumeric
valueorcharacterstringthatuniquelyidentifiesthetypeoffile(muchlikeaDOS3-character
filenameextension).See/usr/share/magicandthemagicmanpage(5)formoreinformation.
mainmemory
Randomaccessmemory(RAM),anintegralpartofthecomputer.Althoughdiskstorageissometimes
referredtoasmemory,itisneverreferredtoasmainmemory.
majordevicenumber
Anumberassignedtoaclassofdevices,suchasterminals,printers,ordiskdrives.Usingthels
utilitywiththeloptiontolistthecontentsofthe/devdirectorydisplaysthemajorandminordevice
numbersofmanydevices(asmajor,minor).
MAN
Metropolitanareanetwork.AnetworkthatconnectscomputersandLANs(page884)atmultiple
sitesinasmallregionalarea,suchasacity.
masquerade
ToappeartocomefromonedomainorIPaddresswhenactuallycomingfromanother.Saidofa
packet(iptables)ormessage(sendmail).
MD5
MessageDigest5.Aone-wayhashfunction(page891).
MDA
Maildeliveryagent.Oneofthethreecomponentsofamailsystem;theothertwoaretheMTAand
MUA.AnMDAacceptsinboundmailfromanMTAanddeliversittoalocaluser.
mega-
Inthebinarysystem,theprefixmega-multipliesby220(i.e.,1,048,576).Megabitandmegabyteare
commonusesofthisprefix.AbbreviatedasM.
menu
Alistfromwhichtheusermayselectanoperationtobeperformed.Thisselectionisoftenmade
withamouseorotherpointingdeviceunderaGUIbutmayalsobecontrolledfromthekeyboard.
Veryconvenientforbeginners,menusshowwhichcommandsareavailableandfacilitate
experimentingwithanewprogram,oftenreducingtheneedforuserdocumentation.Experienced
usersusuallypreferkeyboardcommands,especiallyforfrequentlyusedoperations,becausetheyare
fastertouse.FOLDOC
merge
Tocombinetwoorderedlistssothattheresultinglistisstillinorder.Thesortutilitycanmerge
files.
METAkey
Onthekeyboard,akeythatislabeledMETAorALT.UsethiskeyasyouwouldtheSHIFTkey.
Whileholdingitdown,pressanotherkey.TheemacseditormakesextensiveuseoftheMETAkey.
metacharacter
Acharacterthathasaspecialmeaningtotheshelloranotherprograminaparticularcontext.
Metacharactersareusedintheambiguousfilereferencesrecognizedbytheshellandintheregular
expressionsrecognizedbyseveralutilities.Youmustquoteametacharacterifyouwanttouseit
withoutinvokingitsspecialmeaning.
Seealso[regularcharacter]
Seealso[specialcharacter]
metadata
Dataaboutdata.Indataprocessing,metadataisdefinitionaldatathatprovidesinformationabout,or
documentationof,otherdatamanagedwithinanapplicationorenvironment.
Forexample,metadatacandocumentdataaboutdataelementsorattributes(name,size,datatype,
andsoon),recordsordatastructures(page870)(length,fields,columns,andsoon),anddataitself
(whereitislocated,howitisassociated,whoownsit,andsoon).Metadatacanincludedescriptive
informationaboutthecontext,qualityandcondition,orcharacteristicsofthedata.FOLDOC
metropolitanareanetwork
See[MAN]
MIME
MultipurposeInternetMailExtension.Originallyusedtodescribehowspecifictypesoffilesthat
wereattachedtoemailweretobehandled.TodayMIMEtypesdescribehowafileistobeopened
orworkedwith,basedonitsfilenameextension.
minimize
See[iconify]
minordevicenumber
Anumberassignedtoaspecificdevicewithinaclassofdevices.
Seealso[majordevicenumber]
modem
Modulator/demodulator.Aperipheraldevicethatmodulatesdigitaldataintoanalogdatafor
transmissionoveravoice-gradetelephoneline.Anothermodemdemodulatesthedataattheother
end.
module
See[loadablemodule]
mount
Tomakeafilesystemaccessibletosystemusers.Whenafilesystemisnotmounted,youcannotread
fromorwritetofilesitcontains.
mountpoint
Adirectorythatyoumountalocalorremotefilesystemon.
mouse
Adeviceyouusetopointtoaparticularlocationonadisplayscreen,typicallysoyoucanchoosea
menuitem,drawaline,orhighlightsometext.Youcontrolapointeronthescreenbyslidingamouse
aroundonaflatsurface;thepositionofthepointermovesrelativetothemovementofthemouse.
Youselectitemsbypressingoneormorebuttonsonthemouse.
mousepointer
InaGUI,amarkerthatmovesincorrespondencewiththemouse.ItisusuallyasmallblackXwitha
whiteborderoranarrow.Differsfromthecursor(page870).
mouseover
Theactionofpassingthemousepointeroveraniconorotherobjectonthescreen.
MTA
Mailtransferagent.Oneofthethreecomponentsofamailsystem;theothertwoaretheMDAand
MUA.AnMTAacceptsmailfromusersandMTAs.
MUA
Mailuseragent.Oneofthethreecomponentsofamailsystem;theothertwoaretheMDAandMTA.
AnMUAisanend-usermailprogramsuchasKmail,mutt,orOutlook.
multibootspecification
Specifiesaninterfacebetweenabootloaderandanoperatingsystem.Withcompliantbootloaders
andoperatingsystems,anybootloadershouldbeabletoloadanyoperatingsystem.Theobjectof
thisspecificationistoensurethatdifferentoperatingsystemswillworkonasinglemachine.For
moreinformation,gotoodin-os.sourceforge.net/guides/multiboot.html.
multicast
Amulticastpackethasonesourceandmultipledestinations.Inmulticast,sourcehostsregisterata
specialaddresstotransmitdata.Destinationhostsregisteratthesameaddresstoreceivedata.In
contrasttobroadcast(page865),whichisLAN-based,multicasttrafficisdesignedtoworkacross
routednetworksonasubscriptionbasis.Multicastreducesnetworktrafficbytransmittingapacket
onetime,withtherouterattheendofthepathbreakingitapartasneededformultiplerecipients.
multitasking
Acomputersystemthatallowsausertorunmorethanonejobatatime.Amultitaskingsystem,such
asLinux,allowsyoutorunajobinthebackgroundwhilerunningajobintheforeground.
multiusersystem
Acomputersystemthatcanbeusedbymorethanonepersonatatime.Linuxisamultiuseroperating
system.Contrastwithsingle-usersystem(page900).
NAT
NetworkAddressTranslation.AschemethatenablesaLANtouseonesetofIPaddressesinternally
andadifferentsetexternally.TheinternalsetisforLAN(private)use.Theexternalsetistypically
usedontheInternetandisInternetunique.NATprovidessomeprivacybyhidinginternalIP
addressesandallowsmultipleinternaladdressestoconnecttotheInternetthroughasingleexternal
IPaddress.
NBT
NetBIOSoverTCP/IP.AprotocolthatsupportsNetBIOSservicesinaTCP/IPenvironment.Also
NetBT.
NetBIOS
NetworkBasicInput/OutputSystem.AnAPI(page861)forwritingnetwork-awareapplications.
netboot
Tobootacomputeroverthenetwork(asopposedtobootingfromalocaldisk).
netiquette
Theconventionsofetiquettethatis,politebehaviorrecognizedonUsenetandinmailinglists,suchas
not(cross-)postingtoinappropriategroupsandrefrainingfromcommercialadvertisingoutsidethe
businessgroups.
Themostimportantruleofnetiquetteis"Thinkbeforeyoupost."Ifwhatyouintendtopostwillnot
makeapositivecontributiontothenewsgroupandbeofinteresttoseveralreaders,donotpostit.
Personalmessagestooneortwoindividualsshouldnotbepostedtonewsgroups;useprivateemail
instead.FOLDOC
netmask
A32-bitmask(forIPv4),thatshowshowanInternetaddressistobedividedintonetwork,subnet,
andhostparts.Thenetmaskhasonesinthebitpositionsinthe32-bitaddressthataretobeusedfor
thenetworkandsubnetpartsandzerosforthehostpart.Themaskshouldcontainatleastthe
standardnetworkportion(asdeterminedbytheaddressclass).Thesubnetfieldshouldbe
contiguouswiththenetworkportion.FOLDOC
networkaddress
Thenetworkportion(netid)ofanIPaddress.ForaclassAnetwork,itisthefirstbyte,orsegment,
oftheIPaddress;foraclassBnetwork,itisthefirsttwobytes;andforaclassCnetwork,itisthe
firstthreebytes.IneachcasethebalanceoftheIPaddressisthehostaddress(hostid).Assigned
networkaddressesaregloballyuniquewithintheInternet.Alsonetworknumber.
NetworkFilesystem
See[NFS]
NetworkInformationService
See[NIS]
networknumber
See[networkaddress]
networksegment
ApartofanEthernetorothernetworkonwhichallmessagetrafficiscommontoallnodes;thatis,it
isbroadcastfromonenodeonthesegmentandreceivedbyallothers.Thiscommonalitynormally
occursbecausethesegmentisasinglecontinuousconductor.Communicationbetweennodeson
differentsegmentsisviaoneormorerouters.FOLDOC
networkswitch
Aconnectingdeviceinnetworks.Switchesareincreasinglyreplacingsharedmediahubsinaneffort
toincreasebandwidth.Forexample,a16-port10BaseThubsharesthetotal10megabitspersecond
bandwidthwithall16attachednodes.Byreplacingthehubwithaswitch,bothsenderandreceiver
cantakeadvantageofthefull10megabitspersecondcapacity.Eachportontheswitchcangivefull
bandwidthtoasingleserverorclientstationortoahubwithseveralstations.Networkswitchrefers
toadevicewithintelligence.Contrastwithhub(page880).
NetworkTimeProtocol
See[NTP]
NFS
NetworkFilesystem.AremotefilesystemdesignedbySunMicrosystems,availableoncomputers
frommostUNIXsystemvendors.
NIC
Networkinterfacecard(orcontroller).Anadaptercircuitboardinstalledinacomputertoprovidea
physicalconnectiontoanetwork.FOLDOC
NIS
NetworkInformationService.Adistributedservicebuiltonashareddatabasetomanagesystem-
independentinformation(suchasloginnamesandpasswords).
NISdomainname
AnamethatdescribesagroupofsystemsthatshareasetofNISfiles.Differentfromdomainname
(page873).
NNTP
NetworkNewsTransferProtocol.
node
Inatreestructure,theendofabranchthatcansupportotherbranches.WhentheLinuxfilesystem
hierarchyisconceptualizedasatree,directoriesarenodes.
Seealso[leaf]
nonprintingcharacter
Alsononprintablecharacter.
Seealso[controlcharacter]
nonvolatilestorage
Astoragedevicewhosecontentsarepreservedwhenitspowerisoff.AlsoNVSandpersistent
storage.SomeexamplesareCD-ROM,paperpunchtape,harddisk,ROM(page898),PROM(page
895),EPROM(page874),andEEPROM(page873).ContrastwithRAM(page896).
NTP
NetworkTimeProtocol.BuiltontopofTCP/IP,NTPmaintainsaccuratelocaltimebyreferringto
knownaccurateclocksontheInternet.
nullstring
Astringthatcouldcontaincharactersbutdoesnot.Astringofzerolength.
octalnumber
Abase8number.Octalnumbersarecomposedofthedigits07,inclusive.RefertoTableG-1on
page879.
one-wayhashfunction
Aone-wayfunctionthattakesavariable-lengthmessageandproducesafixed-lengthhash.Giventhe
hash,itiscomputationallyinfeasibletofindamessagewiththathash;infact,youcannotdetermine
anyusableinformationaboutamessagewiththathash.Alsomessagedigestfunction.
Seealso[hash]
OpenSSH
AfreeversionoftheSSH(secureshell)protocolsuitethatreplacesTELNET,rlogin,andmore
withsecureprogramsthatencryptallcommunicationevenpasswordsoveranetwork.
operatingsystem
Acontrolprogramforacomputerthatallocatescomputerresources,schedulestasks,andprovides
theuserwithawaytoaccessresources.
option
Acommandlineargumentthatmodifiestheeffectsofacommand.Optionsareusuallyprecededby
hyphensonthecommandlineandtraditionallyhavesingle-characternames(suchashorn).Some
commandsallowyoutogroupoptionsfollowingasinglehyphen(forexample,hn).GNUutilities
frequentlyhavetwoargumentsthatdothesamething:asingle-characterargumentandalonger,more
descriptiveargumentthatisprecededbytwohyphens(suchasshow-allandinvert-match).
ordinaryfile
Afilethatisusedtostoreaprogram,text,orotheruserdata.
Seealso[directory]
Seealso[devicefile]
output
Informationthataprogramsendstotheterminaloranotherfile.
Seealso[standardoutput]
P2P
Peer-to-Peer.Anetworkthatdoesnotdividenodesintoclientsandservers.EachcomputeronaP2P
networkcanfulfilltherolesofclientandserver.Inthecontextofafile-sharingnetwork,thisability
meansthatonceanodehasdownloaded(partof)afile,itcanactasaserver.BitTorrentimplements
aP2Pnetwork.
packet
Aunitofdatasentacrossanetwork.Packetisagenerictermusedtodescribeaunitofdataatany
layeroftheOSIprotocolstack,butitismostcorrectlyusedtodescribenetworkorapplicationlayer
dataunits("applicationprotocoldataunit,"APDU).FOLDOC
Seealso[frame]
Seealso[datagram]
packetfiltering
Atechniqueusedtoblocknetworktrafficbasedonspecifiedcriteria,suchastheorigin,destination,
ortypeofeachpacket.
Seealso[firewall]
packetsniffer
Aprogramordevicethatmonitorspacketsonanetwork.
Seealso[sniff]
pager
Autilitythatallowsyoutoviewafileonescreenatatime(forexample,lessandmore).
paging
Theprocessbywhichvirtualmemoryismaintainedbytheoperatingsystem.Thecontentsofprocess
memoryismoved(pagedout)totheswapspace(page904)asneededtomakeroomforother
processes.
PAM
Linux-PAMorLinux-PluggableAuthenticationModules.Thesemodulesallowasystem
administratortodeterminehowvariousapplicationsauthenticateusers.
parentprocess
Aprocessthatforksotherprocesses.
Seealso[process]
Seealso[childprocess]
partition
Asectionofa(hard)diskthathasanamesoyoucanaddressitseparatelyfromothersections.A
diskpartitioncanholdafilesystemoranotherstructure,suchastheswaparea.UnderDOSand
Windows,partitions(andsometimeswholedisks)arelabeledC:,D:,andsoon.Alsodiskpartition
andslice.
passiveFTP
AllowsFTPtoworkthroughafirewallbyallowingtheflowofdatatobeinitiatedandcontrolledby
theclientFTPprograminsteadoftheserver.AlsocalledPASVFTPbecauseitusestheFTPPASV
command.
passphrase
Astringofwordsandcharactersthatyoutypeintoauthenticateyourself.Apassphrasediffersfroma
passwordonlyinlength.Apasswordisusuallyshort6to10characters.Apassphraseisusually
muchlongerupto100charactersormore.Thegreaterlengthmakesapassphrasehardertoguessor
reproducethanapasswordandthereforemoresecure.FOLDOC
password
Topreventunauthorizedaccesstoauser'saccount,anarbitrarystringofcharacterschosenbythe
userorsystemadministratorandusedtoauthenticatetheuserwhenattemptingtologin.FOLDOC
Seealso[passphrase]
PASVFTP
See[passiveFTP]
pathname
Alistofdirectoriesseparatedbyslashes(/)andendingwiththenameofafile,whichcanbea
directory.Apathnameisusedtotraceapaththroughthefilestructuretolocateoridentifyafile.
pathname,lastelementofa
Thepartofapathnamefollowingthefinal/,orthewholefilenameifthereisno/.Asimple
filename.Alsobasename.
pathnameelement
Oneofthefilenamesthatformsapathname.
peripheraldevice
See[device]
persistent
Datathatisstoredonnonvolatilemedia,suchasaharddisk.
physicaldevice
Atangibledevice,suchasadiskdrive,thatisphysicallyseparatefromother,similardevices.
PID
Processidentification,usuallyfollowedbythewordnumber.LinuxassignsauniquePIDnumberas
eachprocessisinitiated.
pipe
Aconnectionbetweenprogramssuchthatstandardoutputofoneprogramisconnectedtostandard
inputofthenext.Alsopipeline.
pixel
Thesmallestelementofapicture,typicallyasingledotonadisplayscreen.
plaintext
Textthatisnotencrypted.Alsocleartext.Contrastwithciphertext(page867).
PluggableAuthenticationModules
See[PAM]
point-to-pointlink
Aconnectionlimitedtotwoendpoints,suchastheconnectionbetweenapairofmodems.
port
Alogicalchannelorchannelendpointinacommunicationssystem.TheTCP(page905)andUDP
(page907)transportlayerprotocolsusedonEthernetuseportnumberstodistinguishbetween
differentlogicalchannelsonthesamenetworkinterfaceonthesamecomputer.
The/etc/servicesfile(seethebeginningofthisfileformoreinformation)ortheNIS(page890)
servicesdatabasespecifiesauniqueportnumberforeachapplicationprogram.Thenumberlinks
incomingdatatothecorrectservice(program).Standard,well-knownportsareusedbyeveryone:
Port80isusedforHTTP(Web)traffic.Someprotocols,suchasTELNETandHTTP(whichisa
specialformofTELNET),havedefaultportsspecifiedasmentionedearlierbutcanuseotherports
aswell.FOLDOC
portforwarding
Theprocessbywhichanetworkportononecomputeristransparentlyconnectedtoaporton
anothercomputer.IfportXisforwardedfromsystemAtosystemB,anydatasenttoportXon
systemAissenttosystemBautomatically.Theconnectioncanbebetweendifferentportsonthetwo
systems.
portmapper
AserverthatconvertsTCP/IPportnumbersintoRPC(page899)programnumbers.
printablecharacter
Oneofthegraphiccharacters:aletter,number,orpunctuationmark.Contrastwithanonprintable,or
control,character.Alsoprintingcharacter.
privateaddressspace
IANA(page880)hasreservedthreeblocksofIPaddressesforprivateinternetsorLANs:
10.0.0.0-10.255.255.255
172.16.0.0-172.31.255.255
192.168.0.0-192.168.255.255
YoucanusetheseaddresseswithoutcoordinatingwithanyoneoutsideofyourLAN(youdonothave
toregisterthesystemnameoraddress).SystemsusingtheseIPaddressescannotcommunicate
directlywithhostsusingtheglobaladdressspacebutmustgothroughagateway.Becauseprivate
addresseshavenoglobalmeaning,routinginformationisnotstoredbyDNSsandmostISPsreject
privatelyaddressedpackets.Makesurethatyourrouterissetupnottoforwardthesepacketsonto
theInternet.
privilegedport
Aport(page893)withanumberlessthan1,024.OnLinuxandotherUNIX-likesystems,onlyroot
canbindtoaprivilegedport.AnyuseronWindows98andearlierWindowssystemscanbindtoany
port.
procedure
Asequenceofinstructionsforperformingaparticulartask.Mostprogramminglanguages,including
machinelanguages,enableaprogrammertodefineproceduresthatallowtheprocedurecodetobe
calledfrommultipleplaces.Alsosubroutine.FOLDOC
process
TheexecutionofacommandbyLinux.See"Processes"onpage292.
.profilefile
Astartupfileinauser'shomedirectorythattheBourneAgainShellexecuteswhenyoulogin.The
TCShellexecutes.logininstead.Youcanusethe.profilefiletoruncommands,setvariables,and
definefunctions.
program
Asequenceofexecutablecomputerinstructionscontainedinafile.Linuxutilities,applications,and
shellscriptsareallprograms.Wheneveryourunacommandthatisnotbuiltintoashell,youare
executingaprogram.
PROM
Programmablereadonlymemory.Akindofnonvolatilestorage.ROM(page898)thatcanbewritten
tousingaPROMprogrammer.
prompt
Acuefromaprogram,usuallydisplayedonthescreen,indicatingthatitiswaitingforinput.The
shelldisplaysaprompt,asdosomeoftheinteractiveutilities,suchasmail.BydefaulttheBourne
AgainandZShellsuseadollarsign($)asaprompt,andtheTCShellusesapercentsign(%).
protocol
Asetofformalrulesdescribinghowtotransmitdata,especiallyacrossanetwork.Low-level
protocolsdefinetheelectricalandphysicalstandards,bitandbyteordering,andtransmission,error
detection,andcorrectionofthebitstream.High-levelprotocolsdealwithdataformatting,including
messagesyntax,terminal-to-computerdialog,charactersets,andsequencingofmessages.FOLDOC
proxy
Aservicethatisauthorizedtoactforasystemwhilenotbeingpartofthatsystem.
Seealso[proxygateway]
Seealso[proxyserver]
proxygateway
Acomputerthatseparatesclients(suchasbrowsers)fromtheInternet,workingasatrustedagent
thataccessestheInternetontheirbehalf.AproxygatewaypassesarequestfordatafromanInternet
service,suchasHTTPfromabrowser/client,toaremoteserver.Thedatathattheserverreturns
goesbackthroughtheproxygatewaytotherequestingservice.Aproxygatewayshouldbe
transparenttotheuser.
Aproxygatewayoftenrunsonafirewall(page875)systemandactsasabarriertomalicioususers.
IthidestheIPaddressesofthelocalcomputersinsidethefirewallfromInternetusersoutsidethe
firewall.
Youcanconfigurebrowsers,suchasMozillaandNetscape,touseadifferentproxygatewayorto
usenoproxyforeachURLaccessmethodincludingFTP,netnews,SNMP,HTTPS,andHTTP.
Seealso[proxy]
proxyserver
Aproxygatewaythatusuallyincludesacache(page866)thatholdsfrequentlyusedWebpagesso
thatthenextrequestforthatpageisavailablelocally(andthereforemorequickly).Thetermsproxy
serverandproxygatewayarefrequentlyinterchangedsothattheuseofcachedoesnotrest
exclusivelywiththeproxyserver.
Seealso[proxy]
Python
Asimple,high-level,interpreted,object-oriented,interactivelanguagethatbridgesthegapbetween
Candshellprogramming.SuitableforrapidprototypingorasanextensionlanguageforC
applications,Pythonsupportspackages,modules,classes,user-definedexceptions,agoodC
interface,anddynamicloadingofCmodules.Ithasnoarbitraryrestrictions.Formoreinformation,
seewww.python.orgFOLDOC
quote
Whenyouquoteacharacter,youtakeawayanyspecialmeaningthatithasinthecurrentcontext.You
canquoteacharacterbyprecedingitwithabackslash.Whenyouareinteractingwiththeshell,you
canalsoquoteacharacterbysurroundingitwithsinglequotationmarks.Forexample,thecommand
echo\*orecho'*'displays*.Thecommandecho*displaysalistofthefilesintheworking
directory.Alsoescape.
Seealso[ambiguousfilereference]
Seealso[metacharacter]
Seealso[regularcharacter]
Seealso[regularexpression]
Seealso[specialcharacter]
radiobutton
Oneofagroupofbuttonssimilartothoseusedtoselectthestationonaradio.Onlyonebuttoncan
beselectedatatime.
RAID
Redundantarrayofinexpensive/independentdisks.Twoormore(hard)diskdrivesusedin
combinationtoimprovefaulttoleranceandperformance.RAIDcanbeimplementedinhardwareor
software.
RAM
Randomaccessmemory.Akindofvolatilestorage.Adatastoragedeviceforwhichtheorderof
accesstodifferentlocationsdoesnotaffectthespeedofaccess.Contrastwithaharddiskortape
drive,whichprovidesquickeraccesstosequentialdatabecauseaccessinganonsequentiallocation
requiresphysicalmovementofthestoragemediumand/orread/writeheadratherthanjustelectronic
switching.Contrastwithnonvolatilestorage(page891).FOLDOC
RAMdisk
RAMthatismadetolooklikeafloppydisketteorharddisk.ARAMdiskisfrequentlyusedaspart
oftheboot(page864)process.
RAS
Remoteaccessserver.Inanetwork,acomputerthatprovidesaccesstoremoteusersviaanalog
modemorISDNconnections.RASincludesthedial-upprotocolsandaccesscontrol
(authentication).Itmaybearegularfileserverwithremoteaccesssoftwareoraproprietarysystem,
suchasShiva'sLANRover.Themodemsmaybeinternalorexternaltothedevice.
RDF
ResourceDescriptionFramework.BeingdevelopedbyW3C(themainstandardsbodyfortheWorld
WideWeb),astandardthatspecifiesamechanismforencodingandtransferringmetadata(page
887).RDFdoesnotspecifywhatthemetadatashouldorcanbe.Itcanintegratemanykindsof
applicationsanddata,usingXMLasaninterchangesyntax.Examplesofthedatathatcanbe
integratedincludelibrarycatalogsandworldwidedirectories;syndicationandaggregationofnews,
software,andcontent;andcollectionsofmusicandphotographs.Gotowww.w3.org/RDFformore
information.
redirection
Theprocessofdirectingstandardinputforaprogramtocomefromafileratherthanfromthe
keyboard.Also,directingstandardoutputorstandarderrortogotoafileratherthantothescreen.
reentrant
Codethatcanhavemultiplesimultaneous,interleaved,ornestedinvocationsthatdonotinterfere
withoneanother.Noninterferenceisimportantforparallelprocessing,recursiveprogramming,and
interrupthandling.
Itisusuallyeasytoarrangeformultipleinvocations(thatis,callstoasubroutine)toshareonecopy
ofthecodeandanyreadonlydata.Forthecodetobereentrant,however,eachinvocationmustuse
itsowncopyofanymodifiabledata(orsynchronizedaccesstoshareddata).Thisgoalismostoften
achievedbyusingastackandallocatinglocalvariablesinanewstackframeforeachinvocation.
Alternatively,thecallermaypassinapointertoablockofmemorythatthatinvocationcanuse
(usuallyforoutput),orthecodemayallocatesomememoryonaheap,especiallyifthedatamust
surviveaftertheroutinereturns.
Reentrantcodeisoftenfoundinsystemsoftware,suchasoperatingsystemsandteleprocessing
monitors.Itisalsoacrucialcomponentofmultithreadedprograms,wherethetermthread-safeis
oftenusedinsteadofreentrant.FOLDOC
regularcharacter
Acharacterthatalwaysrepresentsitselfinanambiguousfilereferenceoranothertypeofregular
expression.Contrastwithspecialcharacter.
regularexpression
Astringcomposedofletters,numbers,andspecialsymbolsthatdefinesoneormorestrings.See
AppendixA.
relativepathname
Apathnamethatstartsfromtheworkingdirectory.Contrastwithabsolutepathname(page860).
remoteaccessserver
See[RAS]
remotefilesystem
Afilesystemonaremotecomputerthathasbeensetupsothatyoucanaccess(usuallyovera
network)itsfilesasthoughtheywerestoredonyourlocalcomputer'sdisks.Anexampleofaremote
filesystemisNFS.
remoteprocedurecall
See[RPC]
resolver
TheTCP/IPlibrarysoftwarethatformatsrequeststobesenttotheDNS(page872)forhostname-to-
Internetaddressconversion.FOLDOC
ResourceDescriptionFramework
See[RDF]
restore
Theprocessofturninganiconintoawindow.Contrastwithiconify(page880)
returncode
See[exitstatus]
RFC
Requestforcomments.Begunin1969,oneofaseriesofnumberedInternetinformationaldocuments
andstandardswidelyfollowedbycommercialsoftwareandfreewareintheInternetand
UNIX/Linuxcommunities.FewRFCsarestandardsbutallInternetstandardsarerecordedinRFCs.
PerhapsthesinglemostinfluentialRFChasbeenRFC822,theInternetelectronicmailformat
standard.
TheRFCsareunusualinthattheyarefloatedbytechnicalexpertsactingontheirowninitiativeand
reviewedbytheInternetatlargeratherthanbeingformallypromulgatedthroughaninstitutionsuch
asANSI.ForthisreasontheyremainknownasRFCs,evenaftertheyareadoptedasstandards.The
RFCtraditionofpragmatic,experience-driven,after-the-factstandardwritingdonebyindividualsor
smallworkinggroupshasimportantadvantagesoverthemoreformal,committee-drivenprocess
typicalofANSIorISO.ForacompletelistofRFCs,gotowww.rfc-editor.org.FOLDOC
roam
Tomoveacomputerbetweenwirelessaccesspoints(page910)onawirelessnetworkwithoutthe
userorapplicationsbeingawareofthetransition.Movingbetweenaccesspointstypicallyresultsin
somepacketloss,althoughthislossistransparenttoprogramsthatuseTCP.
ROM
Readonlymemory.Akindofnonvolatilestorage.Adatastoragedevicethatismanufacturedwith
fixedcontents.Ingeneral,ROMdescribesanystoragesystemwhosecontentscannotbealtered,such
asaphonographrecordorprintedbook.Whenusedinreferencetoelectronicsandcomputers,ROM
describessemiconductorintegratedcircuitmemories,ofwhichseveraltypesexist,andCD-ROM.
ROMisnonvolatilestorageitretainsitscontentsevenafterpowerhasbeenremoved.ROMisoften
usedtoholdprogramsforembeddedsystems,astheseusuallyhaveafixedpurpose.ROMisalso
usedforstorageoftheBIOS(page863)inacomputer.ContrastwithRAM(page896).FOLDOC

rootdirectory
Theancestorofalldirectoriesandthestartofallabsolutepathnames.Thenameoftherootdirectory
is/.
rootfilesystem
Thefilesystemthatisavailablewhenthesystemisbroughtupinsingle-usermode.Thenameofthis
filesystemisalways/.Youcannotunmountormounttherootfilesystem.Youcanremountrootto
changeitsmountoptions.
rootlogin
UsuallytheloginnameofSuperuser(page904).
root(user)
AnothernameforSuperuser(page904).
rotate
Whenafile,suchasalogfile,getsindefinitelylarger,youmustkeepitfromtakinguptoomuch
spaceonthedisk.Becauseyoumayneedtorefertotheinformationinthelogfilesinthenearfuture,
itisgenerallynotagoodideatodeletethecontentsofthefileuntilithasaged.Insteadyoucan
periodicallysavethecurrentlogfileunderanewnameandcreateanew,emptyfileasthecurrent
logfile.Youcankeepaseriesofthesefiles,renamingeachasanewoneissaved.Youwillthen
rotatethefiles.Forexample,youmightremovexyzlog.4,xyzlog.3 xyzlog.4,xyzlog.2
xyzlog.3,xyzlog.1 xyzlog.2,xyzlog xyzlog.1,andcreateanewxyzlogfile.Bythetimeyou
removexyzlog.4,itwillnotcontainanyinformationmorerecentthanyouwanttoremove.
router
Adevice(oftenacomputer)thatisconnectedtomorethanonesimilartypeofnetworktopassdata
betweenthem.
Seealso[gateway]
RPC
Remoteprocedurecall.Acalltoaprocedure(page894)thatactstransparentlyacrossanetwork.
Theprocedureitselfisresponsibleforaccessingandusingthenetwork.TheRPClibrariesmake
surethatnetworkaccessistransparenttotheapplication.RPCrunsontopofTCP/IPorUDP/IP.
RSA
Apublickeyencryptiontechnologythatisbasedonthelackofanefficientwaytofactorverylarge
numbers.Becauseofthislack,ittakesanextraordinaryamountofcomputerprocessingtimeand
powertodeduceanRSAkey.TheRSAalgorithmisthedefactostandardfordatasentoverthe
Internet.
run
Toexecuteaprogram.
Samba
AfreesuiteofprogramsthatimplementtheServerMessageBlock(SMB)protocol.
Seealso[SMB]
schema
WithinaGUI,apatternthathelpsyouseeandinterprettheinformationthatispresentedinawindow,
makingiteasiertounderstandnewinformationthatispresentedusingthesameschema.
scroll
Tomovelinesonaterminalorwindowupanddownorleftandright.
scrollbar
Awidgetfoundingraphicaluserinterfacesthatcontrols(scrolls)whichpartofadocumentis
visibleinthewindow.Awindowcanhaveahorizontalscrollbar,averticalscrollbar(more
common),orboth.FOLDOC
server
Apowerfulcentralizedcomputer(orprogram)designedtoprovideinformationtoclients(smaller
computersorprograms)onrequest.
session
Thelifetimeofaprocess.Foradesktop,itisthedesktopsessionmanager.Foracharacter-based
terminal,itistheuser'sloginshellprocess.InKDE,itislaunchedbykdeinit.Asessionmayalso
bethesequenceofeventsbetweenwhenyoustartusingaprogram,suchasaneditor,andwhenyou
finish.
setgid
Whenyouexecuteafilethathassetgid(setgroupID)permission,theprocessexecutingthefiletakes
ontheprivilegesofthegroupthefilebelongsto.Thelsutilityshowssetgidpermissionasansin
thegroup'sexecutableposition.
Seealso[setuid]
setuid
Whenyouexecuteafilethathassetuid(setuserID)permission,theprocessexecutingthefiletakes
ontheprivilegesoftheownerofthefile.Asanexample,ifyourunasetuidprogramthatremovesall
thefilesinadirectory,youcanremovefilesinanyofthefileowner'sdirectories,evenifyoudonot
normallyhavepermissiontodoso.Whentheprogramisownedbyroot,youcanremovefilesinany
directorythatrootcanremovefilesfrom.Thelsutilityshowssetuidpermissionasansinthe
owner'sexecutableposition.
Seealso[setgid]
sexillion
IntheBritishsystem,1036.IntheAmericansystem,thisnumberisnamedundecillion.
Seealso[largenumber]
share
AdirectoryandthefilesystemhierarchybelowitthataresharedwithanothersystemusingSMB
(page901).AlsoWindowsshare(page910).
sharednetworktopology
Anetwork,suchasEthernet,inwhicheachpacketmaybeseenbysystemsotherthanitsdestination
system.Sharedmeansthatthenetworkbandwidthissharedbyallusers.
shell
ALinuxsystemcommandprocessor.ThethreemajorshellsaretheBourneAgainShell(page864),
theTCShell(page905),andtheZShell(page911).
shellfunction
Aseriesofcommandsthattheshellstoresforexecutionatalatertime.Shellfunctionsarelikeshell
scriptsbutrunmorequicklybecausetheyarestoredinthecomputer'smainmemoryratherthanin
files.Also,ashellfunctionisrunintheenvironmentoftheshellthatcallsit(unlikeashellscript,
whichistypicallyruninasubshell).
shellscript
AnASCIIfilecontainingshellcommands.Alsoshellprogram.
signal
AverybriefmessagethattheUNIXsystemcansendtoaprocess,apartfromtheprocess'sstandard
input.Referto"trap:CatchesaSignal"onpage493.
simplefilename
Asinglefilenamecontainingnoslashes(/).Asimplefilenameisthesimplestformofpathname.
Alsothelastelementofapathname.Alsobasename(page863).
single-usersystem
Acomputersystemthatonlyonepersoncanuseatatime.Contrastwithmultiusersystem(page
889).
SMB
ServerMessageBlock.Developedintheearly1980sbyIntel,Microsoft,andIBM,SMBisa
client/serverprotocolthatisthenativemethodoffileandprintersharingforWindows.Inaddition,
SMBcanshareserialportsandcommunicationsabstractions,suchasnamedpipesandmailslots.
SMBissimilartoaremoteprocedurecall(RPC;page899)thathasbeencustomizedforfilesystem
access.AlsoMicrosoftNetworking.FOLDOC
smiley
Acharacter-basedglyph(page877),typicallyusedinemail,thatconveysanemotion.The
characters:-)inamessageportrayasmileyface(lookatitsideways).Becauseitcanbedifficultto
tellwhenthewriterofanelectronicmessageissayingsomethinginjestorinseriousness,email
usersoftenuse:-)toindicatehumor.Thetwooriginalsmileys,designedbyScottFahlman,were:-)
and:-(.Alsoemoticon,smileys,andsmilies.FormoreinformationsearchonsmileyontheInternet.
smilies
See[smiley]
SMTP
SimpleMailTransferProtocol.Aprotocolusedtotransferelectronicmailbetweencomputers.Itis
aserver-to-serverprotocol,sootherprotocolsareusedtoaccessthemessages.TheSMTPdialog
usuallyhappensinthebackgroundunderthecontrolofamessagetransportsystemsuchas
sendmail.FOLDOC
snap(windows)
Asyoudragawindowtowardanotherwindoworedgeoftheworkspace,itcanmovesuddenlyso
thatitisadjacenttotheotherwindow/edge.Thusthewindowsnapsintoposition.
sneakernet
Usinghand-carriedmagneticmediatotransferfilesbetweenmachines.
sniff
Tomonitorpacketsonanetwork.Asystemadministratorcanlegitimatelysniffpacketsanda
malicioususercansniffpacketstoobtaininformationsuchasusernamesandpasswords.
Seealso[packetsniffer]

SOCKS
AnetworkingproxyprotocolembodiedinaSOCKSserver,whichperformsthesamefunctionsasa
proxygateway(page895)orproxyserver(page895).SOCKSworksattheapplicationlevel,
requiringthatanapplicationbemodifiedtoworkwiththeSOCKSprotocol,whereasaproxy(page
895)makesnodemandsontheapplication.
SOCKSv4doesnotsupportauthenticationorUDPproxy.SOCKSv5supportsavarietyof
authenticationmethodsandUDPproxy.
sort
Toputinaspecifiedorder,usuallyalphabeticornumeric.
SPACEcharacter
Acharacterthatappearsastheabsenceofavisiblecharacter.Eventhoughyoucannotseeit,a
SPACEisaprintablecharacter.ItisrepresentedbytheASCIIcode32(decimal).ASPACE
characterisconsideredablankorwhitespace(page909).
spam
PostingirrelevantorinappropriatemessagestooneormoreUsenetnewsgroupsormailinglistsin
deliberateoraccidentalviolationofnetiquette(page889).Also,sendinglargeamountsof
unsolicitedemailindiscriminately.Thisemailusuallypromotesaproductorservice.Spamisthe
electronicequivalentofjunkmail.FromtheMontyPython"Spam"song.FOLDOC
sparsefile
Afilethatislargebuttakesuplittlediskspace.Thedatainasparsefileisnotdense(thusitsname).
Examplesofsparsefilesarecorefiles,dbmfiles,and/etc/utmp( /var/adm/utmp).
spawn
See[fork]
specialcharacter
Acharacterthathasaspecialmeaningwhenitoccursinanambiguousfilereferenceoranothertype
ofregularexpression,unlessitisquoted.Thespecialcharactersmostcommonlyusedwiththeshell
are*and?.Alsometacharacter(page887)andwildcard.
specialfile
See[devicefile]
spinner
InaGUI,atypeoftextbox(page905)thatholdsanumberyoucanchangebytypingoveritorusing
theupanddownarrowsattheendofthebox.
spoofing
See[IPspoofing]
spool
Toplaceitemsinaqueue,eachwaitingitsturnforsomeaction.Oftenusedwhenspeakingabout
printers.Alsousedtodescribethequeue.
SQL
StructuredQueryLanguage.Alanguagethatprovidesauserinterfacetorelationaldatabase
managementsystems(RDBMS).SQL,thedefactostandard,isalsoanISOandANSIstandardandis
oftenembeddedinotherprogramminglanguages.FOLDOC
squarebracket
Aleftsquarebracket([)orarightsquarebracket(]).Thesespecialcharactersdefinecharacter
classesinambiguousfilereferencesandotherregularexpressions.
SSHCommunicationsSecurity
ThecompanythatcreatedtheoriginalSSH(secureshell)protocolsuite(www.ssh.com).Linuxuses
OpenSSH.
Seealso[OpenSSH]
standarderror
Afiletowhichaprogramcansendoutput.Usuallyonlyerrormessagesaresenttothisfile.Unless
youinstructtheshellotherwise,itdirectsthisoutputtothescreen(thatis,tothedevicefilethat
representsthescreen).
standardinput
Afilefromwhichaprogramcanreceiveinput.Unlessyouinstructtheshellotherwise,itdirectsthis
inputsothatitcomesfromthekeyboard(thatis,fromthedevicefilethatrepresentsthekeyboard).
standardoutput
Afiletowhichaprogramcansendoutput.Unlessyouinstructtheshellotherwise,itdirectsthis
outputtothescreen(thatis,tothedevicefilethatrepresentsthescreen).
startupfile
Afilethattheloginshellrunswhenyoulogin.TheBourneAgainandZShellsrun.profile,andthe
TCShellruns.login.TheTCShellalsoruns.cshrcwheneveranewTCShellorasubshellis
invoked.TheZShellrunsananalogousfilewhosenameisidentifiedbytheENVvariable.
statusline
Thebottom(usuallythetwenty-fourth)lineoftheterminal.Thevimeditorusesthestatuslineto
displayinformationaboutwhatishappeningduringaneditingsession.
stickybit
Anaccesspermissionbitthatcausesanexecutableprogramtoremainontheswapareaofthedisk.It
takeslesstimetoloadaprogramthathasitsstickybitsetthanonethatdoesnot.OnlySuperusercan
setthestickybit.Ifthestickybitissetonadirectorythatispubliclywritable,onlytheownerofa
fileinthatdirectorycanremovethefile.
streamingtape
Atapethatmovesataconstantspeedpasttheread/writeheadsratherthanspeedingupandslowing
down,whichcanslowtheprocessofwritingtoorreadingfromthetape.Aproperblockingfactor
helpsensurethatthetapedevicewillbekeptstreaming.
streams
See[connection-orientedprotocol]
string
Asequenceofcharacters.
stylesheet
See[CSS]
subdirectory
Adirectorythatislocatedwithinanotherdirectory.Everydirectoryexcepttherootdirectoryisa
subdirectory.
subnet
Subnetwork.Aportionofanetwork,whichmaybeaphysicallyindependentnetworksegment,that
sharesanetworkaddresswithotherportionsofthenetworkandisdistinguishedbyasubnetnumber.
Asubnetistoanetworkasanetworkistoaninternet.FOLDOC
subnetaddress
ThesubnetportionofanIPaddress.Inasubnettednetwork,thehostportionofanIPaddressissplit
intoasubnetportionandahostportionusingasubnetmask(alsoaddressmask).
Seealso[subnetnumber]
subnetmask
AbitmaskusedtoidentifywhichbitsinanIPaddresscorrespondtothenetworkaddressandsubnet
portionsoftheaddress.Calledasubnetmaskbecausethenetworkportionoftheaddressis
determinedbythenumberofbitsthataresetinthemask.Thesubnetmaskhasonesinpositions
correspondingtothenetworkandsubnetnumbersandzerosinthehostnumberpositions.Also
addressmask.
subnetnumber
ThesubnetportionofanIPaddress.Inasubnettednetwork,thehostportionofanIPaddressissplit
intoasubnetportionandahostportionusingasubnetmask(alsoaddressmask).
Seealso[subnetaddress]
subpixelhinting
Similartoanti-aliasing(page861)buttakesadvantageofcolorstodotheanti-aliasing.
ParticularlyusefulonLCDscreens.
subroutine
See[procedure]
subshell
Ashellthatisforkedasaduplicateofitsparentshell.Whenyourunanexecutablefilethatcontains
ashellscriptbyusingitsfilenameonthecommandline,theshellforksasubshelltorunthescript.
Also,commandssurroundedwithparenthesesareruninasubshell.
superblock
Ablockthatcontainscontrolinformationforafilesystem.Thesuperblockcontainshousekeeping
information,suchasthenumberofinodesinthefilesystemandfreelistinformation.
superserver
TheextendedInternetservicesdaemon.
Superuser
Aprivilegeduserhavingaccesstoanythinganyothersystemuserhasaccesstoandmore.The
systemadministratormustbeabletobecomeSuperusertoestablishnewaccounts,change
passwords,andperformotheradministrativetasks.TheloginnameofSuperuserisusuallyroot.
Alsorootorrootuser.
swap
Theoperatingsystemmovingaprocessfrommainmemorytoadisk,orviceversa.Swappinga
processtothediskallowsanotherprocesstobeginorcontinueexecution.
swapspace
Anareaofadisk(thatis,aswapfile)usedtostoretheportionofaprocess'smemorythathasbeen
pagedout.Underavirtualmemorysystem,theamountofswapspaceratherthantheamountof
physicalmemorydeterminesthemaximumsizeofasingleprocessandthemaximumtotalsizeofall
activeprocesses.Alsoswapareaorswappingarea.FOLDOC
switch
See[networkswitch]
symboliclink
Adirectoryentrythatpointstothepathnameofanotherfile.Inmostcasesasymboliclinktoafile
canbeusedinthesamewaysahardlinkcanbeused.Unlikeahardlink,asymboliclinkcanspan
filesystemsandcanconnecttoadirectory.
systemadministrator
Thepersonresponsiblefortheupkeepofthesystem.Thesystemadministratorhastheabilitytolog
inasSuperuser.
Seealso[Superuser]
systemconsole
Themainsystemterminal,usuallydirectlyconnectedtothecomputerandtheonethatreceives
systemerrormessages.Alsoconsoleandconsoleterminal.
systemmode
Thedesignationforthestateofthesystemwhileitisdoingsystemwork.Someexamplesaremaking
systemcalls,runningNFSandautofs,processingnetworktraffic,andperformingkerneloperations
onbehalfofthesystem.Contrastwithusermode(page908).
SystemV
OneofthetwomajorversionsoftheUNIXsystem.
TCShell
tcsh.AnenhancedbutcompletelycompatibleversionoftheBSDUNIXCshell,csh.
TCP
TransmissionControlProtocol.ThemostcommontransportlayerprotocolusedontheInternet.This
connection-orientedprotocolisbuiltontopofIP(page882)andisnearlyalwaysseeninthe
combinationTCP/IP(TCPoverIP).TCPaddsreliablecommunication,sequencing,andflowcontrol
andprovidesfull-duplex,process-to-processconnections.UDP(page907),although
connectionless,istheotherprotocolthatrunsontopofIP.FOLDOC
tera-
Inthebinarysystem,theprefixtera-multipliesby240(1,099,511,627,776).Terabyteisacommon
useofthisprefix.AbbreviatedasT.
Seealso[largenumber]
termcap
Terminalcapability.The/etc/termcapfilecontainsalistofvarioustypesofterminalsandtheir
characteristics.SystemVreplacedthefunctionofthisfilewiththeterminfosystem.
terminal
Differentiatedfromaworkstation(page910)byitslackofintelligence,aterminalconnectstoa
computerthatrunsLinux.AworkstationrunsLinuxonitself.
terminfo
Terminalinformation.The/usr/lib/terminfodirectorycontainsmanysubdirectories,eachcontaining
severalfiles.Eachofthosefilesisnamedforandholdsasummaryofthefunctionalcharacteristics
ofaparticularterminal.Visuallyorientedtext-basedprograms,suchasvim,usethesefiles.An
alternativetothetermcapfile.
textbox
InaGUI,aboxyoucantypein.
theme
Definedasanimplicitorrecurrentidea,themeisusedinaGUItodescribealookthatisconsistent
forallelementsofadesktop.Gotothemes.freshmeat.netforexamples.
thicknet
Atypeofcoaxialcable(thick)usedforanEthernetnetwork.Devicesareattachedtothicknetby
tappingthecableatfixedpoints.
thinnet
Atypeofcoaxialcable(thin)usedforanEthernetnetwork.Thinnetcableissmallerindiameterand
moreflexiblethanthicknetcable.Eachdeviceistypicallyattachedtotwoseparatecablesegments
byusingaT-shapedconnector;onesegmentleadstothedeviceaheadofitonthenetworkandoneto
thedevicethatfollowsit.
thread-safe
See[reentrant]
thumb
Themovablebuttoninthescrollbarthatpositionstheimageinthewindow.Thesizeofthethumb
reflectstheamountofinformationinthebuffer.Alsobubble.
TIFF
TaggedImageFileFormat.Afileformatusedforstill-imagebitmaps,storedintaggedfields.
Applicationprogramscanusethetagstoacceptorignorefields,dependingontheir
capabilities.FOLDOC
tiledwindows
Anarrangementofwindowssuchthatnowindowoverlapsanother.Theoppositeofcascading
windows(page866).
timetolive
See[TTL]
toggle
Toswitchbetweenoneoftwopositions.Forexample,theftpglobcommandtogglestheglob
feature:Givethecommandonce,anditturnsthefeatureonoroff;givethecommandagain,andit
setsthefeaturebacktoitsoriginalstate.
token
Abasic,grammaticallyindivisibleunitofalanguage,suchasakeyword,operator,or
identifier.FOLDOC
tokenring
AtypeofLAN(page884)inwhichcomputersareattachedtoaringofcable.Atokenpacket
circulatescontinuouslyaroundthering.Acomputercantransmitinformationonlywhenitholdsthe
token.
tooltip
Aminicontexthelpsystemthatyouactivatebyallowingyourmousepointertohover(page879)
overabutton,icon,orapplet(suchasthoseonapanel).
transientwindow
Adialogorotherwindowthatisdisplayedforonlyashorttime.
TransmissionControlProtocol
See[TCP]
Trojanhorse
Aprogramthatdoessomethingdestructiveordisruptivetoyoursystem.Itsactionisnotdocumented,
andthesystemadministratorwouldnotapproveofitifshewereawareofit.
ThetermTrojanhorsewascoinedbyMIT-hacker-turned-NSA-spookDanEdwards.Itreferstoa
malicioussecurity-breakingprogramthatisdisguisedassomethingbenign,suchasadirectorylister,
archiveutility,game,or(inonenotorious1990caseontheMac)aprogramtofindanddestroy
viruses.Similartobackdoor(page862).FOLDOC
TTL
Timetolive.
1. AllDNSrecordsspecifyhowlongtheyaregoodforusuallyuptoaweekatmost.Thistimeis
calledtherecord'stimetolive.WhenaDNSserveroranapplicationstoresthisrecordin
cache(page866),itdecrementstheTTLvalueandremovestherecordfromcachewhenthe
valuereacheszero.ADNSserverpassesacachedrecordtoanotherserverwiththecurrent
(decremented)TTLguaranteeingtheproperTTL,nomatterhowmanyserverstherecordpasses
through.
2. IntheIPheader,afieldthatindicateshowmanymorehopsthepacketshouldbeallowedto
makebeforebeingdiscardedorreturned.
TTY
Teletypewriter.TheterminaldevicethatUNIXwasfirstrunfrom.TodayTTYreferstothescreen
(orwindow,inthecaseofaterminalemulator),keyboard,andmousethatareconnectedtoa
computer.ThistermappearsinUNIX,andLinuxhaskeptthetermforthesakeofconsistencyand
tradition.
tunneling
EncapsulationofprotocolAwithinpacketscarriedbyprotocolB,suchthatAtreatsBasthoughit
wereadatalinklayer.Tunnelingisusedtotransferdatabetweenadministrativedomainsthatusea
protocolnotsupportedbytheinternetconnectingthosedomains.Itcanalsobeusedtoencryptdata
sentoverapublicinternet,aswhenyouusesshtotunnelaprotocolovertheInternet.FOLDOC
Seealso[VPN]
UDP
UserDatagramProtocol.TheInternetstandardtransportlayerprotocolthatprovidessimplebut
unreliabledatagramservices.UDPisaconnectionlessprotocol(page869)that,likeTCP(page
905),islayeredontopofIP(page882).
UnlikeTCP,UDPneitherguaranteesdeliverynorrequiresaconnection.Asaresultitislightweight
andefficient,buttheapplicationprogrammusthandleallerrorprocessingandretransmission.UDP
isoftenusedforsendingtime-sensitivedatathatisnotparticularlysensitivetominorloss,suchas
audioandvideodata.FOLDOC
UID
UserID.Anumberthatthepasswddatabaseassociateswithaloginname.
undecillion
IntheAmericansystem,1036.IntheBritishsystem,thisnumberisnamedsexillion.
Seealso[largenumber]
unicast
Apacketsentfromonehosttoanotherhost.Unicastmeansonesourceandonedestination.
unmanagedwindow
See[ignoredwindow]
URI
UniformResourceIdentifier.Thegenericsetofallnamesandaddressesthatareshortstrings
referringtoobjects(typicallyontheInternet).ThemostcommonkindsofURIsareURLs.FOLDOC
URL
Uniform(wasUniversal)ResourceLocator.Astandardwayofspecifyingthelocationofanobject,
typicallyaWebpage,ontheInternet.URLsareasubsetofURIs.
usagemessage
Amessagedisplayedbyacommandwhenyoucallthecommandusingincorrectcommandline
arguments.
UserDatagramProtocol
See[UDP]
UserID
See[UID]
userinterface
See[interface]
usermode
Thedesignationforthestateofthesystemwhileitisdoinguserwork,suchasrunningauser
program(butnotthesystemcallsmadebytheprogram).Contrastwithsystemmode(page905).
userspace
Thepartofmemory(RAM)whereapplicationsreside.Coderunninginuserspacecannotaccess
hardwaredirectlyandcannotaccessmemoryallocatedtootherapplications.Alsouserland.Seethe
KernelAnalysis-HOWTO.
UTC
CoordinatedUniversalTime.UTCistheequivalenttothemeansolartimeattheprimemeridian(0
degreeslongitude).AlsocalledZulutime(Zstandsforlongitudezero)andGMT(GreenwichMean
Time).
utility
AprogramincludedasastandardpartofLinux.Youtypicallyinvokeautilityeitherbygivinga
commandinresponsetoashellpromptorbycallingitfromwithinashellscript.Utilitiesareoften
referredtoascommands.Contrastwithbuiltin(command)(page865).
variable
Anameandanassociatedvalue.Theshellallowsyoutocreatevariablesandusetheminshell
scripts.Also,theshellinheritsseveralvariableswhenitisinvoked,anditmaintainsthoseandother
variableswhileitisrunning.Someshellvariablesestablishcharacteristicsoftheshellenvironment;
othershavevaluesthatreflectdifferentaspectsofyourongoinginteractionwiththeshell.
viewport
Sameasworkspace(page910).
virtualconsole
Additionalconsoles,ordisplays,thatyoucanviewonthesystem,orphysical,console.
virus
Acracker(page869)programthatsearchesoutotherprogramsand"infects"thembyembeddinga
copyofitselfinthem,sothattheybecomeTrojanhorses(page906).Whentheseprogramsare
executed,theembeddedvirusisexecutedaswell,propagatingthe"infection,"usuallywithoutthe
user'sknowledge.Byanalogywithbiologicalviruses.FOLDOC
VLAN
VirtualLAN.Alogicalgroupingoftwoormorenodesthatarenotnecessarilyonthesamephysical
networksegmentbutthatsharethesamenetworknumber.AVLANisoftenassociatedwithswitched
Ethernet.FOLDOC
VPN
VirtualPrivateNetwork.Aprivatenetworkthatexistsonapublicnetwork,suchastheInternet.A
VPNisalessexpensivesubstituteforcompany-owned/leasedlinesandusesencryptiontoensure
privacy.Anicesideeffectisthatyoucansendnon-Internetprotocols,suchasAppletalk,IPX,or
NetBIOS,overtheVPNconnectionbytunneling(page907)themthroughtheVPNIPstream.
W2K
Windows2000ProfessionalorServer.
W3C
WorldWideWebConsortium(www.w3.org).
WAN
Wideareanetwork.AnetworkthatinterconnectsLANs(page884)andMANs(page886),spanninga
largegeographicarea(typicallystatesorcountries).
WAP
See[wirelessaccesspoint]
Webring
AcollectionofWebsitesthatprovideinformationonasingletopicorgroupofrelatedtopics.Each
homepagethatispartoftheWebringhasaseriesoflinksthatletyougofromsitetosite.
whitespace
AcollectivenameforSPACEsand/orTABsandoccasionallyNEWLINEs.Alsowhitespace.
wideareanetwork
See[WAN]
widget
Thebasicobjectsofagraphicaluserinterface.Buttons,textfields,andscrollbarsareexamplesof
widgets.
wildcard
See[metacharacter]
Wi-Fi
WirelessFidelity.Agenerictermthatreferstoanytypeof802.11(page860)wirelessnetwork.
window
Onadisplayscreen,aregionthatrunsoriscontrolledbyaparticularprogram.
windowmanager
Aprogramthatcontrolshowwindowsappearonadisplayscreenandhowyoumanipulatethem.
Windowsshare
See[share]
WINS
WindowsInternetNamingService.TheserviceresponsibleformappingNetBIOSnamestoIP
addresses.WINShasthesamerelationshiptoNetBIOSnamesthatDNShastoInternetdomain
names.
WINSserver
TheprogramresponsibleforhandlingWINSrequests.Thisprogramcachesnameinformationabout
hostsonalocalnetworkandresolvesthemtoIPaddresses.
wirelessaccesspoint
Abridgeorrouterbetweenwiredandwirelessnetworks.Wirelessaccesspointstypicallysupport
someformofaccesscontroltopreventunauthorizedclientsfromconnectingtothenetwork.Also
WAP.
word
AsequenceofoneormorenonblankcharactersseparatedfromotherwordsbyTABs,SPACEs,or
NEWLINEs.Usedtorefertoindividualcommandlinearguments.Invim,awordissimilartoa
wordintheEnglishlanguageastringofoneormorecharactersboundedbyapunctuationmark,a
numeral,aTAB,aSPACE,oraNEWLINE.
Workbuffer
Alocationwherevimstorestextwhileitisbeingedited.TheinformationintheWorkbufferisnot
writtentothefileonthediskuntilyougivetheeditoracommandtowriteit.
workingdirectory
Thedirectorythatyouareassociatedwithatanygiventime.Therelativepathnamesyouuseare
relativetotheworkingdirectory.Alsocurrentdirectory.
workspace
Asubdivisionofadesktop(page871)thatoccupiestheentiredisplay.
workstation
Asmallcomputer,typicallydesignedtofitinanofficeandbeusedbyonepersonandusually
equippedwithabit-mappedgraphicaldisplay,keyboard,andmouse.Differentiatedfromaterminal
(page905)byitsintelligence.AworkstationrunsLinuxonitselfwhileaterminalconnectstoa
computerthatrunsLinux.
worm
Aprogramthatpropagatesitselfoveranetwork,reproducingitselfasitgoes.Todaythetermhas
negativeconnotations,asitisassumedthatonlycrackers(page869)writeworms.Comparetovirus
(page909)andTrojanhorse(page906).FromTapeworminJohnBrunner'snovel,TheShockwave
Rider,BallantineBooks,1990(viaXEROXPARC).FOLDOC
WYSIWYG
WhatYouSeeIsWhatYouGet.Agraphicalapplication,suchasawordprocessor,whosedisplayis
similartoitsprintedoutput.
Xterminal
AgraphicsterminaldesignedtoruntheXWindowSystem.
XWindowSystem
Adesignandsetoftoolsforwritingflexible,portablewindowingapplications,createdjointlyby
researchersatMITandseveralleadingcomputermanufacturers.
XDMCP
XDisplayManagerControlProtocol.XDMCPallowstheloginservertoacceptrequestsfrom
networkdisplays.XDMCPisbuiltintomanyXterminals.
xDSL
DifferenttypesofDSL(page873)areidentifiedbyaprefixforexample,ADSL,HDSL,SDSL,and
VDSL.
Xinerama
AnextensiontoXFree86release6version4.0(X4.0).Xineramaallowswindowmanagersand
applicationstousetwoormorephysicaldisplaysasonelargevirtualdisplay.RefertoXinerama-
HOWTO.
XML
ExtensibleMarkupLanguage.AuniversalformatforstructureddocumentsanddataontheWeb.
DevelopedbyW3C(page909),XMLisapared-downversionofSGML.
Seewww.w3.org/XMLandwww.w3.org/XML/1999/XML-in-10-points.
XSM
XSessionManager.Thisprogramallowsyoutocreateasessionthatincludescertainapplications.
Whilethesessionisrunning,youcanperformacheckpoint(savestheapplicationstate)ora
shutdown(savesthestateandexitsfromthesession).Whenyoulogbackin,youcanloadyour
sessionsothateverythinginyoursessionisrunningjustasitwaswhenyouloggedoff.
ZShell
zsh.Ashell(page900)thatincorporatesmanyofthefeaturesoftheBourneAgainShell(page
864),KornShell(page884),andTCShell(page905),aswellasmanyoriginalfeatures.
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
!Booleanoperator2nd3rd4th
!variable
!!toreexecutethepreviousevent
!$lastwordofthepreviousevent
#comment2nd
#variable
#!tochooseascriptshell2nd
#defineCpreprocessordirective2nd3rd
#includeCpreprocessordirective
#Note
Onlyvariablesthatmustalwaysappearwithaleadingdollarsignareindexedwithaleadingdollarsign.
Othervariablesareindexedwithoutaleadingdollarsign.[#zzz]
$inregularexpressions
$invariablename
$!variable
$#variable2nd3rd
$#argvvariable
$$variable2nd3rd4th5th
$(...)[SeeCommand,substitution]
$*variable2nd
$,usewithvariables[$]
$0variable
$<variable
$?variable2nd
$@variable2nd3rd
${},expandvariable
%job&builtin
%jobbuiltin
%jobnumber2nd
&background2nd3rd4th5th6th
&backgroundprocess
&bitwiseoperator2nd
&Booleanoperator
&inreplacementstring2nd
&&Booleanoperator2nd3rd4th5th6th7th
((...))[SeeArithmeticevaluation]
()commandgrouping
()inshellfunctions
*inregularexpressions
*specialcharacter
*/Ccomment
+infullregularexpressions
-aBooleanoperator2nd3rd
-oBooleanoperator2nd
-orBooleanoperator
.(dot)builtin2nd3rd4th
./toexecuteafileintheworkingdirectory2nd
.directory2nd
.inregularexpressions
..directory2nd
.afilenameextension2nd3rd
.aspell.conffile
.bash_historyfile
.bash_loginfile
.bash_logoutfile
.bash_profilefile2nd
.bashrcfile2nd
.bz2filenameextension2nd3rd
.cfilenameextension2nd3rd4th
.Cfilenameextension
.cfilenameextension
.Cfilenameextension
.c++filenameextension
.ccfilenameextension2nd
.cppfilenameextension
.cshrcfile2nd3rd
.cxxfilenameextension2nd
.dir_colorsfile
.emacsfile2nd3rd4th
.ffilenameextension
.giffilenameextension
.gzfilenameextension2nd
.hfilenameextension2nd
.historyfile2nd
.htmlfilenameextension
.ifilenameextension2nd
.iifilenameextension2nd
.inputrcfile
.jpegfilenameextension2nd
.jpgfilenameextension2nd
.lfilenameextension
.loginfile2nd3rd
.logoutfile2nd
.netrcfile
.nofingerfile
.ofilenameextension2nd3rd4th5th
.pdffilenameextension
.pgpkeyfile
.planfile2nd
.profilefile2nd
.projectfile2nd
.psfilenameextension
.rhostsfile2nd3rd4th
.sfilenameextension2nd3rd
.Sfilenameextension
.sfilenameextension
.shfilenameextension
.sofilenameextension2nd
.tar.bz2filenameextension
.tar.gzfilenameextension
.tar.Zfilenameextension2nd
.tcshrcfile2nd
.tgzfilenameextension
.tifffilenameextension
.toprcfile
.torrentfile
.txtfilenameextension2nd
.tzfilenameextension
.vimrcfile2nd
.yfilenameextension
.Zfilenameextension2nd
/directory(root)2nd
/*Ccomment
/bindirectory
/bootdirectory
/dev2nd3rd
nullfile2nd3rd
randomfile
ttyfile
urandomfile
/etc
aspell.conffile
at.allowfile
at.denyfile
bashrcfile
cron.allowfile
cron.dailydirectory
cron.denyfile
cron.hourlydirectory
cron.monthlydirectory
cron.weeklydirectory
crontabfile
csh.cshrcfile
csh.loginfile
csh.logoutfile2nd
DIR_COLORSfile
groupfile
hosts.equivfile2nd3rd
issuefile
man.configfile
motdfile
optdirectory
passwdfile2nd3rd4th5th6th7th8th9th
printcapfile
profilefile
termcapfile
yum.conffile
/homedirectory
/lib2nd
gccand
modulesdirectory
/mntdirectory
/optdirectory
/proccontents
/rootdirectory
/sbindirectory
/tmpdirectory2nd3rd4th
/usr
bin
X11directory
docdirectory
gamesdirectory
include
Cpreprocessor
X11directory
infodirectory
lib
directory
gcc2nd
sharedlibraries
terminfodirectory
X11
localdirectory
mandirectory
pub/asciifile
sbindirectory
share
magicfile
srcdirectory
X11R6directory2nd
/var
log2nd
lastlogfile
messagesfile2nd
securefile
wtmpfile
spool
at
at:spooldirectory
crondirectory
maildirectory
0<redirectstandardinput
1>redirectstandardoutput
2>redirectstandarderror
802.11
:(null)builtin2nd
:=assigndefaultvalue
:=substitutedefaultvalue
:?displayerrormessage
<redirectstandardinput2nd
<$nopage><Z><B>...<Z><I>[SeeCommand,substitution]
<&duplicateinputfiledescriptor
<<heredocument
>redirectstandardoutput2nd3rd4th5th
>&duplicateoutputfiledescriptor2nd
>&redirectstandardoutputandstandarderror
>>appendstandardoutput2nd
?infullregularexpressions
?specialcharacter
@builtin2nd3rd4th
@variable
@vim
[[...]][SeealsoConditionalexpression]
[[...]]builtin
[_]builtin[Seetestbuiltin]
[_]characterclass2nd
[Completion:aaa][SeealsoWord,completion[Completion]
[gcc:aaa][SeealsoCprogramminglanguage[gcc]
[Substitution:aaa][SeealsoExpansion[Substitution]]
\
(null)builtin
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
afilenameextension2nd3rd
a.outfile2nd3rd
Abortexecution
Absolutefilename
Absolutepathname2nd3rd
Access
AccessControlList[SeeACL]
Accesspermission
changeusingchmod2nd
defined2nd
descriptionof
directory
displayusingls
execute2nd
group
other
owner
read
write
ACL2nd
Activewindow
addcommand(cvs)
addbannershellscript
Address
IP
MAC
network
space,private
Addressmask
Administrator,system[SeeSystem,System;administrator]
Algorithm
Alias
bash
defined
doubleversussinglequotationmarks
quotationmarks
recursion
recursiveplunge
singleversusdoublequotationmarks
special
aliasbuiltin2nd3rd
allocbuiltin
Alphanumericcharacter
ALTkey
Ambiguousfilereference2nd3rd
AmericanNationalStandardsInstitute
ANDBooleanoperator2nd
Anglebracket
Animate
AnonymousFTP
ANSI
ANSIC
ansiterminalname
Anti-aliasing2nd
API
Append
defined
standardoutput2nd3rd
appendstandardoutput2nd
Applet
Applicationprogrammer
aproposutility2nd3rd4th
Apt
apt-getcheckcommand
apt-getdist-upgradecommand
apt-getinstallcommand
apt-getremovecommand
apt-getupdatecommand
apt-getupgradecommand
checkingthedependencytree
configuring
updatethelocalpackagelist
using
apt.conffile
apt.freshrpms.net2nd
Archive
library,using
packusingtar
shell
unpackusingtar
Argument2nd
commandline
defined
display
testing
argvvariable
Arithmetic
bash
expansion2nd
expression
Arithmeticevaluation
example2nd3rd
Array
argv
defined
numericvariables
stringvariables
ASCII
codesandemacs
defined
EBCDICconversion
manpage
terminal
asciifile
ASP
aspellutility2nd
aspell.conffile
aspell.sourceforge.net
ASPELL_CONFvariable
Assemblylanguage2nd
Associativearray
Asteriskspecialcharacter
atdirectory
atutility
AT&TBellLaboratories2nd3rd4th
at.allowfile
at.denyfile
atddaemon
atqutility
atrmutility
Attachment
defined
mail
Authentication
defined
OpenSSH
autoconfutility
autocorrectvariable
autolistvariable2nd
autologoutvariable
Automaticmounting
Avoided
awk[Seegawk]
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
Blanguage
Backdoor2nd
Backtick2nd3rd4th
Background
commandgrouping
defined
foreground,versus
jobcontrol2nd
PIDstoredin$!
process2nd
runningacommandin
symbol(&)
BACKSLASHescapecharacter2nd3rd
BACKSLASHinreplacementstrings
BACKSPACEkey
changing
function
badtabs.cprogram
Basename
basenameutility2nd3rd
bash
-xoption
<&duplicateinputfiledescriptor2nd
>&duplicateoutputfiledescriptor2nd
alias
arguments
arithmetic
arithmeticevaluation
example2nd3rd
operators
arithmeticexpansion
operators
arrayvariables
attribute
array
export
function
integer2nd
readonly2nd
background
builtin
_[SeealsoBuiltin]
exec
getopts
kill
typeset
closefile
command
process
substitution
commandline,orderofexpansion
conditionalexpression
example2nd
controlstructure[SeeControl,Filesystem;structure]
defined
directorystackmanipulation
editingpreviouscommands2nd
emacscommandlineeditor
eventnumber
expandnullvariable
expandunsetvariable
expression
features
filedescriptor
globbing
historymechanism2nd
makepathshellscript
menu
openfile2nd
operator
bitwise
remainder
short-circuiting
ternary
options[Seebash,bash;features]
overlay
pathnamecompletion
processsubstitution
programstructures
programming
prompt2nd
PS3prompt
quicksubstitution
quizshellscript
quotationmarkremoval
recursion
redirectionoperators
reexecutingevents2nd
REPLYkeywordvariable
signalnames2nd
specialcharacters
standarderror
standardinput
standardoutput
startupfiles
stringpatternmatching2nd
substitution,quick
symboliclink
tcsh,featuressharedwith
ternaryoperator
tildesubstitution
variable
_[SeealsoVariable]
array
assigndefaultvalue
COLUMNS
displayerrormessage
expansion
LINES
modifier
OPTARG
OPTIND
PS3
REPLY2nd
substitutedefaultvalue2nd
vicommandlineeditor
BASH_ENVvariable
batchutility
Baud
Baudrate
BCPLlanguage
BellLaboratories[SeeAT&TBellLaboratories]
BerkeleyUNIX2nd3rd
bgbuiltin2nd3rd4th
bindirectory
Binaryfile
Binaryfiles,fixingbroken
BIND
bindbuiltin
Binding,key
bindkeybuiltin
BIOSdefined
birthdayshellscript
bisonutility
Bit
Bitbucket
Bitdepth
Bit-mappeddisplay
BitTorrent2nd
peer
prerequisites
seed
torrent
tracker
using
Bitwiseoperator
&2nd
^
|
Blankcharacter2nd3rd4th
Block
defined
device
number
specialfile
Blockingfactor
Booleanoperator
!2nd3rd4th
&
&&2nd3rd4th5th6th7th8th
-a2nd3rd
-o2nd
-or
NOT
SPACE2nd
||
||
Boot
bootstrap
defined
loader
netboot
Bootstrap
BourneAgainShell[Seebash]
BourneShell(original)2nd3rd
Bourne,Steve[Bourne]2nd
Brace
aroundavariable
defined
expansion
shellfunctions
Bracket
characterclass
filenameexpansion
Branch
breakcontrolstructure2nd
breakshellkeyword
breakswshellkeyword2nd
Bridge,network
Broadcast
address
defined2nd
BSD[SeeBerkeleyUNIX]
Buffer
defined
Numbered,vim
Work,vim
Bug
Builtin2nd3rd4th
%job
%job&
.(dot)2nd3rd
:(null)2nd
@2nd3rd4th
[[...]]
[_][Seetestbuiltin]
\
(null)
alias2nd3rd
alloc
bash,listof2nd
bg2nd3rd4th
bind
bindkey
builtins
cd2nd3rd4th5th6th7th8th9th
chdir2nd
command
commandeditingusingfc
declare2nd
defined2nd
dirs2nd3rd4th
echo2nd3rd4th5th6th7th8th9th10th11th12th
eval2nd3rd
exec2nd3rd4th5th6th7th
executionof
exit2nd3rd4th5th6th7th
export2nd3rd4th5th6th
fc
fg2nd3rd4th
filetest2nd
getopts2nd
glob
hashstat
history2nd3rd4th
jobs2nd3rd4th5th6th
kill2nd3rd4th5th6th7th8th
let2nd
limit
locale
log2nd
login
logout2nd3rd
ls-F2nd
nice2nd
nohup
notify
null2nd
onintr2nd
popd2nd3rd
printenv
pushd2nd3rd
pwd2nd3rd4th5th
read2nd3rd4th5th6th
readonly2nd3rd4th
rehash
repeat
sched
set2nd3rd4th5th6th7th8th9th10th11th
setenv2nd3rd
shift2nd3rd4th
source2nd
stop
suspend
tcsh
test2nd3rd4th5th6th7th8th9th10th11th
time2nd
times
tput2nd
trap2nd3rd
type2nd
typeset
ulimit
umask2nd
unalias2nd3rd4th
unhash
unlimit
unset2nd3rd4th5th6th
unsetenv2nd
utility,versus
wait2nd
where
which2nd
builtinsbuiltin
bundleshellscript
bunzip2utility2nd
Byte
bz2filenameextension2nd3rd
bzcatutility2nd
bzip2utility2nd3rd
bzip2recoverutility2nd
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
C[SeeCprogramminglanguage[C]]
cfilenameextension2nd3rd4th
Cfilenameextension
cfilenameextension
Cfilenameextension
Cprogramminglanguage2nd3rd
#includepreprocessordirective
a.outfile
archivedlibrary
assembler
badtabs.cprogram
comments
compiler
phase
using
warningoptions
debugging
defined
expression
functionprototype
functions
getcharmacro
headerfile2nd
includefile2nd
library
libc.so
libm.so
linkeditor
macroexpansion
mainfunction
objectfile2nd
operator
optimizer2nd
portability
preprocessor2nd3rd4th
preprocessordirectives
programming
putcharmacro
sampleprogram
sharedlibrary
staticallylinkedlibrary
stdio.hheaderfile
symbolicdebugger
tabs.cprogram
c++filenameextension
C++programminglanguage
C89programminglanguage
Cablemodem
Cache
calutility
Callbyvalue
Callingenvironment
Callingprogram,nameof
Cambridgeculture
Caretinregularexpressions
Cascadingwindows
casecontrolstructure2nd
Case-sensitive
defined
filename
password
catutility2nd3rd4th5th6th7th
Catenate2nd3rd4th
cc[SeegccorCprogramminglanguage[cc]]
ccfilenameextension2nd
cdbuiltin2nd3rd4th5th6th7th8th9th
CDPATHvariable
cdpathvariable2nd
CDPATHvariable
cdpathvariable
Chainloading
Change
accesspermissionusingchmod
directoriesusingcd
filenameusingmv
passwordusingpasswd
Character
alphanumeric
class2nd3rd
device
escaping
list[SeeCharacter,Character;class]
quoting
specialfile
characterclass2nd
Character-based
defined
terminal
chdirbuiltin
checkoutcommand(cvs)2nd
Checksum
chgrputility
Child
directory2nd
process2nd3rd4th
chkargsshellscript2nd
chmodutility2nd3rd
chmod()systemcall
chownutility
chown()systemcall
chshutility
CIDR
CIFS
CIPE
Cipher
Ciphertext
Class,character
ClasslessInter-DomainRouting[SeeCIDR]
Cleanfilesystem
cleanupshellscript
Clearscreen
Cleartext
CLI
Client
Clones,vi
Closefiles,bash
close()systemcall
cmputility
Code,reentrant
CODEC
Collatingsequence,machine
Colon(
)builtin
Colordepth
Colorquality
COLUMNSvariable
Combobox
Comer,Doug
commutility
Command
;separator
argument
builtin2nd3rd4th
completion
controlflow[SeeControl,Filesystem;structure]
controlstructure[SeeControl,Filesystem;structure]
defined2nd
editingprevious
executionof
grouping2nd
Mode,vim
name
NEWLINEseparator
option
process
reexecutingprevious
repeating
separation
separator2nd
substitution2nd3rd4th5th6th7th
summary
syntax
terminator
usagemessage2nd3rd4th5th
Commandline
argument2nd
defined2nd
editing
execution
expansion2nd3rd
interface
option
parse2nd
processing2nd
syntax
token2nd
whitespace
word2nd
command_menushellscript2nd
Comments
Cprograms
makefile
shellscripts
commitcommand(cvs)
CommonUNIXPrintingSystem[SeeCUPS]
Communication
interprocess
write
comp.os.linux.answersnewsgroup
comp.os.linux.miscnewsgroup
Comparefilesusingdiff
CompilingaCprogram
Completion
command
pathname2nd
ReadlineLibrary
variable
Componentarchitecture
Compress
bunzip2
bzcat
bzip22nd3rd4th
bzip2recover2nd
compress2nd3rd4th5th6th
gunzip
gzip2nd
uncompress
unzip2nd
zcat2nd
zip2nd
compressutility2nd3rd4th
ComputerSystemsResearchGroup,Berkeley
Computer,diskless[Computer]
Computing,distributed
Concatenate[SeeCatenate]
ConcurrentVersionsSystem[SeeUtility;cvs]
Conditioncode[SeeExit,status]
Conditionalexpression
example2nd
configureutility2nd
Connection-orientedprotocol
Connectionless,protocol
Console
system
terminal2nd
virtual2nd
Context,diff
continuecontrolstructure2nd
continueshellkeyword
Control
character
characters,printer
flow[SeeControl,Filesystem;structure]
job
structure2nd
break2nd
case2nd
continue2nd
defined
do2nd3rd4th
done2nd3rd4th
elif2nd
elifversusfi
else
esac
fi2nd3rd
fiversuselif
for2nd3rd
for...in2nd3rd
foreach
goto
if2nd3rd4th5th
if...then
if...then...elif2nd
if...then...else2nd
in
select
shellkeyword:break
shellkeyword:breaksw2nd
shellkeyword:case
shellkeyword:continue
shellkeyword:default
shellkeyword:else
shellkeyword:endsw
shellkeyword:switch
shellkeyword:then
shellkeyword:while
shellscripts
switch
then2nd3rd
two-waybranch
until2nd
while2nd3rd4th5th6th
CONTROLkey
CONTROL-Ckey2nd
CONTROL-Dkey2nd3rd4th
CONTROL-Hkey2nd3rd4th5th6th
CONTROL-Lkey2nd3rd
CONTROL-Mkey
CONTROL-Qkey
CONTROL-Rkey
CONTROL-Ukey2nd3rd4th5th
CONTROL-Vkey
CONTROL-Wkey2nd3rd4th
CONTROL-Xkey
CONTROL-Zkey2nd
Conventions
filenaming
usedinthisbook
Convertfileto/fromWindowsformat
Cookie
CoordinatedUniversalTime[SeeUTC]
Copy
directory,shellscript
fileusingcp2nd
floppydisketteusingdd
Copyleft
Core
dump
memory
corefile2nd
Correct
typingmistakes,howto
vimtypingmistakes
correctvariable
countshellscript
cputility2nd3rd4th
cpversusln
cpdirshellscript
cpioutility2nd3rd
cppfilenameextension
CPU
Cracker
Crash
creat()systemcall
Create
directoryusingmkdir
fileusingvim
Creationdate,file,displayusingls
crondirectory
cronutility2nd
cron,Vixie[cron]
cron.allowfile
cron.dailydirectory
cron.denyfile
cron.hourlydirectory
cron.monthlydirectory
cron.weeklydirectory
crontabfile2nd
crontabutility
Cryptography
csh2nd
csh.cshrcfile
csh.loginfile
csh.logoutfile2nd
CSRG
CSS2nd
CUPS
Current
Currentdirectory[SeeWorkingdirectory]
Cursor
cututility2nd3rd
cvscommand
add
checkout2nd
commit
export
import
log
release
remove
rtag
update
cvsutility2nd
CVSROOTvariable
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
Daemon
atd
defined
ftpd
lpd
syslogd
Data
sink
structure
Database
dbm
gdbm
group
LinuxSoftwareMap
locale
locate
manpageheader
ndbm
NIS
passwd2nd3rd
services
slocate
SQL
systemservices
terminfo
whatis
Datagram,network
Datalesssystem
dateutility2nd3rd4th
Date,display[Date]
dbmdatabase
ddutility
dddutility2nd
DDoSattack
Debug
Debugger
ddd
graphicalsymbolic
option
shellscript
symbolic
ups
xxgdb
declarebuiltin2nd
Decrementoperator2nd
Default
defaultshellkeyword
Delete
directoryusingrmdir
fileusingrm
key
line
linkusingrm
word
Deletekey
Delimiter,regularexpression
Delta,SCCS
DenialofService[SeeDOSandDDoSattack]
Dependencyline(make)
Dereference
Descriptor,file
Descriptor,file,duplicate
Design,top-down
Desktop
defined
manager
Detachedprocess[SeeBackground,process]
devdirectory
developer.apple.com/darwin
Device
block
character
defined
driver2nd
file2nd
filename
independence
independentinputandoutput
null
number
major
minor
physical
dfutility
DHCP
dickey.his.com/vile/vile.html
Die,process
diffutility2nd
diff,context[diff]
diff3utility
DIR_COLORSfile
dircolorsutility
Directory2nd3rd
/(root)2nd
/bin
/boot
/dev2nd3rd
/etc
cron.daily
cron.hourly
cron.monthly
cron.weekly
opt
X11
/home
/lib
gcc,and2nd
modules
/mnt
/opt
/proc
/root
/sbin
/tmp2nd3rd
/usr
bin
bin:X11
doc
games
include
include:X11
info
lib
lib:gcc,and2nd
lib:linking,and
lib:shared
lib:terminfo
lib:X11
man
share
src
X11R62nd
/var
log2nd
spool:at
spool:at:spool
spool:cron
spool:problemsolving
accesspermission
at
bin2nd
changeusingcd
child2nd
copy,shellscript
createusingmkdir
cron
cron.daily
cron.hourly
cron.monthly
cron.weekly
current[SeeDirectory,Directory;working]
defined2nd3rd4th
deleteusingrmdir
dev2nd
doc
empty
eraseusingrmdir
file2nd
games
hierarchy
home2nd3rd4th
versusworking
include2nd
info
lib2nd3rd4th5th6th
link
listusingls
listing
local
log2nd
lost+found2nd3rd
makeusingmkdir
man
modules
moveusingmv
opt2nd
parent2nd
pathname2nd
proc
removeusingrmdir
renameusingmv
root2nd3rd4th
sbin2nd
service
share
spool
spool,problemsolving
src
stackmanipulation2nd3rd
standard
terminfo
tmp
working
changeusingcd
defined
home,versus
relativepathnames
significanceof
with
X112nd3rd4th
X11R62nd
~(home)[SeeHomedirectory]
dirsbuiltin2nd3rd4th
dirstackvariable
Disk
freespace
partition
usage
Disklessdefined
Display
dateusingdate
endofafileusingtail
fileinreverseorderusingtac
fileusingcat
graphical
invisiblefilename
machinename
orderedfileusingsort
sortedfileusingsort
systemloadusingw2nd
textusingecho
topofafileusinghead
uptimeusingw
userlist
usingfinger
usingw
usingwho
Distributedcomputing
Distribution,Linux
DMZ
DNS
docontrolstructure2nd3rd4th
docdirectory
DocumentObjectModel[SeeDOM]
Documentation
finding
system2nd
Dollarsign
regularexpression,in
variables,usewith2nd
DOM
Domainname
donecontrolstructure2nd3rd4th
Door
DOS
convertfiles
filename
filenameextension
Mtools
DoSattack
dos2unixutility
Doubleversussinglequotationmarks
DPMS
Drag
Driver,device
Druid
DSA
DSL
duutility2nd3rd
duniquevariable
Duplex,fullandhalf
Duplicatelines,gettingridofusinguniq
Dynamiclibrary[SeeShared,library]
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
e2fsckutility
EBCDIC
echobuiltin2nd3rd4th5th6th7th8th9th10th11th12th13th
echoutility
echovariable
ededitor2nd3rd
Editor
commandline
defined
ed2nd3rd
emacs
ex2nd3rd
ReadlineLibrary
vim
EDITORvariable2nd
Edwards,Dan
EEPROM
EffectiveuserID
egreputility2nd3rd
Electronicmail[SeeMail]
Electronicmessage,sendingusingwrite
Element
elifcontrolstructure2nd
elsecontrolstructure
elseshellkeyword
elvisutility
elvis.the-little-red-haired-girl.org
emacs
*compilation*buffer
*TabStops*buffer
acronyms
ALTkey
aspell
AutoFillMode
backgroundshellcommands
backup
buffer
bufferwidereplacement
bufferwidesearch
current
savingandretrieving
state
workingwith
CMode
caseconversion
comments
CONTROLkey
currentbuffer
cursor
customizing
cuttext
delete
Diredmode
EchoArea
editcommands
editingatthecursor
erasetext
escapecharacter
ESCAPEkey2nd
expressions,workingwith
FIFO
files
fill
foregroundshellcommands
function,defining
globalcommands
GUDmode
help
human-languagemodes
incrementalsearch
indention
inserttext
interactivereplacement
key
notation
remap
sequencesandcommands
use
keymaps
keystrokenotation
kill
KillRing2nd3rd
killtext
language-sensitiveediting
Lispsystem,internal
mail
majormodes2nd
Mark
MarkRing
METAkey2nd3rd
Minibuffer
ModeLine2nd
moveby
characters
lines
paragraphs
sentences
windowposition
words
movecursor
multilevelbackups
nonincrementalsearch
numericargument
onlinehelp
paragraphs,workingwith
pastetext
Point2nd
Region
regularexpressionsearch
remapkeys
repetitioncount
replacement2nd
resources
retrievingbuffer
Rmailmode
save
buffer
file
scrollingthroughbuffer
search
bufferwide
incremental
nonincremental
regularexpression
typesof
sentences,workingwith
shellcommands2nd
Shellmode2nd
SHIFTkey
smartcompletion
specialcharacters
special-purposemodes
spellchecking
start
stop
subshell
TABkey
TextMode
textualunits
Trampmode
unconditionalreplacement
undochanges
VCmode
visimulation
vi,versus[emacs
vi]
VIPmode
visitingafile2nd
window
adjust
createbysplitting
delete
manipulate
otherwindow
workingwith
words,workingwith
XWindowSystemand
yanktext
Email[SeeMail]
Emoticon
Emptyregularexpression
Emulation,terminal
Emulator,operatingsystem
Encryption,RSA
Endoffile[SeeEOF]
endswshellkeyword
Entertextusingvim
ENVvariable
Environment
calling
defined
exec
export2nd3rd
setenv
unsetenv
variable
EOF2nd3rd
Epoch,defined
EPROM
Erasekey2nd3rd4th5th6th7th8th9th10th
Erasewordkey
Error
correcting
message
cannotexecute
conditional
nameofcallingscript
notfound
redirectingtostandarderror
standarderror[SeeStandard,error]
usage2nd3rd4th5th
shellscript
standard[Seebash;Standarderror]
usagemessage2nd3rd4th5th
esaccontrolstructure
Escapeacharacter2nd
Escapeanendofline
escapecharacter2nd3rd
Ethernetnetwork
evalbuiltin2nd3rd
Event
defined
history
modifyingprevious
number2nd3rd
reexecuting
text
wordswithin
Evolutionutility
exeditor2nd
Exabyte
Exclamationpoint
execbuiltin2nd3rd4th5th6th7th
exec()systemcall2nd3rd
Execute
access2nd3rd
command2nd
permission
shellscript
Exit
shell,froma
status2nd
exitbuiltin2nd3rd4th5th6th7th
exit()systemcall
exmhutility
Expansion
arithmetic2nd
brace2nd
commandline2nd
filename
macro
nullvariable
orderof2nd
parameter
pathname2nd3rd4th
quotationmarks,double
tilde2nd
unsetvariable
variable
Exploit
exportbuiltin2nd3rd4th5th6th
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
ffilenameextension
fabrice.bellard.free.fr/qemu
Fahlman,Scott
Failsafesession
Familytree
fcbuiltin
FCEDITvariable
FDDInetwork
fdformatutility
Features,bash[Seebash,bash;features]
fgbuiltin2nd3rd4th
fgreputility2nd
FHS2nd3rd
ficontrolstructure2nd3rd
FiberDistributedDataInterface[SeeFDDInetwork]
FIFOspecialfile2nd3rd
fignorevariable
File
.aspell.conf
.bash_history
.bash_login
.bash_logout
.bash_profile2nd
.bashrc2nd
.cshrc2nd
.dir_colorsfile
.emacs2nd3rd4th
.history2nd
.inputrc
.login2nd3rd
.logout2nd
.netrc
.nofinger
.pgpkey
.plan2nd
.profile2nd
.project2nd
.rhosts2nd3rd4th
.tcshrc2nd
.toprc
.torrent
.vimrc2nd
/dev
null2nd3rd
random
tty
urandom
/etc
aspell.conf
at.allow
at.deny
cron.allow
cron.deny
crontab
csh.cshrc
csh.login
csh.logout2nd
DIR_COLORS
hosts.equiv2nd3rd
issue
man.config
motd
passwd2nd3rd4th5th6th7th
printcap
profile
termcap
yum.conf
/usr
include
local
pub:ascii
sbin
share:magic
/var
log:lastlog
log:messages2nd
log:secure
log:wtmp
a.out2nd
accesspermission2nd
ambiguousreference
apt.conf
archiveusingtar
ascii
aspell.conf
at.allow
at.deny
bashrc
binary,fixingbroken
blockspecial2nd
characterspecial2nd
close(bash)
copyusingcp
core2nd
createusingcat
creationdate,displayusingls
cron.allow
cron.deny
crontab2nd
csh.cshrc
csh.login
csh.logout2nd
defined2nd
descriptor2nd
duplicate
device2nd
DIR_COLORS
directory2nd3rd
display
beginningofusinghead
endofusingtail
usingcat
empty,creatingan
executepermission
FIFOspecial2nd
GNUmakefile
group,displayusingls
header2nd
hierarchicalstructure
hosts.equiv2nd3rd
identifyingusingfile
include
issue
lastlog
link
list
log
magic
Makefile
makefile
Makefile
makefile2nd
Makefile
makefile
Makefile
man.config
messages2nd
motd2nd
moveusingmv
name[SeeFilename]
namedpipe2nd
null2nd3rd
object2nd
open,bash
orderusingsort
ordinary2nd3rd
owner
displayusingls
packarchiveusingtar
passwd2nd3rd4th5th6th7th
pathname2nd
permission2nd
pointerto
printcap
profile
random
reference,ambiguous2nd
removeusingrm
renameusingmv
rotate
secure
size,displayusingls
sortusingsort
sparse2nd
special2nd3rd
standard
startup2nd3rd4th
stdio.hCheader
structure
swap
tar
temporary,nameof2nd
termcap
terminal
text
torrent
tty
typeof,discoverusingls
typescript
urandom
window
wtmp
yum.conf
fileutility2nd
filecvariable
Filename2nd
/
absolute
ambiguousreference[SeeFile,File;ambiguousreference]
case
case-sensitive
changeusingmv
charactersin
choiceof
completion
conventions
defined2nd
device
DOS
extension
a2nd3rd
bz22nd3rd
c2nd3rd4th
C
c
C
c++
cc2nd
cpp
cxx2nd
defined
DOS
emacsand
f
gif
gz2nd3rd
h2nd
html
i2nd
ii2nd
jpeg2nd
jpg2nd
l
listof2nd
lsand
o2nd3rd4th5th
pdf
ps
removea
s2nd3rd
S
s
sh
sharedobject
so2nd
tar.bz2
tar.gz
tar.Z2nd
tgz
tiff
torrent
txt2nd
tz
y
Z2nd
generation2nd3rd
invisible2nd3rd
length2nd3rd
period,leading
quoting
reference,ambiguous[SeeFile,File;ambiguousreference]
rootdirectory
simple2nd3rd4th
substitution
temporaryfile2nd
typeface
unique2nd
Windows
Filesystem
clean
defined2nd
ext22nd3rd
ext32nd3rd
filenamelength
freelist
HierarchyStandard,Linux2nd
journaling2nd
organize
root
Standard,Linux2nd
structure2nd
use
filetestbuiltin2nd
Filling
FILOstack
Filter2nd3rd
Find
commandnameusingapropos
stringusinggrep
findutility
inode2nd
find_uidshellscript
findershellscript
fingerutility2nd3rd4th
Firewall
Firstinlastoutstack
flexutility
Floppydiskette,copyusingdd
fmtutility
Focus,desktop
Folder[SeeDirectory]
Font,anti-aliasing2nd
Footer
forcontrolstructure2nd3rd
for...incontrolstructure2nd3rd
foreachcontrolstructure
Foreground
backgroundversus
defined
process
Fork
child
defined
process
forksystemcall
fork()systemcall2nd3rd4th5th
FQDN
Frame,network
Free
list,filesystem
space
space,disk
StandardsGroup
fsckutility
FSG
FSSTND2nd
FTP
activeconnection
anonymous
automaticlogin
passiveconnection2nd
PASVconnection
PORTconnection
pubdirectory
tutorial
ftp.gnu.org/pub/gnu/make/make-3.80.tar.gz
ftp.ibiblio.org/pub/Linux
ftpddaemon
Full
duplex2nd
regularexpressions
egrep
pipe
plussign
questionmark
summary
Fullyqualifieddomainname[SeeFQDN]
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
g++utility
gamesdirectory
Gateway
gawk2nd
format
operator2nd
printffunction
shellscript,ina
sprintffunction
gcc
history
homepage
using
warningoptions
gcc.gnu.org
gdbutility2nd3rd
gdbmdatabase
GECOS
Generatefilenames
Genericoperatingsystem
getcharCmacro
getoptsbuiltin2nd
gettyutility
gidvariable
giffilenameextension
Giga-
globbuiltin
Globalvariable2nd
Globbing2nd3rd4th
Glyph
GMT[SeeUTC[GMT]]
GNU
CompilerCollection
emacs
gcc
compiler2nd
homepage
gdbutility
GeneralPublicLicense
manuals
usagemessage
GNUmakefilefile
gotocontrolstructure
GPL[SeeGNU,GNU;GeneralPublicLicense]
gprofutility
Graphicaldisplay
Graveaccent[SeeBacktick]
GreenwichMeanTime[SeeUTC]
greputility2nd3rd4th5th6th7th8th9th
Group
access
changing
commands2nd
ID2nd3rd4th
nameof,displayusingls
users
windows
groupdatabase
groups.google.com2nd
GUI
combobox
defined
radiobutton
scrollbar
spinner
textbox
thumb
wysiwyg
XWindowSystem
gunziputility2nd
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
hfilenameextension2nd
Hacker
Half-duplex2nd
Hardlink
createusingln
defined2nd
numberofusingls
removeusingrm
Hardcodedfilenameinshellscripts
Hash
defined
one-way
table
hashstatbuiltin
headutility
Header
document
file2nd
Help
aproposutility
documentation
emacs
errormessages
getting
GNUmanuals
HOWTOs
infopages
Internet,fromthe
LinuxDocumentationProject2nd
manpages
Heredocument2nd
heredocument
Heredocument
Hesiod
Heterogeneous
Hexadecimalnumber
Hiddenfile[SeeInvisiblefilename]
Hierarchicalfilestructure
Hierarchy
histfilevariable2nd3rd
HISTFILESIZEvariable
histlitvariable2nd
History
CShellmechanism,classic
defined
event
editing
number
previous:!$lastwordof
previous:modifying
reexecuting
text
wordswithin
mechanism2nd
vi,of
viewing
worddesignator
historybuiltin2nd3rd4th
historyvariable2nd3rd
HISTSIZEvariable
Homedirectory2nd
.aspell.conf
.bash_historyfile
.bash_loginfile
.bash_logoutfile
.bash_profilefile2nd
.bashrcfile2nd
.cshrcfile
.dir_colorsfile
.historyfile2nd
.inputrcfile
.loginfile2nd3rd
.logoutfile2nd
.netrc
.nofingerfile
.pgpkeyfile
.planfile
.profilefile2nd
.projectfile
.rhosts
.tcshrcfile2nd
.toprcfile
.vimrcfile2nd
defined2nd
invisiblefile
startupfile
workingdirectory,versus
~,shorthandfor2nd
HOMEvariable2nd
homevariable
HOMEvariable2nd
hostnameutility
hosts.equivfile2nd3rd
Hover
HOWTOdocuments,finding
HTML
htmlfilenameextension
HTTP
Hub
Humor2nd3rd4th
hunk(diff)
Hypertext
defined
MarkupLanguage[SeeHTML]
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
ifilenameextension2nd
I/Odevice[SeeDevice]
IANA
ICMPpacket
Icon
Iconify
ifcontrolstructure2nd3rd4th5th
ifthecharacterisa-,itis
if...thencontrolstructure
if...then...elifcontrolstructure2nd
if...then...elsecontrolstructure2nd
IFSvariable
Ignoredwindow
ignoreeofvariable2nd
iifilenameextension2nd
Implieddependency,make
importcommand,cvs
incontrolstructure
inregularexpressions2nd
inreplacementstrings
Includedirective
includedirectory2nd
Includefile
Incorrectlogin
Incrementoperator
indentshellscript
Indentation[SeeIndention]
Indention
Indirectpointer
Infiniterecursion,alias
infodirectory
infoutility
manual
using
initutility
Inode
defined
displayusingls
explained
filesystem
linksshellscript
Input
defined
Mode,vim
standard[SeeStandard,input]
Input/outputdevice[SeeDevice]
input_linevariable
INPUTRCvariable
Installation,computer
IntegratedServicesDigitalNetwork[SeeISDN]
Interactive
Interface
commandline
defined
user2nd
InternalFieldSeparator[SeeIFSvariable]
InternationalOrganizationforStandardization[SeeISO]
Internet
AssignedNumbersAuthority[SeeIANA]
defined
mirrorsite
netiquette
PrintingProtocol[SeeIPPprotocol]
Protocol[SeeIPandTCP]
serviceprovider[SeeISP]
URI
URL
internet(smalli)
Interprocesscommunication2nd
Interrupthandling
Interruptkey2nd3rd4th5th
Intranet
Invisiblefilename
defined2nd
display
notdisplayedwith?
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
Job
control2nd3rd
bgbuiltin
defined
fgbuiltin2nd
howtouse
jobsbuiltin2nd
notifybuiltin
stopbuiltin
defined
number2nd
stopforeground
jobsbuiltin2nd3rd4th5th6th
Journalingfilesystem2nd
Joy,Bill
JPEG
jpegfilenameextension2nd
jpgfilenameextension2nd
Justify
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
K&R2nd
kdbgutility
KDE
desktop
kdbgutility
Kerberos
Kernel
defined
devicedriver
module[SeealsoLoadablemodule]
programminginterface
responsibilities2nd
systemcalls
kernelspace
Kernighan&Ritchie[SeeK&R]
Key
BACKSPACE
binding
binding,emacs
CONTROL
CONTROL-C2nd
CONTROL-D2nd3rd4th
CONTROL-H2nd3rd4th5th6th
CONTROL-L2nd3rd
CONTROL-M
CONTROL-Q
CONTROL-R
CONTROL-U2nd3rd4th
CONTROL-V2nd
CONTROL-W2nd3rd4th5th
CONTROL-X2nd
CONTROL-Z2nd
CONTROL_U2nd
Delete
erase2nd3rd4th5th6th7th8th9th10th
interrupt2nd3rd4th
kill2nd3rd4th
linekill2nd3rd4th
META2nd
NEWLINE2nd
notation
RETURN2nd3rd4th
SPACEbar
suspend2nd3rd4th5th6th7th8th9th
TAB
typeface
worderase2nd
Keyboard
defined
Keystrokenotation
Keyword
searchingforusingapropos
variable2nd
killbuiltin2nd3rd4th5th6th7th8th
Killkey2nd3rd4th
Killlinekey2nd3rd4th
killutility
kill()systemcall
kilo-
Knowledgebase,RedHat
KornShell[Seeksh]
Korn,David[Korn]2nd
ksh
defined
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
lfilenameextension
LAN
defined
Language
-sensitiveeditor,emacs[Language
sensitive]
procedural
Largenumber
LASONSEMICOLONcommandseparator
LastLinemode,vim
lastlogfile
ldutility
ld-linuxlibrary
ld-linux.soutility
LD_LIBRARY_PATHvariable2nd
LD_RUN_PATHvariable
LDAP
lddutility2nd
Leaf
Leastprivilege
Lengthoffilename
lessutility2nd3rd4th5th
LESSvariable
letbuiltin2nd
libdirectory2nd3rd4th5th6th
libattrlibrary
libclibrary
libc.solibrary
libm.alibrary
libm.solibrary
Library
archived
dynamic[SeeShared,library]
ld-linux
libacl
libattr
libc
libc.so
libm.so
shared2nd
staticallylinked
LightweightDirectoryAccessProtocol[SeeLDAP]
limitbuiltin
Linekillkey2nd3rd4th5th6th7th8th
LinePrinterDaemon[Seelpddaemon]
LINESvariable
Link
createusingln
defined2nd
deleteusingrm
hard2nd3rd4th
hardversussymbolic
numberof,displayusingls
point-to-point
removeusingrm
soft[SeeLink,symbolic]
symbolic
bashand
createusingln2nd
defined
displayusingfind
followusingfind
markusingls
versushard2nd
symlink[SeeLink,symbolic]
linksshellscript
lintutility
Linux
distribution
documentation
DocumentationProject2nd
FilesystemHierarchyStandard2nd
FilesystemStandard2nd
manual
newsgroup
PAM[SeePAM]
PluggableAuthenticationModules[SeePAM]
StandardBase
LinuxSoftwareMapdatabase
linuxterminalname
linux.duke.edu/projects/yum
Lispprogramminglanguage
Listoperator
Listserver
listjobsvariable
listlinksvariable
Listserv
llibacllibrary
lnutility2nd
versuscp
Loadaverage2nd
Load,system,displayusingw[Load]
Loadablemodule
Local
areanetwork[SeeLAN]
variable2nd3rd4th
localfile
Locale
localebuiltin
localedatabase
locatedatabase
locateutility
lockutility
lockttyshellscript2nd
Log
files
out
logbuiltin2nd
logcommand(cvs)
logdirectory2nd
Logical
expression
operator[SeeBooleanoperator]
Login
defined
incorrect
name
problems
procedure
prompt
remote2nd
root
shell2nd3rd4th
loginbuiltin
loginutility
loginshvariable
Logout
logoutbuiltin2nd3rd
lost+founddirectory2nd3rd
lpddaemon
lpqutility2nd
LPRlineprintersystem
lprutility2nd3rd4th
lprmutility2nd
lsutility2nd3rd4th5th6th7th8th
ls-Fbuiltin2nd
LSB
lseek()systemcall
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
MACaddress
Machine
collatingsequence2nd
independence
name,display
Macro
Cpreprocessor2nd
defined
expansion
make
magicfile
Magicnumber2nd
Mail
attachment
listserver
mailbox
MDA
MTA
MUA
networkaddresses
mailutility
MAILvariable
mailvariable
Mailbox
MAILCHECKvariable
MAILPATHvariable
MAILTOvariable
mainfunction
Mainmemory
Mainframecomputer
Majordevicenumber2nd
makeutility2nd3rd4th5th6th7th
Makefilefile
makefilefile2nd3rd
Makefilefile
makefilefile
Makefilefile
makefilefile
makefile,discussion[makefile]
makewhatisutility
MAN
mandirectory
manpageheaderdatabase
manutility2nd3rd4th
man.configfile
MANPATHvariable
Manuals
GNU2nd
man
reference,finding
system,about
Masquerading
MassachusettsInstituteofTechnology[SeeMIT]
McCarthy,JohnM
mcdutility
mcopyutility
MD5encryption
MDA
mdelutility
mdirutility
Mega-
Memory,main
Menu
defined
shellscript
Merge
mesgutility
Message
denyusingmesg
Digest5[SeeMD5encryption]
oftheday[Seemotdfile]
sendusingwrite
usage2nd3rd4th5th6th7th
messagesfile2nd
METAkey2nd
Metabit
Metacharacter2nd
Metadata
mformatutility
Microprocessor
MIME
defined
type,displayedbyfile
mingettyutility
mini-HOWTOdocuments,finding
Minicomputer
Minimizewindow
MINIX
Minordevicenumber2nd
Mirrorsite
Mistake,correcttyping
MIT
lispculture
mkdirutility2nd3rd4th5th
mke2fsutility
mkfsutility
mkfs.ext2utility
mkfs.ext3utility
mklost+foundutility
Modelesseditor
Modem
cable
defined
Module[SeeLoadablemodule]
modulesdirectory
moreutility2nd3rd
motdfile2nd
Mount
automatic
defined
point
Mouse
pointer
pointer,hover
windowmanager
Mouseover
Move
directoryusingmkdir
fileusingmv
MSWindows[SeeWindows]
MTA
Mtoolsutility
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
Name
command
login
variable2nd
Namedpipe2nd3rd
NAT
NBT
ndbmdatabase
NetBIOS
Netboot
Netiquette
Netmask
Network
address
defined
mail
space,private
AddressTranslation[SeeNAT]
boot
broadcast
address
defined
datagram
Ethernet
extranet
FDDI
frame
gateway
hub2nd
ICMPpacket
InformationService[SeeNIS]
multicast
netmask
number[SeeNetwork,address]
packet
packetfiltering
packetsniffer
portforwarding
privateaddressspace
privilegedport
router
segment
sniff
subnet
address
defined
mask
number
switch
TimeProtocol[SeeNTP]
tokenring
topology,shared
tunneling2nd
UDP
unicast
VPN
Wi-Fi
widearea[SeeWAN]
wirelessaccesspoint
NEWLINEkey2nd
Newsgroup
comp.os.linux.answers
comp.os.linux.misc
listof
NFS
NIC
nicebuiltin2nd
niceutility
nice()systemcall
NIS
database
defined
domainname
NNTP
Nonewsisgoodnews
noarch
nobeepvariable
noclobbervariable2nd3rd
Node
noglobvariable
nohupbuiltin
nohuputility2nd
nonomatchvariable
Nonprintingcharacter2nd
Nonvolatilestorage
Normalmode,vim[Seevim,vim;Commandmode]
NOTBooleanoperator
notifybuiltin
notifyvariable
NTP
Null
builtin(
)
builtin(\
)
device
string2nd
nullfile2nd3rd
Number
block
device
major
minor
giga-
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
ofilenameextension2nd3rd4th5th
Objectfile2nd
Octalnumber
odutility
OLDPWDvariable
onintrbuiltin2nd
Onlinedocumentation
Openfile
open()systemcall
OpenSSH
authentication
defined
initialconnectionto
public-keyencryption
Operatingsystem
defined
generic
proprietary
Operator
bash
inexpressions
redirection
bitwise
&2nd
^
|
Boolean
!2nd3rd4th
&
&&2nd3rd4th5th6th7th8th
-a2nd3rd
-o2nd
-or
NOT
SPACE2nd
||
||
decrement2nd
increment
logical[SeeOperator,Operator;Boolean]
postdecrement2nd
postincrement2nd
predecrement
preincrement
relational
short-circuiting
tableof
optdirectory2nd
OPTARGvariable
Optimizer,Ccompiler2nd
OPTINDvariable
Option
bash[Seebash,bash;features]
combining
defined2nd
ORoperator
Orderfileusingsort
Orderofexpansion,commandline
Ordinaryfile2nd
Organizeafilesystem
Otheraccess
outshellscript
Output
append[SeeAppend,Terminal;standardoutput]
defined
redirect
standard[SeeStandard,output]
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
P2P
Packarchivefileusingtar
Packet
defined
filtering
sniffer
Pagebreak
Pager2nd3rd
PAGERvariable2nd
Paging
PAM
Parameter
expansion
positional2nd
shell
special
substitution
vim
Parent
directory2nd
process2nd3rd4th
Parentheses
groupingcommands
shellfunctions
Parse2nd
Partition,disk
PASC
PassiveFTP
Passphrase
passwddatabase2nd3rd
passwdfile2nd3rd4th5th6th7th
passwdutility
passwd_checkshellscript
Password
change
criteria
defined
security
pasteutility
PASVFTP[SeePassiveFTP]
PATHvariable
pathvariable
PATHvariable
builtinand
findexecutablesusingwhich
inherited
tcsh
usage
Path,search[Path]
Pathname
absolute2nd3rd
completion2nd3rd
defined2nd
element
expansion2nd3rd4th
lastelementof
relative2nd3rd4th
using
~(tilde)ina
pdffilenameextension
Peer,BitTorrent
Performance,system
Period,leadinginafilename
Peripheraldevice[SeeDevice]
Permission
access
changeusingchmod
controlof
directory
displayusingls
execute
read
typesof
execute
fileaccess
read
setgid
setuid
Persistent
Philosophy,UNIX2nd
Physicaldevice
PID
$!variable,and
$$variable2nd
backgroundprocessand2nd
defined
determiningusingps
fg
kill,usingwith2nd
number1
temporaryfile,useinnameof
Pipe
commandseparator
defined2nd
endofline,at
filter2nd
introduction
named2nd
noclobberand
standarderror,and
symbol
syntaxexception
Pipeline[SeePipe]
Pixel
Plaintext
planfile[See.planfile]
Plussign
Point-to-pointlink
Pointertoafile
popdbuiltin2nd3rd
Port
defined
forwarding
Portability2nd
Portmapper
Position-independentcode
Positionalparameter2nd3rd4th
POSIXstandards2nd
Postdecrementoperator2nd
Postincrementoperator2nd
Postscript,braceexpansion
PPID[SeeParent,process]
prutility
Preamble,braceexpansion
Predecrementoperator
Preincrementoperator
Preprocessordirective
#define2nd3rd
#include
defined
macro2nd
symbolicconstant2nd
Prerequisites
BitTorrent
make
Print,IPPprotocol
Printablecharacter
printcapfile
printenvbuiltin
Printer
controlcharacters
lprand
pagebreak2nd
skiptotopofpage
topofform
using
PRINTERvariable
Printing
afile[SeePrinter,infoutility;using]
CUPS
Privateaddressspace
Privilege,least
Privilegedport
Problems,login
procfilesystem
Procedurallanguage
Procedure
Process
background2nd3rd
child2nd3rd4th
defined2nd3rd
die2nd
foreground
fork2nd
ID[SeePID]
parent2nd3rd
parent-childrelationship
PID,displayusingps
sleep2nd
spawn[SeeFork]
spontaneous
start
structure
substitution
wakeup2nd3rd
Processingacommandline
procmailutility
profilefile
Program
badtabs.c
defined
keepingcurrent
stop
structures
tabs.c
terminate
Programmer
applications
systems
Programmingtools
PROM
Prompt
$
%
bash2nd
defined
jobcontroland
login
PS2
PS3
representation
secondary
shell2nd
tcsh2nd
variable
promptvariable
prompt2variable
prompt3variable
Proprietaryoperatingsystem
Protectedmemory
Protocol
connection-oriented
connectionless
defined
IPP
TELNET
Proxy
defined
gateway
server
psfilenameextension
psutility2nd3rd4th5th
PS1variable2nd
PS2variable2nd
PS3variable
PS4variable
pstreeutility
pubdirectory
PublicLicense,GNU[SeeGNU,GNU;GeneralPublicLicense]
Public-keyencryption,OpenSSH
pushdbuiltin2nd3rd
pushdsilentvariable
pushdtohomevariable
putcharCmacro
pwckutility
pwdbuiltin2nd3rd4th5th
pwdutility
PWDvariable
Python
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
Questionmark
Quicksubstitution
Quotationmark
double2nd3rd4th
removal
single2nd3rd
singleversusdouble2nd
usagemessage
Quoting
characters2nd
defined
shellvariables
specialcharacters
variables
whitespace
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
Radiobutton
RAID
RAM
defined
disk
Randomaccessmemory[SeeRAM]
Randombytes,generating
randomfile
Randomnumbergenerator2nd
RANDOMvariable
RAS2nd
rcputility
RDF
Read
access2nd
userinput
readbuiltin2nd3rd4th5th6th
read()systemcall2nd
ReadlineLibrary2nd
completion
readonlybuiltin2nd3rd4th
Readonlymemory[SeeROM]
Readonlyvariable
Recursion
defined
example
infinite,alias2nd
Recursiveplunge[SeeRecursion,infinite,alias]
RedHat
Knowledgebase
Redirect
operators,bash
output
standard
error2nd3rd
input2nd
output2nd3rd4th5th6th7th
outputandappend
outputanderror
outputofbackgroundjob
outputusingtee
redirectstandardinput
redirectstandardoutput
Redirection2nd3rd
Reentrantcode2nd
Reexecutingcommands2nd
Refreshscreen
Regularcharacter
Regularexpression
...bracketexpression
ampersand2nd
anchor
asterisk
bracket
bracketing
caret
characterclass
defined
delimiter
dollarsign
empty
extended2nd
full
gawk
grep
listoperator
longestmatch
period
quoteddigit
quotingparentheses
quotingspecialcharacters
replacementstring
rulesofuse
simplestring
specialcharacter2nd3rd
specialcharacter,quoting
squarebracket
summary
vim
rehashbuiltin
Relationaloperator
Relativepathname2nd3rd4th
releasecommand(cvs)
Release,CVS[Release]
Religiousstatue,miniature[SeeIcon]
Remainderoperator
Remote
AccessServer[SeeRAS]
login
procedurecall[SeeRPC]
Remove
directoryusingrmdir
fileusingrm
linkusingrm
variable
removecommand
Rename
directoryusingmv
fileusingmv2nd
renameshellscript
repeatbuiltin
Repeatingacommand
Replacementstring2nd3rd4th5th
REPLYvariable2nd
RequestforComments[SeeRFC]
Resolver
ResourceDescriptionFramework[SeeRDF]
Restore
Returncode[SeeExit,status]
RETURNkey2nd3rd4th
Reversesinglequotationmark[SeeBacktick]
RFC2nd
RFS
Ritchie,Dennis
rloginutility
rmutility2nd3rd4th5th
rmdirutility2nd
rmstarvariable
Roam
ROM
Root
directory2nd3rd4th
filesystem
root(user)
rootlogin
ROT13
Rotatefile
Router
RPC
rpmfind.net
RSAencryption
rshutility
rtagcommand(cvs)
Run
backgroundcommand
defined
shellscript
run-partsutility
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
sfilenameextension2nd3rd
Sfilenameextension
sfilenameextension
safeditshellscript
Samba
defined
NBT
NetBIOS
share
SMB
Windowsshare
WINS
savehistvariable2nd3rd
sbindirectory
schedbuiltin
Schedulingjobs
Schema
scputility
Screen,refresh
scriptutility
Script,shell[SeeShellscript]
Scroll
Scrollbar
sdiffutility
Search
keywordusingapropos
path
stringusinggrep
stringusingvi2nd
Secondaryprompt
securefile
Security
accesspermission2nd3rd
ACL2nd
authentication
backdoor2nd
checksum
cipher
ciphertext
cleartext
cookie
cracker
cryptography
cypher[SeeSecurity,cipher]
DDoSattack
DoSattack
Kerberos
Linuxfeatures
lockttyscript
password
PATHvariable
RSA
setgid
setuid2nd
shredutility
Trojanhorse
virus
wipingafile
worm2nd
sedutility2nd3rd
Seed,BitTorrent
Segment,network
selectcontrolstructure
sendmail,masquerade
Separatingcommands
Server
defined
maillist2nd
MessageBlockProtocol[SeeSamba]
Service,directory
servicesdatabase
Session
defined
failsafe
setbuiltin2nd3rd4th5th6th7th8th9th10th11th
SetgroupID[SeeSetgid]
setenvbuiltin2nd3rd
Setgid
defined
displayusingls
permission
root,filesbelongingtothegroup
Setuid
defined
lsdisplayof
root,filesownedby
Sexillion
shfilenameextension
shShell2nd3rd
sharshellscript
Share
sharedirectory
Shared
library
creating
gcc
using
networktopology
object,filenameextension
Shell
archive
arithmetic(bash)
callingprogram,nameof
command
grouping2nd
separation
substitution2nd
comment
comparingstrings
controlstructure
break
case2nd
continue
do2nd3rd4th
done2nd3rd4th
elif2nd
else
esac
fi2nd
for2nd3rd
for...in2nd
goto
if2nd3rd4th
if...then
if...then...elif2nd
if...then...else2nd
in
switch
then2nd3rd
until2nd
while2nd3rd4th5th
defined
environmentvariable2nd
exitfrom
features
function2nd
identifying
jobcontrol
keyword
break
breaksw2nd
case
continue
default
else
endsw
switch
then
variable
while
login2nd3rd
nameofthecallingprogram
options[SeeShell,bash;features]
parameter
positional
special
prompt2nd3rd4th
readonlyvariable
sh2nd3rd
sleep
strings,comparing
user-createdvariable
variable[SeeShellvariable]
Shellscript2nd3rd
#comment
#!shelltouse
/dev/ttyforaterminal
addbanner
bash
birthday
bundle
chkargs2nd
cleanup
command_menu2nd
comment
count
cpdir
create
debug
defined
doublequotationmarks2nd
errormessage2nd
executing2nd
find_uid
finder
Heredocument
indent
infiniteloop
invocation
is_regfile
links
locktty2nd
makepath
menu
out
passwd_check
PATHusage
quiz
quotein2nd3rd4th
readuserinput
recursion
rename
running
safedit
shar
specifyingashell
spell_check2nd
temporaryfilename2nd
usagemessage2nd3rd4th5th
userinput
whos2nd3rd
whoson
word_count
word_usage
shellvariable
SHELLvariable
Shellvariable
$!
$#2nd3rd4th
$#argv
$$2nd3rd4th5th
$*2nd3rd
$0
$<
$?2nd
$@2nd3rd
argv
ASPELL_CONF
autocorrect
autolist2nd
autologout
BASH_ENV
CDPATH
cdpath2nd
CDPATH
cdpath
COLUMNS
correct
CVSROOT
cwd2nd
dirstack
dunique
echo
EDITOR2nd
ENV
FCEDIT
fignore
filec
gid
histfile2nd3rd
HISTFILESIZE
histlit2nd
history2nd3rd
HISTSIZE
HOME2nd
home
HOME2nd
IFS
ignoreeof2nd
input_line
INPUTRC
keyword
LD_LIBRARY_PATH2nd
LD_RUN_PATH
LESS
LINES
listjobs
listlinks
loginsh
MAIL
mail
MAILCHECK
MAILPATH
MAILTO
MANPATH
naming
nobeep
noclobber2nd3rd
noglob
nonomatch
notify
OLDPWD
OPTARG
OPTIND
owd
PAGER2nd
PATH
path
PATH
builtinsdonotuse
example
findexecutablesusingwhich
keywordshellvariable
tcsh
positionalparameter
PRINTER
prompt
prompt2
prompt3
PS12nd
PS22nd
PS3
PS4
pushdsilent
pushdtohome
PWD
quoting
RANDOM
readonly
REPLY2nd
rmstar
savehist2nd3rd
shell
SHELL
shlvl
status
switches
tcsh2nd3rd
TERM2nd
time
tperiod2nd
user
verbose
version
VIMINIT
visiblebell
VISUAL
watch
who
shiftbuiltin2nd3rd4th
shlvlvariable
Short-circuitingoperator
Shortcut[SeeLink]
shredutility
Signal
defined2nd
hangup
kill
listof
names2nd
quit
softwaretermination
TERM
terminalinterrupt
Simplefilename2nd3rd4th
Singlequotationmark2nd
Singleversusdoublequotationmarks
Single-usersystem
Sizeoffile,displayusingls
Skiptotopofpage
sleepsystemcall
sleeputility2nd
Sleep,shell[Sleep]
Slice[SeeDisk;Partition,disk]
slocatedatabase
slocateutility
SMB[SeeSamba]
Smiley
Smilies,pluralofsmiley
SMTP
Snap,window
Sneakernet
Sniff
sofilenameextension2nd
SOCKS
Softlink[SeeSymbolic,link]
Softwareterminationsignal
Sort
sortutility2nd3rd4th5th6th
sourcebuiltin2nd
Sourcecodemanagement
Sourcerepository
sources.redhat.com/bzip22nd
SPACE2nd
SPACEBooleanoperator2nd
Spamdefined
Sparsefile2nd
Spawn[SeeFork]
Special
aliases
character
*
?
[_]
defined2nd
filenamegeneration
Heredocument
pathnameexpansion
quoting2nd
regularexpressions
standardinput
file,devicefile
parameters,shell2nd
spell_checkshellscript2nd
Spellingcorrection[Seeaspellutility]
Spinner
splintutility
splitutility
Splitting,word
Spontaneousprocess
Spoofing,IP
Spool
spooldirectory2nd
SQL
Squarebracket
defined
test
srcdirectory
sshutility
Stack
defined
directory,manipulation2nd
FILO
Stallman,Richard2nd3rd4th5th6th
Standard
directoriesandfiles
error2nd3rd
defined2nd
exec
filedescriptor2nd
redirect
shellscript
trap
input
defined2nd
exec
filedescriptor2nd
redirect
specialcharacter
output
append
defined2nd
exec
filedescriptor2nd
redirect2nd3rd
Standards
FHS
FreeStandardsGroup
FSG
FSSTND
LinuxFilesystemHierarchyStandard
LinuxStandardBase
LSB
optionhandling
Start
emacs
vim
Startupfile
.bash_loginfile
.bash_logoutfile
.bash_profilefile
.bashrcfile2nd
.cshrc
.cshrcfile
.emacs2nd3rd4th
.historyfile2nd
.inputrcfile
.loginfile2nd3rd
.logoutfile2nd
.profilefile2nd
.tcshrcfile2nd
.vimrcfile2nd
/etc
bashrcfile
csh.cshrcfile
csh.loginfile
csh.logoutfile
profilefile
bash
BASH_ENVvariable
defined
ENVvariable
listing
sourcetoexecute
tcsh
vim
VIMINITvariable
stat()systemcall2nd
Staticallylinkedlibrary
Status
exit
line
vim
statusvariable
stdio.hCheaderfile
Steele,Guy
Stickybit2nd
stopbuiltin
Stoppingajobusingthesuspendkey
Stoppingaprogram
straceutility
Streamingtape
Streams[SeeConnection-orientedprotocol]
String
comparing
defined
doublequotationmarks
findingusinggrep
patternmatching(bash)
variable
array
stringsutility
Stroustrup,Bjarne
Structure,data
StructuredQueryLanguage[SeeSQL]
sttyutility2nd
Stylesheet[SeeCSS]
Subdirectory2nd
Subnet
address
defined
mask
number
Subpixelhinting
Subroutine[SeeProcedure]
Subshell2nd3rd4th5th
Substitution
command2nd
parameter
Superblock
Supercomputers
Superuser
defined
explained
password,changingauser's
powers
priority
suspendbuiltin
Suspendkey2nd3rd4th5th6th7th8th9th
SVID[SeeSystem,System;VInterfaceDefinition]
Swap
defined
file,vim
space
Switch[SeeNetwork,switch[Switch]]
switchcontrolstructure
sylpheedutility
sylpheed.good-day.net
Symboltable
Symbolic
constant
debugger
link2nd3rd4th5th
creatingusingln
defined2nd
deletingusingrm
tcsh
symlink[SeeSymbolic,link]
Syntax,commandline
syslogddaemon
System
administration
cronutility
pwckutility
tune2fsutility
administrator
defined
powers
Superuser
call2nd3rd
bad,trapping
C,from
chmod()
chown()
close()
creat()
defined2nd
exec()2nd3rd
exit()
filesystemoperations
fork
fork()2nd3rd4th5th
getpid()
kill()
lseek()
manualsection
nice()
open()
processcontrol
read()2nd
sleep()
stat()2nd
tracingwithstrace
unlink()
wait()
write()2nd
console2nd
dataless
loadaverage
mode
performance
programmer
single-user
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
TABkey
Table,hash
tabs.cprogram2nd
tacutility2nd
tailutility2nd3rd4th
Tanenbaum,Andrew
Tape,streaming
tarfile
tarutility2nd3rd
tar.bz2filenameextension
tar.gzfilenameextension
tar.Zfilenameextension2nd
Targetfile,make
TCShell[Seetcsh]
tcl.sourceforge.net
TCP
tcsh
alias
arithmeticexpression
arrayofvariables2nd
builtins
controlstructure
defined
directorystackmanipulation2nd
environment
eventnumber
expressionoperator
featuressharedwithbash
filenamesubstitution
globbing
hashmechanism2nd
historymechanism
jobcontrol2nd3rd4th5th
leaving
nicebuiltin
nohupbuiltin
numericvariable2nd
positionalparameters
prompt2nd
quotingvariables
redirect,separatestdoutfromstderr
shellvariable
specialaliases
startupfile2nd
stringvariables
switchvariables
variablearray
variables
wordcompletion
tcshvariable
teeutility2nd
Teletypewriter2nd
TELNETprotocol
telnetutility2nd
Temporaryfile2nd
Tera-
TERMsignal
TERMvariable2nd
Termcap2nd
termcapfile
Terminal
ASCII
character-based
console2nd
defined
emulator,telnet
file
interruptsignal
name
ansi
linux
vt100
vt102
vt220
xterm
specifying
standardinput
standardoutput
X
Terminateaprogram
Terminfo2nd
terminfodatabase
terminfodirectory
Ternaryoperator2nd
testbuiltin2nd3rd4th5th6th7th8th9th10th11th
testutility2nd
Text
box
echo
file
tgzfilenameextension
Theme
thencontrolstructure2nd3rd4th
Thicknet
Thinnet
Thompson,Ken2nd
Thread
reentrantcode
safe[SeeReentrantcode]
Thumb
tifffilenameextension
Tildeexpansion2nd3rd4th
Tiledwindows
timebuiltin2nd3rd
Timetolive[SeeTTL]
timevariable
TkCVSutility
tldp.org/FAQ/Threads-FAQ
tmpdirectory
Toggle
Token2nd
Tokenringnetwork
Tooltip
Topofform
toputility
Top-downdesign
torrentfile
torrentfilenameextension
Torrent,BitTorrent[Torrent]
Torvalds,Linus2nd3rd4th5th
touchutility2nd3rd
tperiodvariable2nd
tputbuiltin2nd
trutility2nd3rd4th5th
Tracker,BitTorrent
Transientwindow
TransmissionControlProtocol[SeeTCP]
trapbuiltin2nd3rd
Treestructure
Trojanhorse2nd
trueutility
TTL
TTY[SeeTeletypewriter]
ttyfile
ttyutility2nd
tune2fsutility2nd
Tunneling
Tutorial
FTP
Gettingstartedwithemacs
Usingvimtocreateandeditafile
txtfilenameextension2nd
typebuiltin2nd
Typeoffile,displayusingls
Typefaceconventions
typescriptfile
typesetbuiltin2nd
Typographicalerror,correcting
tzfilenameextension
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
UDP
UID
chown
defined
effective
find
ulimitbuiltin
umaskbuiltin2nd3rd
unaliasbuiltin2nd3rd4th
uncompressutility
Undecillion
Undeclaredvariable
unhashbuiltin
Unicastpacket
uniqutility2nd
Uniquefilename2nd
UniversalCoordinatedTime[SeeUTC]
UNIX
Berkeley[SeeBerkeleyUNIX]
BourneShell
BSD[SeeBerkeleyUNIX]
SystemV2nd
SystemVInterfaceDefinition[SeeSystem,System;VInterface
Definition]
unix2dosutility
unlimitbuiltin
unlink()systemcall
Unmanagedwindow
Unpackarchivefileusingtar
unsetbuiltin2nd3rd4th5th6th
unsetenvbuiltin2nd
untilcontrolstructure2nd
unziputility
updatecommand(cvs)
updatedbutility
upsutility2nd
ups.sourceforge.net
uptimeutility2nd
Uptime,displayusingw[Uptime]
urandomfile
URI
URL
Usagemessage2nd3rd4th5th6th7th
User
createdvariable2nd
DatagramProtocol[SeeUDP]
finger
ID[SeeUID]
interface2nd
mode
variables,specialforms
w
who
uservariable
Userspace
UTC2nd
Utility
[_][Seetestbuiltin]
apropos2nd3rd4th
Apt[SeeApt]
aspell2nd
at
atq
atrm
autoconf
awk[Seegawk]
basename2nd3rd
batch
bison
BitTorrent[SeeBitTorrent]
builtinversus
bunzip22nd
bzcat2nd
bzip22nd3rd
bzip2recover2nd
cal
cat2nd3rd4th5th6th7th
chgrp
chmod2nd3rd
chown
chsh
cmp
comm
compress2nd3rd4th
configure2nd
cp2nd3rd4th
cpio2nd3rd
cron2nd
crontab
cut2nd3rd
cvs2nd
date2nd3rd4th
dd
ddd2nd
defined
df
diff2nd
diff3
dircolors
dos2unix
du2nd3rd
e2fsck
echo
ed2nd
egrep2nd3rd
elvis
emacs
Evolution
ex2nd
exmh
expr
fdformat
fgrep2nd
file2nd
find2nd3rd
findusingwhereis
findusingwhich
finger2nd3rd4th
flex
fmt
fsck
g++
gawk2nd3rd
gcc2nd
gcc(GNU)
gdb2nd3rd
getty
gprof
grep2nd3rd4th5th6th7th8th9th
gunzip2nd
gzip2nd
head
hostname
info2nd3rd
init
ispell[Seeaspellutility]
kdbg
kill
ld
ld-linux.so
ldd2nd
less2nd3rd4th5th
lint
ln2nd
locate
lock
login
lpq2nd
lpr2nd3rd4th
lprm2nd
ls2nd3rd4th5th6th7th8th
mail
make2nd3rd4th5th6th7th
makewhatis
man2nd3rd4th
mcd
mcopy
mdel
mdir
mesg
mformat
mingetty
mkdir2nd3rd4th5th
mke2fs
mkfs
mkfs.ext2
mkfs.ext3
mklost+found
more2nd3rd
Mtools
mtype
mv2nd3rd
mxgdb
names,typeface
nice
nohup2nd
nvi
od
option
passwd
paste
pr
procmail
ps2nd3rd4th5th
pstree
pwck
pwd
rcp
rlogin
rm2nd3rd4th5th
rmdir2nd
rsh
run-parts
scp
script
sdiff
sed2nd3rd
shred
sleep2nd
slocate
sort2nd3rd4th5th6th
splint
split
ssh
strace
strings
stty2nd
sylpheed
tac2nd
tail2nd3rd4th
tar2nd3rd
tee2nd
telnet2nd
test2nd3rd4th5th6th7th
TkCVS
top
touch2nd3rd
tr2nd3rd4th5th
true
tty2nd
tune2fs2nd
typeset
uncompress
uniq2nd
unix2dos
unzip
updatedb
ups2nd
uptime2nd
vi
view
vim
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
Variable
array
arrayofnumeric
braces
CShell
completion
defaultvalue,assign
defined
displayerrormessage
environment2nd
expansion2nd
exported
global2nd
keyword
local2nd3rd
modifiers
name,tcsh
naming2nd
numeric
quoting
readonly
remove
shell
substitutedefaultvalue
substitution2nd3rd
tcsh
undeclared
usercreated2nd
verbosevariable
versionvariable
vi
aaa][Seealsovim[vi]]
bashcommandlineeditor
clones
emacsversus
safeditscript
simulationinemacs
viutility
viewutility
Viewport[SeeWorkspace]
vim2nd
$
(key
)key
*
-key
.command2nd
.specialcharacter
.bash_profilefile
.loginfile
.vimrcstartupfile2nd
/key
>
?key
@symbol
[]
^
acommand
Acommand
abnormaltermination
activelinks
address
advancedcommands
anycharacterindicator
Appendcommand2nd
aspell
automaticmatching
autowrite
bkey
Bkey
beginning-of-lineindicator
beginning-of-wordindicator
blank-delimitedword
breakalineintwo
Buffer
General-Purpose2nd
Named
Ccommand
ccommand
Casecommand
casesensitivity2nd
cccommand
Changecommand2nd
changetext
character
character-classdefinition
command2nd
Commandmode2nd
compatibility,vi
CONTROL-Bkey
CONTROL-Dkey
CONTROL-Fkey
CONTROL-Gkey2nd
CONTROL-Tkey
CONTROL-Ukey
CONTROL-Vkey
CONTROL-Wkey
copytext
correctamistake2nd3rd
correcttext
crashrecovery
createafile
currentcharacter
cursormovement[Seevim,vim;movethecursor]
dcommand2nd
ddcommand2nd
Deletecharactercommand
deletecharacters
Deletecommand2nd
deletetext2nd
DOWNARROWkey
editafile
editanotherfile
endasession2nd
end-of-lineindicator
end-of-wordindicator
entertext
erasekey
ESCAPEkey
exitfrom
exit,emergency2nd
fcommand
Filecommand
filesize
formattingusingfmt
Gkey
General-Purposebuffer2nd
gettingstarted
Gotocommand
hkey
Hkey
history
homepage
icommand
Icommand
incrementalsearch
indention2nd
Inputmode2nd3rd4th
Insertcommand2nd
inserttext2nd3rd4th
invisiblecharacters
Jcommand
jkey
Joincommand
kkey
lkey
Lkey
LastLinemode2nd3rd4th5th6th7th
LEFTARROWkey
line
killkey
length
number2nd
wrap2nd
links,active
mcommand
Mkey
marker
matching,automatic
mistake,correct
modes
movetext
movethecursor2nd
bycharacters
bylines
byparagraphs
bysentences
bywords
toaspecificcharacter
withinthescreen
Ncommand
ncommand
Namedbuffer
Normalmode[Seevim,vim;Commandmode]
number,line
ocommand
Ocommand
openaline
Opencommand2nd
overwritetext
pcommand
Pcommand
pagebreak
PAGEDOWNkey
PAGEUPkey
paragraph
parameter
autoindent
autowrite
compatible
flash
ignorecase
incsearch
list
magic
noautoindent
noautowrite
nocompatible
noflash
noignorecase
noincsearch
nolist
nomagic
nonumber
noreport
noshiftwidth
noshowmatch
noshowmode
nowrapscan
number
report
set2nd
shell2nd
shiftwidth
showmatch
showmode
wrapmargin2nd
wrapscan
Putcommand
qcommand
quit2nd
Quitcommand
Quotecommand
rcommand
Rcommand
rcommand2nd
Readcommand2nd
recovertext
redrawthescreen
regularexpression
Repeatcommand
RepeatFactor2nd3rd
replace
Replacecommand2nd
replacestring
replacetext
replacementstring
reportonchanges
RETURNkey2nd
RIGHTARROWkey
Scommand
scommand2nd
screen
scroll
search
andreplace
command
incremental
string2nd
wrapscanparameter
sentence
set
marker
parameter
shell
showmatch2nd
SPACEbar
specialcharacters2nd3rd4th
spellchecking
startover
starting2nd
startupfile
Statuscommand
statusline
Substitutecommand2nd3rd
substitutetext
substitution
summary
terminalspecification
tildesymbol
Transposecommand(~)
ucommand2nd
Ucommand
ucommand
undochanges2nd
Undocommand2nd
UnitofMeasure2nd3rd
UPARROWkey
vicompatibility
viewdifferentpartsoftheWorkbuffer
viewutility
VIMINITvariable
wcommand2nd
wkey
Wkey
word
Workbuffer2nd3rd
Writeaddress
Writecommand2nd
xcommand2nd
ycommand
Yankcommand2nd
yycommand
ZZcommand2nd
{key
}key
~command
~symbol
VIMINITvariable
vimtutorutility
Virtual
console2nd
privatenetwork[SeeVPN]
Virus
visiblebellvariable
Visitingafile,emacs2nd
VISUALvariable
Vixiecron
VLAN
VPN
vt100terminal
vt102terminal
vt220terminal
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
wutility2nd
W2K
W3C
waitbuiltin2nd
wait()systemcall2nd
Wakeup,process
WAN2nd
WAP
watchutility
watchvariable
wcutility2nd
Webring
whatisdatabase
whatisutility
wherebuiltin
whereisutility
whichbuiltin2nd
whichutility2nd
whilecontrolstructure2nd3rd4th5th6th7th
Whitespace
commandline
defined2nd
quoting
whoami
whoutility2nd3rd4th5th6th
whovariable
whosshellscript2nd3rd
whosonshellscript
Wi-Fi
Wideareanetwork[SeeWAN]
Widget
Wildcard2nd3rd[SeealsoMetacharacter]
Window
cascading
defined
file
ignored
manager2nd3rd
minimize
scrollbar
share[SeeSamba,share]
snap
thumb
tiled
transient
unmanaged
Windows
convertfiles
filenamelimitation2nd
privilegedport
WINS
Wipingafile
Word
completion
defined2nd3rd4th
deleting
designator
erasekey2nd
parseacommandline
splitting(bash)
word_countshellscript
word_usageshellscript
Workbuffer,vim2nd3rd4th
Workingdirectory
changeusingcd
defined2nd
executeafilein
PATH
relativepathnamesand
significanceof
versushomedirectory
Workspace
Workstation2nd
WorldWideWebConsortium
Worm2nd
Writeaccess
writeutility2nd3rd
write()systemcall2nd
wtmpfile
www.bittorrent.com
www.bostic.com/vi
www.catb.org/~esr/faqs/smart-questions.html
www.cs.purdue.edu/research/xinu.html
www.cs.vu.nl/~ast/minix.html
www.cvshome.org
www.foldoc.org2nd3rd
www.freebsd.org
www.freestandards.org
www.gnome.org
www.gnu.org2nd
www.gnu.org/licenses/licenses.html
www.gnu.org/manual
www.gnu.org/philosophy/free-sw.html
www.gnu.org/software/bash
www.gnu.org/software/ddd
www.gnu.org/software/emacs2nd
www.gnu.org/software/gcc/gcc.html
www.gnu.org/software/make/manual/make.html
www.gnu.org/software/texinfo/manual/info-stnd
www.google.com2nd
www.gzip.org/zlib
www.ibiblio.org/pub/Linux
www.ibm.com/linux
www.kde.org
www.liacs.nl/~wichert/strace
www.linuxbase.org
www.netbsd.org
www.opengroup.org/austin/papers/posix_faq.html
www.pasc.org
www.pathname.com/fhs
www.perl.org
www.procmail.org
www.sobell.com2nd3rd4th5th6th7th8th
www.splint.org
www.stallman.org
www.tcsh.org
www.tldp.org2nd3rd4th
www.tldp.org/links
www.twobarleycorns.net/tkcvs.html
www.vim.org2nd3rd
www.winehq.com
wysiwyg
Index
[SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T]
[U][V][W][X][Y][Z]
Xterminal
XWindowSystem
defined
emacs
Xinerama
X11directory2nd3rd4th
X11R6directory2nd
xargsutility2nd
XDMCP
xDSL
Xinerama
XINU
XML
XSM
xtermterminalname
xxgdbutility2nd


