AnintroductiontotheCshell WilliamJoy ComputerScienceDivision DepartmentofElectricalEngineeringandComputerScience UniversityofCalifornia,Berkeley Berkeley,California94720 ABSTRACT CshisanewcommandlanguageinterpreterforUNIX◯rsystems.Itincorporatesgoodfeaturesofothershellsandahistorymechanismsimilartotheredoof INTERLISP.Whileincorporatingmanyfeaturesofothershellswhichmakewriting shellprograms(shellscripts)easier,mostofthefeaturesuniquetocshare designedmorefortheinteractiveUNIXuser. UNIXuserswhohavereadageneralintroductiontothesystemwillfinda valuablebasicexplanationoftheshellhere.Simpleterminalinteractionwithcsh ispossibleafterreadingjustthefirstsectionofthisdocument.Thesecondsectiondescribestheshellscapabilitieswhichyoucanexploreafteryouhavebegun tobecomeacquaintedwiththeshell.Latersectionsintroducefeatureswhichare useful,butnotnecessaryforallusersoftheshell. Backmatterincludesanappendixlistingspecialcharactersoftheshelland aglossaryoftermsandcommandsintroducedinthismanual. 8April1993 AnintroductiontotheCshell WilliamJoy ComputerScienceDivision DepartmentofElectricalEngineeringandComputerScience UniversityofCalifornia,Berkeley Berkeley,California94720 Introduction Ashellisacommandlanguageinterpreter.Cshisthenameofoneparticularcommand interpreteronUNIX.Theprimarypurposeofcshistotranslatecommandlinestypedataterminalintosystemactions,suchasinvocationofotherprograms.Cshisauserprogramjustlikeany youmightwrite.Hopefully,cshwillbeaveryusefulprogramforyouininteractingwiththeUNIX system. Inadditiontothisdocument,youwillwanttorefertoacopyoftheUNIXprogrammer’s manual.Thecshdocumentationinthemanualprovidesafulldescriptionofallfeaturesofthe shellandisafinalreferenceforquestionsabouttheshell. Manywordsinthisdocumentareshowninitalics.Theseareimportantwords;namesof commands,andwordswhichhavespecialmeaningindiscussingtheshellandUNIX.Manyofthe wordsaredefinedinaglossaryattheendofthisdocument.Ifyoudon’tknowwhatismeantby aword,youshouldlookforitintheglossary. Acknowledgements Numerouspeoplehaveprovidedgoodinputaboutpreviousversionsofcshandaidedinits debuggingandinthedebuggingofitsdocumentation.IwouldespeciallyliketothankMichael Ubellwhomadethecrucialobservationthathistorycommandscouldbedonewellovertheword structureofinputtext,andimplementedaprototypehistorymechanisminanolderversionofthe shell.EricAllmanhasalsoprovidedalargenumberofusefulcommentsontheshell,helpingto unifythoseconceptswhicharepresentandtoidentifyandeliminateuselessandmarginallyuseful features.MikeO’Briensuggestedthepathnamehashingmechanismwhichspeedscommandexecution.JimKulpaddedthejobcontrolanddirectorystackprimitivesandaddedtheirdocumentationtothisintroduction.

-2-1.Terminalusageoftheshell 1.1.Thebasicnotionofcommands AshellinUNIXactsmostlyasamediumthroughwhichotherprogramsareinvoked.While ithasasetofbuiltinfunctionswhichitperformsdirectly,mostcommandscauseexecutionofprogramsthatare,infact,externaltotheshell.Theshellisthusdistinguishedfromthecommand interpretersofothersystemsbothbythefactthatitisjustauserprogram,andbythefactthat itisusedalmostexclusivelyasamechanismforinvokingotherprograms. CommandsintheUNIXsystemconsistofalistofstringsorwordsinterpretedasacommand namefollowedbyarguments.Thusthecommand mailbill consistsoftwowords.Thefirstwordmailnamesthecommandtobeexecuted,inthiscasethe mailprogramwhichsendsmessagestootherusers.Theshellusesthenameofthecommandin attemptingtoexecuteitforyou.Itwilllookinanumberofdirectoriesforafilewiththename mailwhichisexpectedtocontainthemailprogram. Therestofthewordsofthecommandaregivenasargumentstothecommanditselfwhenit isexecuted.Inthiscasewespecifiedalsotheargumentbillwhichisinterpretedbythemailprogramtobethenameofausertowhommailistobesent.Innormalterminalusagewemight usethemailcommandasfollows. %mailbill Ihaveaquestionaboutthecshdocumentation. Mydocumentseemstobemissingpage5. Doesapagefiveexist? Bill EOT % Herewetypedamessagetosendtobillandendedthismessagewitha↑Dwhichsentan end-of-filetothemailprogram.(Hereandthroughoutthisdocument,thenotation‘‘↑x’’istobe read‘‘control-x’’andrepresentsthestrikingofthexkeywhilethecontrolkeyishelddown.)The mailprogramthenechoedthecharacters‘EOT’andtransmittedourmessage.Thecharacters‘% ’wereprintedbeforeandafterthemailcommandbytheshelltoindicatethatinputwasneeded. Aftertypingthe‘%’prompttheshellwasreadingcommandinputfromourterminal.We typedacompletecommand‘mailbill’.Theshellthenexecutedthemailprogramwithargument billandwentdormantwaitingforittocomplete.Themailprogramthenreadinputfromourterminaluntilwesignalledanend-of-fileviatypinga↑Dafterwhichtheshellnoticedthatmailhad completedandsignaledusthatitwasreadytoreadfromtheterminalagainbyprintinganother ‘%’prompt. ThisistheessentialpatternofallinteractionwithUNIXthroughtheshell.Acompletecommandistypedattheterminal,theshellexecutesthecommandandwhenthisexecutioncompletes,itpromptsforanewcommand.Ifyouruntheeditorforanhour,theshellwillpatiently waitforyoutofinisheditingandobedientlypromptyouagainwheneveryoufinishediting. Anexampleofausefulcommandyoucanexecutenowisthetsetcommand,whichsetsthe defaulteraseandkillcharactersonyourterminal−theerasecharactererasesthelastcharacter youtypedandthekillcharactererasestheentirelineyouhaveenteredsofar.Bydefault,the erasecharacteris‘#’andthekillcharacteris‘@’.MostpeoplewhouseCRTdisplayspreferto usethebackspace(↑H)characterastheirerasecharactersinceitistheneasiertoseewhatyou havetypedsofar.Youcanmakethisbetruebytyping tset−e whichtellstheprogramtsettosettheerasecharacter,anditsdefaultsettingforthischaracteris -3-abackspace. 1.2.Flagarguments AusefulnotioninUNIXisthatofaflagargument.Whilemanyargumentstocommands specifyfilenamesorusernamessomeargumentsratherspecifyanoptionalcapabilityofthecommandwhichyouwishtoinvoke.Byconvention,suchargumentsbeginwiththecharacter‘−’ (hyphen).Thusthecommand ls willproducealistofthefilesinthecurrentworkingdirectory.Theoption−sisthesizeoption, and ls−s causeslstoalsogive,foreachfilethesizeofthefileinblocksof512characters.ThemanualsectionforeachcommandintheUNIXreferencemanualgivestheavailableoptionsforeachcommand.Thelscommandhasalargenumberofusefulandinterestingoptions.Mostothercommandshaveeithernooptionsoronlyoneortwooptions.Itishardtorememberoptionsofcommandswhicharenotusedveryfrequently,somostUNIXutilitiesperformonlyoneortwofunctionsratherthanhavingalargenumberofhardtorememberoptions. 1.3.Outputtofiles Commandsthatnormallyreadinputorwriteoutputontheterminalcanalsobeexecuted withthisinputand/oroutputdonetoafile. Thussupposewewishtosavethecurrentdateinafilecalled‘now’.Thecommand date willprintthecurrentdateonourterminal.Thisisbecauseourterminalisthedefaultstandard outputforthedatecommandandthedatecommandprintsthedateonitsstandardoutput.The shellletsusredirectthestandardoutputofacommandthroughanotationusingthemetacharacter‘>’andthenameofthefilewhereoutputistobeplaced.Thusthecommand date>now runsthedatecommandsuchthatitsstandardoutputisthefile‘now’ratherthantheterminal. Thusthiscommandplacesthecurrentdateandtimeintothefile‘now’.Itisimportanttoknow thatthedatecommandwasunawarethatitsoutputwasgoingtoafileratherthantotheterminal.Theshellperformedthisredirectionbeforethecommandbeganexecuting. Oneotherthingtonotehereisthatthefile‘now’neednothaveexistedbeforethedate commandwasexecuted;theshellwouldhavecreatedthefileifitdidnotexist.Andifthefiledid exist?Ifithadexistedpreviouslythesepreviouscontentswouldhavebeendiscarded!Ashell optionnoclobberexiststopreventthisfromhappeningaccidentally;itisdiscussedinsection2.2. Thesystemnormallykeepsfileswhichyoucreatewith‘>’andallotherfiles.Thusthe defaultisforfilestobepermanent.Ifyouwishtocreateafilewhichwillberemovedautomatically,youcanbeginitsnamewitha‘#’character,this‘scratch’characterdenotesthefactthat thefilewillbeascratchfile.*Thesystemwillremovesuchfilesafteracoupleofdays,orsooner iffilespacebecomesverytight.Thus,inrunningthedatecommandabove,wedon’treallywant tosavetheoutputforever,sowewouldmorelikelydo date>#now *Notethatifyourerasecharacterisa‘#’,youwillhavetoprecedethe‘#’witha‘\’.Thefactthat the‘#’characteristheold(pre-CRT)standarderasecharactermeansthatitseldomappearsinafile name,andallowsthisconventiontobeusedforscratchfiles.IfyouareusingaCRT,yourerasecharactershouldbea↑H,aswedemonstratedinsection1.1howthiscouldbesetup.

-4-1.4.Metacharactersintheshell Theshellhasalargenumberofspecialcharacters(like‘>’)whichindicatespecialfunctions. Wesaythatthesenotationshavesyntacticandsemanticmeaningtotheshell.Ingeneral,most characterswhichareneitherlettersnordigitshavespecialmeaningtotheshell.Weshallshortly learnameansofquotationwhichallowsustousemetacharacterswithouttheshelltreatingthem inanyspecialway. Metacharactersnormallyhaveeffectonlywhentheshellisreadingourinput.Weneednot worryaboutplacingshellmetacharactersinaletterwearesendingviamail,orwhenwearetypingintextordatatosomeotherprogram.Notethattheshellisonlyreadinginputwhenithas promptedwith‘%’. 1.5.Inputfromfiles;pipelines Welearnedabovehowtoredirectthestandardoutputofacommandtoafile.Itisalsopossibletoredirectthestandardinputofacommandfromafile.Thisisnotoftennecessarysince mostcommandswillreadfromafilewhosenameisgivenasanargument.Wecangivethecommand sort<data torunthesortcommandwithstandardinput,wherethecommandnormallyreadsitsinput,from thefile‘data’.Wewouldmorelikelysay sortdata lettingthesortcommandopenthefile‘data’forinputitselfsincethisislesstotype. Weshouldnotethatifwejusttyped sort thenthesortprogramwouldsortlinesfromitsstandardinput.Sincewedidnotredirectthestandardinput,itwouldsortlinesaswetypedthemontheterminaluntilwetypeda↑Dtoindicate anend-of-file. Amostusefulcapabilityistheabilitytocombinethestandardoutputofonecommandwith thestandardinputofanother,i.e.torunthecommandsinasequenceknownasapipeline.For instancethecommand ls−s normallyproducesalistofthefilesinourdirectorywiththesizeofeachinblocksof512characters.Ifweareinterestedinlearningwhichofourfilesislargestwemaywishtohavethissorted bysizeratherthanbyname,whichisthedefaultwayinwhichlssorts.Wecouldlookatthe manyoptionsoflstoseeiftherewasanoptiontodothisbutwouldeventuallydiscoverthat thereisnot.Insteadwecanuseacoupleofsimpleoptionsofthesortcommand,combiningit withlstogetwhatwewant. The−noptionofsortspecifiesanumericsortratherthananalphabeticsort.Thus ls−s|sort−n specifiesthattheoutputofthelscommandrunwiththeoption−sistobepipedtothecommand sortrunwiththenumericsortoption.Thiswouldgiveusasortedlistofourfilesbysize,but withthesmallestfirst.Wecouldthenusethe−rreversesortoptionandtheheadcommandin combinationwiththepreviouscommanddoing ls−s|sort−n−r|head−5 Herewehavetakenalistofourfilessortedalphabetically,eachwiththesizeinblocks.Wehave runthistothestandardinputofthesortcommandaskingittosortnumericallyinreverseorder (largestfirst).Thisoutputhasthenbeenrunintothecommandheadwhichgivesusthefirstfew lines.Inthiscasewehaveaskedheadforthefirst5lines.Thusthiscommandgivesusthenames -5-andsizesofour5largestfiles. Thenotationintroducedaboveiscalledthepipemechanism.Commandsseparatedby‘|’ charactersareconnectedtogetherbytheshellandthestandardoutputofeachisrunintothe standardinputofthenext.Theleftmostcommandinapipelinewillnormallytakeitsstandard inputfromtheterminalandtherightmostwillplaceitsstandardoutputontheterminal.Other examplesofpipelineswillbegivenlaterwhenwediscussthehistorymechanism;oneimportant useofpipeswhichisillustratedthereisintheroutingofinformationtothelineprinter. 1.6.Filenames Manycommandstobeexecutedwillneedthenamesoffilesasarguments.UNIXpathnames consistofanumberofcomponentsseparatedby‘/’.Eachcomponentexceptthelastnamesa directoryinwhichthenextcomponentresides,ineffectspecifyingthepathofdirectoriestofollow toreachthefile.Thusthepathname /etc/motd specifiesafileinthedirectory‘etc’whichisasubdirectoryoftherootdirectory‘/’.Withinthis directorythefilenamedis‘motd’whichstandsfor‘messageoftheday’.Apathnamethatbegins withaslashissaidtobeanabsolutepathnamesinceitisspecifiedfromtheabsolutetopofthe entiredirectoryhierarchyofthesystem(theroot).Pathnameswhichdonotbeginwith‘/’are interpretedasstartinginthecurrentworkingdirectory,whichis,bydefault,yourhomedirectory andcanbechangeddynamicallybythecdchangedirectorycommand.Suchpathnamesaresaid toberelativetotheworkingdirectorysincetheyarefoundbystartingintheworkingdirectory anddescendingtolowerlevelsofdirectoriesforeachcomponentofthepathname.Ifthepathnamecontainsnoslashesatallthenthefileiscontainedintheworkingdirectoryitselfandthe pathnameismerelythenameofthefileinthisdirectory.Absolutepathnameshavenorelationto theworkingdirectory. Mostfilenamesconsistofanumberofalphanumericcharactersand‘.’s(periods).Infact,all printingcharactersexcept‘/’(slash)mayappearinfilenames.Itisinconvenienttohavemost non-alphabeticcharactersinfilenamesbecausemanyofthesehavespecialmeaningtotheshell. Thecharacter‘.’(period)isnotashell-metacharacterandisoftenusedtoseparatetheextension ofafilenamefromthebaseofthename.Thus prog.cprog.oprog.errsprog.output arefourrelatedfiles.Theyshareabaseportionofaname(abaseportionbeingthatpartofthe namethatisleftwhenatrailing‘.’andfollowingcharacterswhicharenot‘.’arestrippedoff). Thefile‘prog.c’mightbethesourceforaCprogram,thefile‘prog.o’thecorrespondingobject file,thefile‘prog.errs’theerrorsresultingfromacompilationoftheprogramandthefile ‘prog.output’theoutputofarunoftheprogram. Ifwewishedtorefertoallfourofthesefilesinacommand,wecouldusethenotation prog.* Thiswordisexpandedbytheshell,beforethecommandtowhichitisanargumentisexecuted, intoalistofnameswhichbeginwith‘prog.’.Thecharacter‘*’herematchesanysequence (includingtheemptysequence)ofcharactersinafilename.Thenameswhichmatcharealphabeticallysortedandplacedintheargumentlistofthecommand.Thusthecommand echoprog.* willechothenames prog.cprog.errsprog.oprog.output Notethatthenamesareinsortedorderhere,andadifferentorderthanwelistedthemabove. Theechocommandreceivesfourwordsasarguments,eventhoughweonlytypedonewordasas argumentdirectly.Thefourwordsweregeneratedbyfilenameexpansionoftheoneinputword.

-6-Othernotationsforfilenameexpansionarealsoavailable.Thecharacter‘?’matchesany singlecharacterinafilename.Thus echo?????? willechoalineoffilenames;firstthosewithonecharacternames,thenthosewithtwocharacter names,andfinallythosewiththreecharacternames.Thenamesofeachlengthwillbeindependentlysorted. Anothermechanismconsistsofasequenceofcharactersbetween‘[’and‘]’.Thismetasequencematchesanysinglecharacterfromtheenclosedset.Thus prog.[co] willmatch prog.cprog.o intheexampleabove.Wecanalsoplacetwocharactersarounda‘−’inthisnotationtodenotea range.Thus chap.[1−5] mightmatchfiles chap.1chap.2chap.3chap.4chap.5 iftheyexisted.Thisisshorthandfor chap.[12345] andotherwiseequivalent. Animportantpointtonoteisthatifalistofargumentwordstoacommand(anargument list)containsfilenameexpansionsyntax,andifthisfilenameexpansionsyntaxfailstomatchany existingfilenames,thentheshellconsidersthistobeanerrorandprintsadiagnostic Nomatch. anddoesnotexecutethecommand. Anotherveryimportantpointisthatfileswiththecharacter‘.’atthebeginningaretreated specially.Neither‘*’or‘?’orthe‘[’‘]’mechanismwillmatchit.Thispreventsaccidentalmatchingofthefilenames‘.’and‘..’intheworkingdirectorywhichhavespecialmeaningtothesystem, aswellasotherfilessuchas.cshrcwhicharenotnormallyvisible.Wewilldiscussthespecialrole ofthefile.cshrclater. Anotherfilenameexpansionmechanismgivesaccesstothepathnameofthehomedirectory ofotherusers.Thisnotationconsistsofthecharacter‘˜ ’(tilde)followedbyanotherusers’login name.Forinstancetheword‘˜ bill’wouldmaptothepathname‘/usr/bill’ifthehomedirectory for‘bill’was‘/usr/bill’.Since,onlargesystems,usersmayhavelogindirectoriesscatteredover manydifferentdiskvolumeswithdifferentprefixdirectorynames,thisnotationprovidesareliable wayofaccessingthefilesofotherusers. Aspecialcaseofthisnotationconsistsofa‘˜ ’alone,e.g.‘˜ /mbox’.Thisnotationis expandedbytheshellintothefile‘mbox’inyourhomedirectory,i.e.into‘/usr/bill/mbox’forme onErnieCo-vax,theUCBComputerScienceDepartmentVAXmachine,wherethisdocument wasprepared.Thiscanbeveryusefulifyouhaveusedcdtochangetoanotherdirectoryand havefoundafileyouwishtocopyusingcp.IfIgivethecommand cpthatfile˜ theshellwillexpandthiscommandto cpthatfile/usr/bill sincemyhomedirectoryis/usr/bill.

-7-Therealsoexistsamechanismusingthecharacters‘{’and‘}’forabbreviatingasetof wordswhichhavecommonpartsbutcannotbeabbreviatedbytheabovemechanismsbecause theyarenotfiles,arethenamesoffileswhichdonotyetexist,arenotthusconveniently described.Thismechanismwillbedescribedmuchlater,insection4.2,asitisusedlessfrequently. 1.7.Quotation Wehavealreadyseenanumberofmetacharactersusedbytheshell.Thesemetacharacters poseaprobleminthatwecannotusethemdirectlyaspartsofwords.Thusthecommand echo* willnotechothecharacter‘*’.Itwilleitherechoansortedlistoffilenamesinthecurrentworkingdirectory,orprintthemessage‘Nomatch’iftherearenofilesintheworkingdirectory. Therecommendedmechanismforplacingcharacterswhichareneithernumbers,digits,‘/’, ‘.’or‘−’inanargumentwordtoacommandistoencloseitwithsinglequotationcharacters‘´ ’, i.e. echo´ *´ Thereisonespecialcharacter‘!’whichisusedbythehistorymechanismoftheshellandwhich cannotbeescapedbyplacingitwithin‘´ ’characters.Itandthecharacter‘´ ’itselfcanbeprecededbyasingle‘\’topreventtheirspecialmeaning.Thus echo\´ \! prints ´ ! Thesetwomechanismssufficetoplaceanyprintingcharacterintoawordwhichisanargumentto ashellcommand.Theycanbecombined,asin echo\´ ´ *´ whichprints ´ * sincethefirst‘\’escapedthefirst‘´ ’andthe‘*’wasenclosedbetween‘´ ’characters. 1.8.Terminatingcommands Whenyouareexecutingacommandandtheshelliswaitingforittocompletethereareseveralwaystoforceittostop.Forinstanceifyoutypethecommand cat/etc/passwd thesystemwillprintacopyofalistofallusersofthesystemonyourterminal.Thisislikelyto continueforseveralminutesunlessyoustopit.YoucansendanINTERRUPTsignaltothecat commandbytypingtheDELorRUBOUTkeyonyourterminal.*SincecatdoesnottakeanyprecautionstoavoidorotherwisehandlethissignaltheINTERRUPTwillcauseittoterminate.The shellnoticesthatcathasterminatedandpromptsyouagainwith‘%’.IfyouhitINTERRUPT again,theshellwilljustrepeatitspromptsinceithandlesINTERRUPTsignalsandchoosestocontinuetoexecutecommandsratherthanterminatinglikecatdid,whichwouldhavetheeffectof loggingyouout. Anotherwayinwhichmanyprogramsterminateiswhentheygetanend-of-filefromtheir standardinput.Thusthemailprograminthefirstexampleabovewasterminatedwhenwetyped a↑Dwhichgeneratesanend-of-filefromthestandardinput.Theshellalsoterminateswhenit getsanend-of-fileprinting‘logout’;UNIXthenlogsyouoffthesystem.Sincethismeansthat *Manyusersusestty(1)tochangetheinterruptcharacterto↑C.

-8-typingtoomany↑D’scanaccidentallylogusoff,theshellhasamechanismforpreventingthis. Thisignoreeofoptionwillbediscussedinsection2.2. Ifacommandhasitsstandardinputredirectedfromafile,thenitwillnormallyterminate whenitreachestheendofthisfile.Thusifweexecute mailbill<prepared.text themailcommandwillterminatewithoutourtypinga↑D.Thisisbecauseitreadtotheend-of-fileofourfile‘prepared.text’inwhichweplacedamessagefor‘bill’withaneditorprogram.We couldalsohavedone catprepared.text|mailbill sincethecatcommandwouldthenhavewrittenthetextthroughthepipetothestandardinput ofthemailcommand.Whenthecatcommandcompleteditwouldhaveterminated,closingdown thepipelineandthemailcommandwouldhavereceivedanend-of-filefromitandterminated. Usingapipehereismorecomplicatedthanredirectinginputsowewouldmorelikelyusethefirst form.ThesecommandscouldalsohavebeenstoppedbysendinganINTERRUPT. Anotherpossibilityforstoppingacommandistosuspenditsexecutiontemporarily,with thepossibilityofcontinuingexecutionlater.ThisisdonebysendingaSTOPsignalviatypinga ↑Z.Thissignalcausesallcommandsrunningontheterminal(usuallyonebutmoreifapipeline isexecuting)tobecomesuspended.Theshellnoticesthatthecommand(s)havebeensuspended, types‘Stopped’andthenpromptsforanewcommand.Thepreviouslyexecutingcommandhas beensuspended,butotherwiseunaffectedbytheSTOPsignal.Anyothercommandscanbeexecutedwhiletheoriginalcommandremainssuspended.Thesuspendedcommandcanbecontinued usingthefgcommandwithnoarguments.Theshellwillthenretypethecommandtoremindyou whichcommandisbeingcontinued,andcausethecommandtoresumeexecution.Unlessany inputfilesinusebythesuspendedcommandhavebeenchangedinthemeantime,thesuspension hasnoeffectwhatsoeverontheexecutionofthecommand.Thisfeaturecanbeveryusefulduringediting,whenyouneedtolookatanotherfilebeforecontinuing.Anexampleofcommandsuspensionfollows. %mailharold Someonejustcopiedabigfileintomydirectoryanditsnameis ↑Z Stopped %ls funnyfile prog.c prog.o %jobs [1]+Stoppedmailharold %fg mailharold funnyfile.Doyouknowwhodidit? EOT % InthisexamplesomeonewassendingamessagetoHaroldandforgotthenameofthefilehe wantedtomention.Themailcommandwassuspendedbytyping↑Z.Whentheshellnoticed thatthemailprogramwassuspended,ittyped‘Stopped’andpromptedforanewcommand. Thenthelscommandwastypedtofindoutthenameofthefile.Thejobscommandwasrunto findoutwhichcommandwassuspended.Atthistimethefgcommandwastypedtocontinueexecutionofthemailprogram.Inputtothemailprogramwasthencontinuedandendedwitha↑D whichindicatedtheendofthemessageatwhichtimethemailprogramtypedEOT.Thejobs commandwillshowwhichcommandsaresuspended.The↑Zshouldonlybetypedatthebeginningofalinesinceeverythingtypedonthecurrentlineisdiscardedwhenasignalissentfromthe -9-keyboard.ThisalsohappensonINTERRUPT,andQUITsignals.Moreinformationonsuspending jobsandcontrollingthemisgiveninsection2.6. Ifyouwriteorrunprogramswhicharenotfullydebuggedthenitmaybenecessarytostop themsomewhatungracefully.ThiscanbedonebysendingthemaQUITsignal,sentbytypinga ↑\.Thiswillusuallyprovoketheshelltoproduceamessagelike: Quit(Coredumped) indicatingthatafile‘core’hasbeencreatedcontaininginformationabouttheprogram‘a.out’s statewhenitterminatedduetotheQUITsignal.Youcanexaminethisfileyourself,orforward informationtothemaintaineroftheprogramtellinghim/herwherethecorefileis. Ifyourunbackgroundcommands(asexplainedinsection2.6)thenthesecommandswill ignoreINTERRUPTandQUITsignalsattheterminal.Tostopthemyoumustusethekillcommand.Seesection2.6foranexample. Ifyouwanttoexaminetheoutputofacommandwithouthavingitmoveoffthescreenas theoutputofthe cat/etc/passwd commandwill,youcanusethecommand more/etc/passwd Themoreprogrampausesaftereachcompletescreenfulandtypes‘−−More−−’atwhichpoint youcanhitaspacetogetanotherscreenful,areturntogetanotherline,ora‘q’toendthemore program.Youcanalsousemoreasafilter,i.e. cat/etc/passwd|more worksjustlikethemoresimplemorecommandabove. Forstoppingoutputofcommandsnotinvolvingmoreyoucanusethe↑Skeytostopthe typeout.Thetypeoutwillresumewhenyouhit↑Qoranyotherkey,but↑Qisnormallyused becauseitonlyrestartstheoutputanddoesnotbecomeinputtotheprogramwhichisrunning. Thisworkswellonlow-speedterminals,butat9600bauditishardtotype↑Sand↑Qfast enoughtopaginatetheoutputnicely,andaprogramlikemoreisusuallyused. Anadditionalpossibilityistousethe↑Oflushoutputcharacter;whenthischaracteris typed,alloutputfromthecurrentcommandisthrownaway(quickly)untilthenextinputread occursoruntilthenextshellprompt.Thiscanbeusedtoallowacommandtocompletewithout havingtosufferthroughtheoutputonaslowterminal;↑Oisatoggle,soflushingcanbeturned offbytyping↑Oagainwhileoutputisbeingflushed. 1.9.Whatnow? Wehavesofarseenanumberofmechanismsoftheshellandlearnedalotaboutthewayin whichitoperates.Theremainingsectionswillgoyetfurtherintotheinternalsoftheshell,but youwillsurelywanttotryusingtheshellbeforeyougoanyfurther.Totryityoucanloginto UNIXandtypethefollowingcommandtothesystem: chshmyname/bin/csh Here‘myname’shouldbereplacedbythenameyoutypedtothesystempromptof‘login:’toget ontothesystem.ThusIwoulduse‘chshbill/bin/csh’.Youonlyhavetodothisonce;it takeseffectatnextlogin.Youarenowreadytotryusingcsh. Beforeyoudothe‘chsh’command,theshellyouareusingwhenyoulogintothesystemis ‘/bin/sh’.Infact,muchoftheabovediscussionisapplicableto‘/bin/sh’.Thenextsectionwill introducemanyfeaturesparticulartocshsoyoushouldchangeyourshelltocshbeforeyoubegin readingit.

-10-2.Detailsontheshellforterminalusers 2.1.Shellstartupandtermination Whenyoulogin,theshellisstartedbythesysteminyourhomedirectoryandbeginsby readingcommandsfromafile.cshrcinthisdirectory.Allshellswhichyoumaystartduringyour terminalsessionwillreadfromthisfile.Wewilllaterseewhatkindsofcommandsareusefully placedthere.Fornowweneednothavethisfileandtheshelldoesnotcomplainaboutits absence. Aloginshell,executedafteryoulogintothesystem,will,afteritreadscommandsfrom .cshrc,readcommandsfromafile.loginalsoinyourhomedirectory.Thisfilecontainscommands whichyouwishtodoeachtimeyoulogintotheUNIXsystem.My.loginfilelookssomethinglike: setignoreeof setmail=(/usr/spool/mail/bill) echo"${prompt}users";users aliasts\ ´ setnoglob;eval` tset−s−mdialup:c100rv4pna−mplugboard:?hp2621nl*` ´ ; ts;sttyintr↑Ckill↑Ucrt settime=15history=10 msgs−f if(−e$mail)then echo"${prompt}mail" mail endif ThisfilecontainsseveralcommandstobeexecutedbyUNIXeachtimeIlogin.Thefirstisa setcommandwhichisinterpreteddirectlybytheshell.Itsetstheshellvariableignoreeofwhich causestheshelltonotlogmeoffifIhit↑D.Rather,Iusethelogoutcommandtologoffofthe system.Bysettingthemailvariable,Iasktheshelltowatchforincomingmailtome.Every5 minutestheshelllooksforthisfileandtellsmeifmoremailhasarrivedthere.Analternativeto thisistoputthecommand biffy inplaceofthisset;thiswillcausemetobenotifiedimmediatelywhenmailarrives,andtobe shownthefirstfewlinesofthenewmessage. NextIsettheshellvariable‘time’to‘15’causingtheshelltoautomaticallyprintoutstatisticslinesforcommandswhichexecuteforatleast15secondsofCPUtime.Thevariable‘history’ issetto10indicatingthatIwanttheshelltorememberthelast10commandsItypeinitshistorylist,(describedlater). Icreateanalias‘‘ts’’whichexecutesatset(1)commandsettingupthemodesoftheterminal.TheparameterstotsetindicatethekindsofterminalwhichIusuallyusewhennotona hardwiredport.Ithenexecute‘‘ts’’andalsousethesttycommandtochangetheinterruptcharacterto↑Candthelinekillcharacterto↑U. Ithenrunthe‘msgs’program,whichprovidesmewithanysystemmessageswhichIhave notseenbefore;the‘−f’optionherepreventsitfromtellingmeanythingiftherearenonewmessages.Finally,ifmymailboxfileexists,thenIrunthe‘mail’programtoprocessmymail. Whenthe‘mail’and‘msgs’programsfinish,theshellwillfinishprocessingmy.loginfileand beginreadingcommandsfromtheterminal,promptingforeachwith‘%’.WhenIlogoff(bygivingthelogoutcommand)theshellwillprint‘logout’andexecutecommandsfromthefile‘.logout’ ifitexistsinmyhomedirectory.AfterthattheshellwillterminateandUNIXwilllogmeoffthe system.Ifthesystemisnotgoingdown,Iwillreceiveanewloginmessage.Inanycase,afterthe ‘logout’messagetheshelliscommittedtoterminatingandwilltakenofurtherinputfrommyterminal.

-11-2.2.Shellvariables Theshellmaintainsasetofvariables.Wesawabovethevariableshistoryandtimewhich hadvalues‘10’and‘15’.Infact,eachshellvariablehasasvalueanarrayofzeroormorestrings. Shellvariablesmaybeassignedvaluesbythesetcommand.Ithasseveralforms,themostuseful ofwhichwasgivenaboveandis setname=value Shellvariablesmaybeusedtostorevalueswhicharetobeusedincommandslaterthrough asubstitutionmechanism.Theshellvariablesmostcommonlyreferencedare,however,those whichtheshellitselfrefersto.Bychangingthevaluesofthesevariablesonecandirectlyaffect thebehavioroftheshell. Oneofthemostimportantvariablesisthevariablepath.Thisvariablecontainsasequence ofdirectorynameswheretheshellsearchesforcommands.Thesetcommandwithnoarguments showsthevalueofallvariablescurrentlydefined(weusuallysayset)intheshell.Thedefault valueforpathwillbeshownbysettobe %set argv() cwd/usr/bill home/usr/bill path(./usr/ucb/bin/usr/bin) prompt% shell/bin/csh status0 termc100rv4pna userbill % Thisoutputindicatesthatthevariablepathpointstothecurrentdirectory‘.’andthen ‘/usr/ucb’,‘/bin’and‘/usr/bin’.Commandswhichyoumaywritemightbein‘.’(usuallyoneof yourdirectories).CommandsdevelopedatBerkeley,livein‘/usr/ucb’whilecommandsdeveloped atBellLaboratorieslivein‘/bin’and‘/usr/bin’. Anumberoflocallydevelopedprogramsonthesystemliveinthedirectory‘/usr/local’.If wewishthatallshellswhichweinvoketohaveaccesstothesenewprogramswecanplacethe command setpath=(./usr/ucb/bin/usr/bin/usr/local) inourfile.cshrcinourhomedirectory.Trydoingthisandthenloggingoutandbackinanddo set againtoseethatthevalueassignedtopathhaschanged. Onethingyoushouldbeawareofisthattheshellexamineseachdirectorywhichyouinsert intoyourpathanddetermineswhichcommandsarecontainedthere.Exceptforthecurrent directory‘.’,whichtheshelltreatsspecially,thismeansthatifcommandsareaddedtoadirectory inyoursearchpathafteryouhavestartedtheshell,theywillnotnecessarilybefoundbythe shell.Ifyouwishtouseacommandwhichhasbeenaddedinthisway,youshouldgivethecommand rehash totheshell,whichwillcauseittorecomputeitsinternaltableofcommandlocations,sothatit willfindthenewlyaddedcommand.Sincetheshellhastolookinthecurrentdirectory‘.’on eachcommand,placingitattheendofthepathspecificationusuallyworksequivalentlyand reducesoverhead.

-12-Otherusefulbuiltinvariablesarethevariablehomewhichshowsyourhomedirectory,cwd whichcontainsyourcurrentworkingdirectory,thevariableignoreeofwhichcanbesetinyour .loginfiletotelltheshellnottoexitwhenitreceivesanend-of-filefromaterminal(asdescribed above).Thevariable‘ignoreeof’isoneofseveralvariableswhichtheshelldoesnotcareaboutthe valueof,onlywhethertheyaresetorunset.Thustosetthisvariableyousimplydo setignoreeof andtounsetitdo unsetignoreeof Thesegivethevariable‘ignoreeof’novalue,butnoneisdesiredorrequired. Finally,someotherbuilt-inshellvariablesofusearethevariablesnoclobberandmail.The metasyntax >filename whichredirectsthestandardoutputofacommandwilloverwriteanddestroythepreviouscontentsofthenamedfile.Inthiswayyoumayaccidentallyoverwriteafilewhichisvaluable.Ifyou wouldpreferthattheshellnotoverwritefilesinthiswayyoucan setnoclobber inyour.loginfile.Thentryingtodo date>now wouldcauseadiagnosticif‘now’existedalready.Youcouldtype date>!now ifyoureallywantedtooverwritethecontentsof‘now’.The‘>!’isaspecialmetasyntaxindicatingthatclobberingthefileisok.† 2.3.Theshell’shistorylist Theshellcanmaintainahistorylistintowhichitplacesthewordsofpreviouscommands. Itispossibletouseanotationtoreusecommandsorwordsfromcommandsinformingnewcommands.Thismechanismcanbeusedtorepeatpreviouscommandsortocorrectminortyping mistakesincommands. Thefollowingfiguregivesasamplesessioninvolvingtypicalusageofthehistorymechanism oftheshell.InthisexamplewehaveaverysimpleCprogramwhichhasabug(ortwo)initin thefile‘bug.c’,whichwe‘cat’outonourterminal.WethentrytoruntheCcompileronit, referringtothefileagainas‘!$’,meaningthelastargumenttothepreviouscommand.Herethe ‘!’isthehistorymechanisminvocationmetacharacter,andthe‘$’standsforthelastargument,by analogyto‘$’intheeditorwhichstandsfortheendoftheline.Theshellechoedthecommand, asitwouldhavebeentypedwithoutuseofthehistorymechanism,andthenexecutedit.The compilationyieldederrordiagnosticssowenowruntheeditoronthefileweweretryingtocompile,fixthebug,andruntheCcompileragain,thistimereferringtothiscommandsimplyas‘!c’, whichrepeatsthelastcommandwhichstartedwiththeletter‘c’.Iftherewereothercommands startingwith‘c’donerecentlywecouldhavesaid‘!cc’oreven‘!cc:p’whichwouldhaveprinted thelastcommandstartingwith‘cc’withoutexecutingit. Afterthisrecompilation,werantheresulting‘a.out’file,andthennotingthattherestillwas abug,rantheeditoragain.AfterfixingtheprogramwerantheCcompileragain,buttacked ontothecommandanextra‘−obug’tellingthecompilertoplacetheresultantbinaryinthefile ‘bug’ratherthan‘a.out’.Ingeneral,thehistorymechanismsmaybeusedanywhereintheformationofnewcommandsandothercharactersmaybeplacedbeforeandafterthesubstituted †Thespacebetweenthe‘!’andtheword‘now’iscriticalhere,as‘!now’wouldbeaninvocationofthe historymechanism,andhaveatotallydifferenteffect.

-13- %catbug.c main() { printf("hello); } %cc!$ ccbug.c "bug.c",line4:newlineinstringorcharconstant "bug.c",line5:syntaxerror %ed!$ edbug.c 29 4s/);/"&/p printf("hello"); w 30 q %!c ccbug.c %a.out hello%!e edbug.c 30 4s/lo/lo\\n/p printf("hello\n"); w 32 q %!c−obug ccbug.c−obug %sizea.outbug a.out:2784+364+1028=4176b=0x1050b bug:2784+364+1028=4176b=0x1050b %ls−l!* ls−la.outbug −rwxr−xr−x1bill3932Dec1909:41a.out −rwxr−xr−x1bill3932Dec1909:42bug %bug hello %numbug.c|spp spp:Commandnotfound. %↑spp↑ssp numbug.c|ssp 1main() 3{ 4printf("hello\n"); 5} %!!|lpr numbug.c|ssp|lpr % commands.

-14-Wethenranthe‘size’commandtoseehowlargethebinaryprogramimageswehavecre-atedwere,andthenan‘ls−l’commandwiththesameargumentlist,denotingtheargumentlist ‘*’.Finallywerantheprogram‘bug’toseethatitsoutputisindeedcorrect. Tomakeanumberedlistingoftheprogramweranthe‘num’commandonthefile‘bug.c’. Inordertocompressoutblanklinesintheoutputof‘num’werantheoutputthroughthefilter ‘ssp’,butmisspelleditasspp.Tocorrectthisweusedashellsubstitute,placingtheoldtextand newtextbetween‘↑’characters.Thisissimilartothesubstitutecommandintheeditor.Finally, werepeatedthesamecommandwith‘!!’,butsentitsoutputtothelineprinter. Thereareothermechanismsavailableforrepeatingcommands.Thehistorycommandprints outanumberofpreviouscommandswithnumbersbywhichtheycanbereferenced.Thereisa waytorefertoapreviouscommandbysearchingforastringwhichappearedinit,andthereare other,lessuseful,waystoselectargumentstoincludeinanewcommand.Acompletedescription ofallthesemechanismsisgivenintheCshellmanualpagesintheUNIXProgrammersManual. 2.4.Aliases Theshellhasanaliasmechanismwhichcanbeusedtomaketransformationsoninputcommands.Thismechanismcanbeusedtosimplifythecommandsyoutype,tosupplydefaultargumentstocommands,ortoperformtransformationsoncommandsandtheirarguments.Thealias facilityissimilartoamacrofacility.Someofthefeaturesobtainedbyaliasingcanbeobtained alsousingshellcommandfiles,butthesetakeplaceinanotherinstanceoftheshellandcannot directlyaffectthecurrentshellsenvironmentorinvolvecommandssuchascdwhichmustbedone inthecurrentshell. Asanexample,supposethatthereisanewversionofthemailprogramonthesystem called‘newmail’youwishtouse,ratherthanthestandardmailprogramwhichiscalled‘mail’.If youplacetheshellcommand aliasmailnewmail inyour.cshrcfile,theshellwilltransformaninputlineoftheform mailbill intoacallon‘newmail’.Moregenerally,supposewewishthecommand‘ls’toalwaysshowsizes offiles,thatistoalwaysdo‘−s’.Wecando aliaslsls−s oreven aliasdirls−s creatinganewcommandsyntax‘dir’whichdoesan‘ls−s’.Ifwesay dir˜ bill thentheshellwilltranslatethisto ls−s/mnt/bill Thusthealiasmechanismcanbeusedtoprovideshortnamesforcommands,toprovide defaultarguments,andtodefinenewshortcommandsintermsofothercommands.Itisalsopossibletodefinealiaseswhichcontainmultiplecommandsorpipelines,showingwheretheargumentstotheoriginalcommandaretobesubstitutedusingthefacilitiesofthehistorymechanism. Thusthedefinition aliascd´ cd\!*;ls´ woulddoanlscommandaftereachchangedirectorycdcommand.Weenclosedtheentirealias definitionin‘´ ’characterstopreventmostsubstitutionsfromoccurringandthecharacter‘;’from beingrecognizedasametacharacter.The‘!’hereisescapedwitha‘\’topreventitfrombeing -15-interpretedwhenthealiascommandistypedin.The‘\!*’heresubstitutestheentireargument listtothepre-aliasingcdcommand,withoutgivinganerroriftherewerenoarguments.The‘;’ separatingcommandsisusedheretoindicatethatonecommandistobedoneandthenthenext. Similarlythedefinition aliaswhois´ grep\!↑/etc/passwd´ definesacommandwhichlooksupitsfirstargumentinthepasswordfile. Warning:Theshellcurrentlyreadsthe.cshrcfileeachtimeitstartsup.Ifyouplacea largenumberofcommandsthere,shellswilltendtostartslowly.Amechanismforsavingthe shellenvironmentafterreadingthe.cshrcfileandquicklyrestoringitisunderdevelopment,but fornowyoushouldtrytolimitthenumberofaliasesyouhavetoareasonablenumber...10or15 isreasonable,50or60willcauseanoticeabledelayinstartingupshells,andmakethesystem seemsluggishwhenyouexecutecommandsfromwithintheeditorandotherprograms. 2.5.Moreredirection;>>and>& Thereareafewmorenotationsusefultotheterminaluserwhichhavenotbeenintroduced yet. Inadditiontothestandardoutput,commandsalsohaveadiagnosticoutputwhichisnormallydirectedtotheterminalevenwhenthestandardoutputisredirectedtoafileorapipe.It isoccasionallydesirabletodirectthediagnosticoutputalongwiththestandardoutput.For instanceifyouwanttoredirecttheoutputofalongrunningcommandintoafileandwishtohave arecordofanyerrordiagnosticitproducesyoucando command>&file The‘>&’heretellstheshelltorouteboththediagnosticoutputandthestandardoutputinto ‘file’.Similarlyyoucangivethecommand command|&lpr toroutebothstandardanddiagnosticoutputthroughthepipetothelineprinterdaemonlpr.# Finally,itispossibletousetheform command>>file toplaceoutputattheendofanexistingfile.† 2.6.Jobs;Background,Foreground,orSuspended Whenoneormorecommandsaretypedtogetherasapipelineorasasequenceofcommands separatedbysemicolons,asinglejobiscreatedbytheshellconsistingofthesecommandstogether asaunit.Singlecommandswithoutpipesorsemicolonscreatethesimplestjobs.Usually,every linetypedtotheshellcreatesajob.Somelinesthatcreatejobs(oneperline)are #Acommandform command>&!file exists,andisusedwhennoclobberissetandfilealreadyexists. †Ifnoclobberisset,thenanerrorwillresultiffiledoesnotexist,otherwisetheshellwillcreatefileifit doesn’texist.Aform command>>!file makesitnotbeanerrorforfiletonotexistwhennoclobberisset.

-16-sort<data ls−s|sort−n|head−5 mailharold Ifthemetacharacter‘&’istypedattheendofthecommands,thenthejobisstartedasa backgroundjob.Thismeansthattheshelldoesnotwaitforittocompletebutimmediately promptsandisreadyforanothercommand.Thejobrunsinthebackgroundatthesametime thatnormaljobs,calledforegroundjobs,continuetobereadandexecutedbytheshelloneata time.Thus du>usage& wouldruntheduprogram,whichreportsonthediskusageofyourworkingdirectory(aswellas anydirectoriesbelowit),puttheoutputintothefile‘usage’andreturnimmediatelywitha promptforthenextcommandwithoutoutwaitingfordutofinish.Theduprogramwouldcontinueexecutinginthebackgrounduntilitfinished,eventhoughyoucantypeandexecutemore commandsinthemeantime.Whenabackgroundjobterminates,amessageistypedbytheshell justbeforethenextprompttellingyouthatthejobhascompleted.Inthefollowingexamplethe dujobfinishessometimeduringtheexecutionofthemailcommandanditscompletionisreported justbeforethepromptafterthemailjobisfinished. %du>usage& [1]503 %mailbill Howdoyouknowwhenabackgroundjobisfinished? EOT [1]−Donedu>usage % Ifthejobdidnotterminatenormallythe‘Done’messagemightsaysomethingelselike‘Killed’.If youwanttheterminationsofbackgroundjobstobereportedatthetimetheyoccur(possibly interruptingtheoutputofotherforegroundjobs),youcansetthenotifyvariable.Intheprevious examplethiswouldmeanthatthe‘Done’messagemighthavecomerightinthemiddleofthe messagetoBill.BackgroundjobsareunaffectedbyanysignalsfromthekeyboardliketheSTOP, INTERRUPT,orQUITsignalsmentionedearlier. Jobsarerecordedinatableinsidetheshelluntiltheyterminate.Inthistable,theshell remembersthecommandnames,argumentsandtheprocessnumbersofallcommandsinthejob aswellastheworkingdirectorywherethejobwasstarted.Eachjobinthetableiseitherrunning intheforegroundwiththeshellwaitingforittoterminate,runninginthebackground,orsuspended.Onlyonejobcanberunningintheforegroundatonetime,butseveraljobscanbesuspendedorrunninginthebackgroundatonce.Aseachjobisstarted,itisassignedasmallidentifyingnumbercalledthejobnumberwhichcanbeusedlatertorefertothejobinthecommands describedbelow.Jobnumbersremainthesameuntilthejobterminatesandthenarere-used. Whenajobisstartedinthebackgoundusing‘&’,itsnumber,aswellastheprocessnumbersofallits(toplevel)commands,istypedbytheshellbeforepromptingyouforanothercommand.Forexample, %ls−s|sort−n>usage& [2]20342035 % runsthe‘ls’programwiththe‘−s’options,pipesthisoutputintothe‘sort’programwiththe ‘−n’optionwhichputsitsoutputintothefile‘usage’.Sincethe‘&’wasattheendoftheline, thesetwoprogramswerestartedtogetherasabackgroundjob.Afterstartingthejob,theshell printsthejobnumberinbrackets(2inthiscase)followedbytheprocessnumberofeachprogram startedinthejob.Thentheshellimmediatespromptsforanewcommand,leavingthejobrunningsimultaneously.

-17-Asmentionedinsection1.8,foregroundjobsbecomesuspendedbytyping↑Zwhichsendsa STOPsignaltothecurrentlyrunningforegroundjob.Abackgroundjobcanbecomesuspendedby usingthestopcommanddescribedbelow.Whenjobsaresuspendedtheymerelystopanyfurther progressuntilstartedagain,eitherintheforegroundorthebackgound.Theshellnoticeswhena jobbecomesstoppedandreportsthisfact,muchlikeitreportstheterminationofbackground jobs.Forforegroundjobsthislookslike %du>usage ↑Z Stopped % ‘Stopped’messageistypedbytheshellwhenitnoticesthattheduprogramstopped.Forbackgroundjobs,usingthestopcommand,itis %sortusage& [1]2345 %stop%1 [1]+Stopped(signal)sortusage % Suspendingforegroundjobscanbeveryusefulwhenyouneedtotemporarilychangewhatyouare doing(executeothercommands)andthenreturntothesuspendedjob.Also,foregroundjobscan besuspendedandthencontinuedasbackgroundjobsusingthebgcommand,allowingyoutocontinueotherworkandstopwaitingfortheforegroundjobtofinish.Thus %du>usage ↑Z Stopped %bg [1]du>usage& % starts‘du’intheforeground,stopsitbeforeitfinishes,thencontinuesitinthebackgroundallowingmoreforegroundcommandstobeexecuted.Thisisespeciallyhelpfulwhenaforegroundjob endsuptakinglongerthanyouexpectedandyouwishyouhadstarteditinthebackgoundinthe beginning. Alljobcontrolcommandscantakeanargumentthatidentifiesaparticularjob.Alljob nameargumentsbeginwiththecharacter‘%’,sincesomeofthejobcontrolcommandsalsoaccept processnumbers(printedbythepscommand.)Thedefaultjob(whennoargumentisgiven)is calledthecurrentjobandisidentifiedbya‘+’intheoutputofthejobscommand,whichshows youwhichjobsyouhave.Whenonlyonejobisstoppedorrunninginthebackground(theusual case)itisalwaysthecurrentjobthusnoargumentisneeded.Ifajobisstoppedwhilerunningin theforegrounditbecomesthecurrentjobandtheexistingcurrentjobbecomesthepreviousjob− identifiedbya‘−’intheoutputofjobs.Whenthecurrentjobterminates,thepreviousjob becomesthecurrentjob.Whengiven,theargumentiseither‘%−’(indicatingthepreviousjob); ‘%#’,where#isthejobnumber;‘%pref’whereprefissomeuniqueprefixofthecommandname andargumentsofoneofthejobs;or‘%?’followedbysomestringfoundinonlyoneofthejobs. Thejobscommandtypesthetableofjobs,givingthejobnumber,commandsandstatus (‘Stopped’or‘Running’)ofeachbackgoundorsuspendedjob.Withthe‘−l’optiontheprocess numbersarealsotyped.

-18- %du>usage& [1]3398 %ls−s|sort−n>myfile& [2]3405 %mailbill ↑Z Stopped %jobs [1]−Runningdu>usage [2]Runningls−s|sort−n>myfile [3]+Stoppedmailbill %fg%ls ls−s|sort−n>myfile %moremyfile Thefgcommandrunsasuspendedorbackgroundjobintheforeground.Itisusedto restartapreviouslysuspendedjoborchangeabackgroundjobtorunintheforeground(allowing signalsorinputfromtheterminal).Intheaboveexampleweusedfgtochangethe‘ls’jobfrom thebackgroundtotheforegroundsincewewantedtowaitforittofinishbeforelookingatitsoutputfile.Thebgcommandrunsasuspendedjobinthebackground.ItisusuallyusedafterstoppingthecurrentlyrunningforegroundjobwiththeSTOPsignal.ThecombinationoftheSTOPsignalandthebgcommandchangesaforegroundjobintoabackgroundjob.Thestopcommandsuspendsabackgroundjob. Thekillcommandterminatesabackgroundorsuspendedjobimmediately.Inadditionto jobs,itmaybegivenprocessnumbersasarguments,asprintedbyps.Thus,intheexample above,therunningducommandcouldhavebeenterminatedbythecommand %kill%1 [1]Terminateddu>usage % Thenotifycommand(notthevariablementionedearlier)indicatesthattheterminationofa specificjobshouldbereportedatthetimeitfinishesinsteadofwaitingforthenextprompt. Ifajobrunninginthebackgroundtriestoreadinputfromtheterminalitisautomatically stopped.Whensuchajobisthenrunintheforeground,inputcanbegiventothejob.If desired,thejobcanberuninthebackgroundagainuntilitrequestsinputagain.Thisisillustratedinthefollowingsequencewherethe‘s’commandinthetexteditormighttakealongtime. %edbigfile 120000 1,$s/thisword/thatword/ ↑Z Stopped %bg [1]edbigfile& % ...someforegroundcommands [1]Stopped(ttyinput)edbigfile %fg edbigfile w 120000 q % Soafterthe‘s’commandwasissued,the‘ed’jobwasstoppedwith↑Zandthenputinthe -19-backgroundusingbg.Sometimelaterwhenthe‘s’commandwasfinished,edtriedtoread anothercommandandwasstoppedbecausejobsinthebackgoundcannotreadfromtheterminal. Thefgcommandreturnedthe‘ed’jobtotheforegroundwhereitcouldonceagainacceptcommandsfromtheterminal. Thecommand sttytostop causesallbackgroundjobsrunonyourterminaltostopwhentheyareabouttowriteoutputto theterminal.Thispreventsmessagesfrombackgroundjobsfrominterruptingforegroundjoboutputandallowsyoutorunajobinthebackgroundwithoutlosingterminaloutput.Italsocanbe usedforinteractiveprogramsthatsometimeshavelongperiodswithoutinteraction.Thuseach timeitoutputsapromptformoreinputitwillstopbeforetheprompt.Itcanthenberuninthe foregroundusingfg,moreinputcanbegivenand,ifnecessarystoppedandreturnedtothebackground.Thissttycommandmightbeagoodthingtoputinyour.loginfileifyoudonotlikeoutputfrombackgroundjobsinterruptingyourwork.Italsocanreducetheneedforredirectingthe outputofbackgroundjobsiftheoutputisnotverybig: %sttytostop %wchugefile& [1]10387 %edtext ...sometimelater q [1]Stopped(ttyoutput)wchugefile %fgwc wchugefile 1337130123302577 %stty−tostop Thusaftersometimethe‘wc’command,whichcountsthelines,wordsandcharactersinafile, hadonelineofoutput.Whenittriedtowritethistotheterminalitstopped.Byrestartingitin theforegroundweallowedittowriteontheterminalexactlywhenwewerereadytolookatits output.Programswhichattempttochangethemodeoftheterminalwillalsoblock,whetheror nottostopisset,whentheyarenotintheforeground,asitwouldbeveryunpleasanttohavea backgroundjobchangethestateoftheterminal. Sincethejobscommandonlyprintsjobsstartedinthecurrentlyexecutingshell,itknows nothingaboutbackgroundjobsstartedinotherloginsessionsorwithinshellfiles.Thepscanbe usedinthiscasetofindoutaboutbackgroundjobsnotstartedinthecurrentshell. 2.7.WorkingDirectories Asmentionedinsection1.6,theshellisalwaysinaparticularworkingdirectory.The ‘changedirectory’commandchdir(itsshortformcdmayalsobeused)changestheworkingdirectoryoftheshell,thatis,changesthedirectoryyouarelocatedin. Itisusefultomakeadirectoryforeachprojectyouwishtoworkonandtoplaceallfiles relatedtothatprojectinthatdirectory.The‘makedirectory’command,mkdir,createsanew directory.Thepwd(‘printworkingdirectory’)commandreportstheabsolutepathnameofthe workingdirectoryoftheshell,thatis,thedirectoryyouarelocatedin.Thusintheexample below:

-20- %pwd /usr/bill %mkdirnewpaper %chdirnewpaper %pwd /usr/bill/newpaper % theuserhascreatedandmovedtothedirectorynewpaper.where,forexample,hemightplacea groupofrelatedfiles. Nomatterwhereyouhavemovedtoinadirectoryhierarchy,youcanreturntoyour‘home’ logindirectorybydoingjust cd withnoarguments.Thename‘..’alwaysmeansthedirectoryabovethecurrentoneinthehierarchy,thus cd.. changestheshell’sworkingdirectorytotheonedirectlyabovethecurrentone.Thename‘..’can beusedinanypathname,thus, cd../programs meanschangetothedirectory‘programs’containedinthedirectoryabovethecurrentone.Ifyou haveseveraldirectoriesfordifferentprojectsunder,say,yourhomedirectory,thisshorthandnotationpermitsyoutoswitcheasilybetweenthem. Theshellalwaysremembersthepathnameofitscurrentworkingdirectoryinthevariable cwd.Theshellcanalsoberequestedtorememberthepreviousdirectorywhenyouchangetoa newworkingdirectory.Ifthe‘pushdirectory’commandpushdisusedinplaceofthecdcommand,theshellsavesthenameofthecurrentworkingdirectoryonadirectorystackbeforechangingtothenewone.Youcanseethislistatanytimebytypingthe‘directories’commanddirs. %pushdnewpaper/references ˜ /newpaper/references˜ %pushd/usr/lib/tmac /usr/lib/tmac˜ /newpaper/references˜ %dirs /usr/lib/tmac˜ /newpaper/references˜ %popd ˜ /newpaper/references˜ %popd ˜ % Thelistisprintedinahorizontalline,readinglefttoright,withatilde(˜ )asshorthandforyour homedirectory—inthiscase‘/usr/bill’.Thedirectorystackisprintedwheneverthereismore thanoneentryonitanditchanges.Itisalsoprintedbyadirscommand.Dirsisusuallyfaster andmoreinformativethanpwdsinceitshowsthecurrentworkingdirectoryaswellasanyother directoriesrememberedinthestack. Thepushdcommandwithnoargumentalternatesthecurrentdirectorywiththefirstdirectoryinthelist.The‘popdirectory’popdcommandwithoutanargumentreturnsyoutothedirectoryyouwereinpriortothecurrentone,discardingthepreviouscurrentdirectoryfromthestack (forgettingit).Typingpopdseveraltimesinaseriestakesyoubackwardthroughthedirectories youhadbeenin(changedto)bypushdcommand.Thereareotheroptionstopushdandpopdto manipulatethecontentsofthedirectorystackandtochangetodirectoriesnotatthetopofthe stack;seethecshmanualpagefordetails.

-21-Sincetheshellrememberstheworkingdirectoryinwhicheachjobwasstarted,itwarnsyou whenyoumightbeconfusedbyrestartingajobintheforegroundwhichhasadifferentworking directorythanthecurrentworkingdirectoryoftheshell.Thusifyoustartabackgroundjob, thenchangetheshell’sworkingdirectoryandthencausethebackgroundjobtorunintheforeground,theshellwarnsyouthattheworkingdirectoryofthecurrentlyrunningforegroundjobis differentfromthatoftheshell. %dirs−l /mnt/bill %cdmyproject %dirs ˜ /myproject %edprog.c 1143 ↑Z Stopped %cd.. %ls myproject textfile %fg edprog.c(wd:˜ /myproject) Thiswaytheshellwarnsyouwhenthereisanimpliedchangeofworkingdirectory,eventhough nocdcommandwasissued.Intheaboveexamplethe‘ed’jobwasstillin‘/mnt/bill/project’ eventhoughtheshellhadchangedto‘/mnt/bill’.Asimilarwarningisgivenwhensuchaforegroundjobterminatesorissuspended(usingtheSTOPsignal)sincethereturntotheshellagain impliesachangeofworkingdirectory. %fg edprog.c(wd:˜ /myproject) ...aftersomeediting q (wdnow:˜ ) % Thesemessagesaresometimesconfusingifyouuseprogramsthatchangetheirownworkingdirectories,sincetheshellonlyrememberswhichdirectoryajobisstartedin,andassumesitstays there.The‘−l’optionofjobswilltypetheworkingdirectoryofsuspendedorbackgroundjobs whenitisdifferentfromthecurrentworkingdirectoryoftheshell. 2.8.Usefulbuilt-incommands Wenowgiveafewoftheusefulbuilt-incommandsoftheshelldescribinghowtheyareused. Thealiascommanddescribedaboveisusedtoassignnewaliasesandtoshowtheexisting aliases.Withnoargumentsitprintsthecurrentaliases.Itmayalsobegivenonlyoneargument suchas aliasls toshowthecurrentaliasfor,e.g.,‘ls’. Theechocommandprintsitsarguments.Itisoftenusedinshellscriptsorasaninteractive commandtoseewhatfilenameexpansionswillproduce. Thehistorycommandwillshowthecontentsofthehistorylist.Thenumbersgivenwiththe historyeventscanbeusedtoreferencepreviouseventswhicharedifficulttoreferenceusingthe contextualmechanismsintroducedabove.Thereisalsoashellvariablecalledprompt.Byplacing a‘!’characterinitsvaluetheshellwilltheresubstitutethenumberofthecurrentcommandin -22-thehistorylist.Youcanusethisnumbertorefertothiscommandinahistorysubstitution. Thusyoucould setprompt=´ \!%´ Notethatthe‘!’characterhadtobeescapedhereevenwithin‘´ ’characters. Thelimitcommandisusedtorestrictuseofresources.Withnoargumentsitprintsthe currentlimitations: cputimeunlimited filesizeunlimited datasize5616kbytes stacksize512kbytes coredumpsizeunlimited Limitscanbeset,e.g.: limitcoredumpsize128k Mostreasonableunitsabbreviationswillwork;seethecshmanualpageformoredetails. Thelogoutcommandcanbeusedtoterminatealoginshellwhichhasignoreeofset. Therehashcommandcausestheshelltorecomputeatableofwherecommandsarelocated. Thisisnecessaryifyouaddacommandtoadirectoryinthecurrentshell’ssearchpathandwish theshelltofindit,sinceotherwisethehashingalgorithmmaytelltheshellthatthecommand wasn’tinthatdirectorywhenthehashtablewascomputed. Therepeatcommandcanbeusedtorepeatacommandseveraltimes.Thustomake5 copiesofthefileoneinthefilefiveyoucoulddo repeat5catone>>five Thesetenvcommandcanbeusedtosetvariablesintheenvironment.Thus setenvTERMadm3a willsetthevalueoftheenvironmentvariableTERMto‘adm3a’.Auserprogramprintenvexists whichwillprintouttheenvironment.Itmightthenshow: %printenv HOME=/usr/bill SHELL=/bin/csh PATH=:/usr/ucb:/bin:/usr/bin:/usr/local TERM=adm3a USER=bill % Thesourcecommandcanbeusedtoforcethecurrentshelltoreadcommandsfromafile. Thus source.cshrc canbeusedaftereditinginachangetothe.cshrcfilewhichyouwishtotakeeffectbeforethe nexttimeyoulogin. ThetimecommandcanbeusedtocauseacommandtobetimednomatterhowmuchCPU timeittakes.Thus -23- %timecp/etc/rc/usr/bill/rc 0.0u0.1s0:018%2+1k3+2io1pf+0w %timewc/etc/rc/usr/bill/rc 521781347/etc/rc 521781347/usr/bill/rc 1043562694total 0.1u0.1s0:0013%3+3k5+3io7pf+0w % indicatesthatthecpcommandusedanegligibleamountofusertime(u)andabout1/10thofa systemtime(s);theelapsedtimewas1second(0:01),therewasanaveragememoryusageof2k bytesofprogramspaceand1kbytesofdataspaceoverthecputimeinvolved(2+1k);theprogramdidthreediskreadsandtwodiskwrites(3+2io),andtookonepagefaultandwasnot swapped(1pf+0w).Thewordcountcommandwcontheotherhandused0.1secondsofuser timeand0.1secondsofsystemtimeinlessthanasecondofelapsedtime.Thepercentage‘13%’ indicatesthatovertheperiodwhenitwasactivethecommand‘wc’usedanaverageof13percent oftheavailableCPUcyclesofthemachine. Theunaliasandunsetcommandscanbeusedtoremovealiasesandvariabledefinitionsfrom theshell,andunsetenvremovesvariablesfromtheenvironment. 2.9.Whatelse? Thisconcludesthebasicdiscussionoftheshellforterminalusers.Therearemorefeatures oftheshelltobediscussedhere,andallfeaturesoftheshellarediscussedinitsmanualpages. Oneusefulfeaturewhichisdiscussedlateristheforeachbuilt-incommandwhichcanbeusedto runthesamecommandsequencewithanumberofdifferentarguments. IfyouintendtouseUNIXalotyouyoushouldlookthroughtherestofthisdocumentand theshellmanualpagestobecomefamiliarwiththeotherfacilitieswhichareavailabletoyou.

-24-3.Shellcontrolstructuresandcommandscripts 3.1.Introduction Itispossibletoplacecommandsinfilesandtocauseshellstobeinvokedtoreadandexecutecommandsfromthesefiles,whicharecalledshellscripts.Weheredetailthosefeaturesof theshellusefultothewritersofsuchscripts. 3.2.Make Itisimportanttofirstnotewhatshellscriptsarenotusefulfor.Thereisaprogramcalled makewhichisveryusefulformaintainingagroupofrelatedfilesorperformingsetsofoperations onrelatedfiles.Forinstancealargeprogramconsistingofoneormorefilescanhaveitsdependenciesdescribedinamakefilewhichcontainsdefinitionsofthecommandsusedtocreatethese differentfileswhenchangesoccur.Definitionsofthemeansforprintinglistings,cleaningupthe directoryinwhichthefilesreside,andinstallingtheresultantprogramsareeasily,andmost appropriatelyplacedinthismakefile.Thisformatissuperiorandpreferabletomaintaininga groupofshellprocedurestomaintainthesefiles. Similarlywhenworkingonadocumentamakefilemaybecreatedwhichdefineshowdifferentversionsofthedocumentaretobecreatedandwhichoptionsofnroffortroffareappropriate. 3.3.Invocationandtheargvvariable Acshcommandscriptmaybeinterpretedbysaying %cshscript... wherescriptisthenameofthefilecontainingagroupofcshcommandsand‘...’isreplacedbya sequenceofarguments.Theshellplacestheseargumentsinthevariableargvandthenbeginsto readcommandsfromthescript.Theseparametersarethenavailablethroughthesamemechanismswhichareusedtoreferenceanyothershellvariables. Ifyoumakethefile‘script’executablebydoing chmod755script andplaceashellcommentatthebeginningoftheshellscript(i.e.beginthefilewitha‘#’character)thena‘/bin/csh’willautomaticallybeinvokedtoexecute‘script’whenyoutype script Ifthefiledoesnotbeginwitha‘#’thenthestandardshell‘/bin/sh’willbeusedtoexecuteit. Thisallowsyoutoconvertyouroldershellscriptstousecshatyourconvenience. 3.4.Variablesubstitution Aftereachinputlineisbrokenintowordsandhistorysubstitutionsaredoneonit,theinput lineisparsedintodistinctcommands.Beforeeachcommandisexecutedamechanismknowas variablesubstitutionisdoneonthesewords.Keyedbythecharacter‘$’thissubstitutionreplaces thenamesofvariablesbytheirvalues.Thus echo$argv whenplacedinacommandscriptwouldcausethecurrentvalueofthevariableargvtobeechoed totheoutputoftheshellscript.Itisanerrorforargvtobeunsetatthispoint. Anumberofnotationsareprovidedforaccessingcomponentsandattributesofvariables. Thenotation $?name expandsto‘1’ifnameissetorto‘0’ifnameisnotset.Itisthefundamentalmechanismusedfor checkingwhetherparticularvariableshavebeenassignedvalues.Allotherformsofreferenceto -25-undefinedvariablescauseerrors. Thenotation $#name expandstothenumberofelementsinthevariablename.Thus %setargv=(abc) %echo$?argv 1 %echo$#argv 3 %unsetargv %echo$?argv 0 %echo$argv Undefinedvariable:argv. % Itisalsopossibletoaccessthecomponentsofavariablewhichhasseveralvalues.Thus $argv[1] givesthefirstcomponentofargvorintheexampleabove‘a’.Similarly $argv[$#argv] wouldgive‘c’,and $argv[1−2] wouldgive‘ab’.Othernotationsusefulinshellscriptsare $n wherenisanintegerasashorthandfor $argv[n] thenthparameterand $* whichisashorthandfor $argv Theform $$ expandstotheprocessnumberofthecurrentshell.Sincethisprocessnumberisuniqueinthe systemitcanbeusedingenerationofuniquetemporaryfilenames.Theform $< isquitespecialandisreplacedbythenextlineofinputreadfromtheshell’sstandardinput(not thescriptitisreading).Thisisusefulforwritingshellscriptsthatareinteractive,readingcommandsfromtheterminal,orevenwritingashellscriptthatactsasafilter,readinglinesfromits inputfile.Thusthesequence echo’yesorno?\c’ seta=($<) wouldwriteouttheprompt‘yesorno?’withoutanewlineandthenreadtheanswerintothevariable‘a’.Inthiscase‘$#a’wouldbe‘0’ifeitherablanklineorend-of-file(↑D)wastyped.

-26-Oneminordifferencebetween‘$n’and‘$argv[n]’shouldbenotedhere.Theform‘$argv[n]’ willyieldanerrorifnisnotintherange‘1−$#argv’while‘$n’willneveryieldanoutofrange subscripterror.Thisisforcompatibilitywiththewayoldershellshandledparameters. Anotherimportantpointisthatitisneveranerrortogiveasubrangeoftheform‘n−’;if therearelessthanncomponentsofthegivenvariablethennowordsaresubstituted.Arangeof theform‘m−n’likewisereturnsanemptyvectorwithoutgivinganerrorwhenmexceedsthe numberofelementsofthegivenvariable,providedthesubscriptnisinrange. 3.5.Expressions Inorderforinterestingshellscriptstobeconstructeditmustbepossibletoevaluateexpressionsintheshellbasedonthevaluesofvariables.Infact,allthearithmeticoperationsofthelanguageCareavailableintheshellwiththesameprecedencethattheyhaveinC.Inparticular, theoperations‘==’and‘!=’comparestringsandtheoperators‘&&’and‘||’implementthe booleanand/oroperations.Thespecialoperators‘=˜ ’and‘!˜ ’aresimilarto‘==’and‘!=’ exceptthatthestringontherightsidecanhavepatternmatchingcharacters(like*,?or[])and thetestiswhetherthestringontheleftmatchesthepatternontheright. Theshellalsoallowsfileenquiriesoftheform −?filename where‘?’isreplacebyanumberofsinglecharacters.Forinstancetheexpressionprimitive −efilename tellwhetherthefile‘filename’exists.Otherprimitivestestforread,writeandexecuteaccessto thefile,whetheritisadirectory,orhasnon-zerolength. Itispossibletotestwhetheracommandterminatesnormally,byaprimitiveoftheform‘{ command}’whichreturnstrue,i.e.‘1’ifthecommandsucceedsexitingnormallywithexitstatus 0,or‘0’ifthecommandterminatesabnormallyorwithexitstatusnon-zero.Ifmoredetailed informationabouttheexecutionstatusofacommandisrequired,itcanbeexecutedandthevariable‘$status’examinedinthenextcommand.Since‘$status’issetbyeverycommand,itisvery transient.Itcanbesavedifitisinconvenienttouseitonlyinthesingleimmediatelyfollowing command. Forafulllistofexpressioncomponentsavailableseethemanualsectionfortheshell. 3.6.Sampleshellscript Asampleshellscriptwhichmakesuseoftheexpressionmechanismoftheshellandsomeof itscontrolstructurefollows:

-27- %catcopyc # #CopyccopiesthoseCprogramsinthespecifiedlist #tothedirectory˜ /backupiftheydifferfromthefiles #alreadyin˜ /backup # setnoglob foreachi($argv) if($i!˜ *.c)continue#nota.cfilesodonothing if(!−r˜ /backup/$i:t)then echo$i:tnotinbackup...notcp\´ ed continue endif cmp−s$i˜ /backup/$i:t#toset$status if($status!=0)then echonewbackupof$i cp$i˜ /backup/$i:t endif end Thisscriptmakesuseoftheforeachcommand,whichcausestheshelltoexecutethecommandsbetweentheforeachandthematchingendforeachofthevaluesgivenbetween‘(’and‘)’ withthenamedvariable,inthiscase‘i’settosuccessivevaluesinthelist.Withinthisloopwe mayusethecommandbreaktostopexecutingtheloopandcontinuetoprematurelyterminate oneiterationandbeginthenext.Aftertheforeachlooptheiterationvariable(iinthiscase)has thevalueatthelastiteration. Wesetthevariablenoglobheretopreventfilenameexpansionofthemembersofargv.This isagoodidea,ingeneral,iftheargumentstoashellscriptarefilenameswhichhavealreadybeen expandedoriftheargumentsmaycontainfilenameexpansionmetacharacters.Itisalsopossible toquoteeachuseofa‘$’variableexpansion,butthisisharderandlessreliable. Theothercontrolconstructusedhereisastatementoftheform if(expression)then command ... endif Theplacementofthekeywordshereisnotflexibleduetothecurrentimplementationofthe shell.† Theshelldoeshaveanotherformoftheifstatementoftheform †Thefollowingtwoformatsarenotcurrentlyacceptabletotheshell: if(expression)#Won’twork! then command ... endif and if(expression)thencommandendif#Won’twork -28-if(expression)command whichcanbewritten if(expression)\ command Herewehaveescapedthenewlineforthesakeofappearance.Thecommandmustnotinvolve‘|’, ‘&’or‘;’andmustnotbeanothercontrolcommand.Thesecondformrequiresthefinal‘\’to immediatelyprecedetheend-of-line. Themoregeneralifstatementsabovealsoadmitasequenceofelse−ifpairsfollowedbya singleelseandanendif,e.g.: if(expression)then commands elseif(expression)then commands ... else commands endif Anotherimportantmechanismusedinshellscriptsisthe‘:’modifier.Wecanusethemodifier‘:r’heretoextractarootofafilenameor‘:e’toextracttheextension.Thusifthevariablei hasthevalue‘/mnt/foo.bar’then %echo$i$i:r$i:e /mnt/foo.bar/mnt/foobar % showshowthe‘:r’modifierstripsoffthetrailing‘.bar’andthethe‘:e’modifierleavesonlythe ‘bar’.Othermodifierswilltakeoffthelastcomponentofapathnameleavingthehead‘:h’orall butthelastcomponentofapathnameleavingthetail‘:t’.Thesemodifiersarefullydescribedin thecshmanualpagesintheprogrammersmanual.Itisalsopossibletousethecommandsubstitutionmechanismdescribedinthenextmajorsectiontoperformmodificationsonstringstothen reentertheshellsenvironment.Sinceeachusageofthismechanisminvolvesthecreationofanew process,itismuchmoreexpensivetousethanthe‘:’modificationmechanism.#Finally,wenote thatthecharacter‘#’lexicallyintroducesashellcommentinshellscripts(butnotfromtheterminal).Allsubsequentcharactersontheinputlineaftera‘#’arediscardedbytheshell.This charactercanbequotedusing‘´ ’or‘\’toplaceitinanargumentword. 3.7.Othercontrolstructures TheshellalsohascontrolstructureswhileandswitchsimilartothoseofC.Thesetakethe forms #Itisalsoimportanttonotethatthecurrentimplementationoftheshelllimitsthenumberof‘:’ modifiersona‘$’substitutionto1.Thus %echo$i$i:h:t /a/b/c/a/b:t % doesnotdowhatonewouldexpect.

-29-while(expression) commands end and switch(word) casestr1: commands breaksw ... casestrn: commands breaksw default: commands breaksw endsw Fordetailsseethemanualsectionforcsh.Cprogrammersshouldnotethatweusebreakswto exitfromaswitchwhilebreakexitsawhileorforeachloop.Acommonmistaketomakeincsh scriptsistousebreakratherthanbreakswinswitches. Finally,cshallowsagotostatement,withlabelslookingliketheydoinC,i.e.: loop: commands gotoloop 3.8.Supplyinginputtocommands Commandsrunfromshellscriptsreceivebydefaultthestandardinputoftheshellwhichis runningthescript.ThisisdifferentfrompreviousshellsrunningunderUNIX.Itallowsshell scriptstofullyparticipateinpipelines,butmandatesextranotationforcommandswhichareto takeinlinedata. Thusweneedametanotationforsupplyinginlinedatatocommandsinshellscripts.Asan example,considerthisscriptwhichrunstheeditortodeleteleadingblanksfromthelinesineach argumentfile %catdeblank #deblank−−removeleadingblanks foreachi($argv) ed−$i<<´ EOF´ 1,$s/↑[]*// w q ´ EOF´ end % Thenotation‘<<´ EOF´ ’meansthatthestandardinputfortheedcommandistocomefromthe textintheshellscriptfileuptothenextlineconsistingofexactly‘´ EOF´ ’.Thefactthatthe ‘EOF’isenclosedin‘´ ’characters,i.e.quoted,causestheshelltonotperformvariable -30-substitutionontheinterveninglines.Ingeneral,ifanypartofthewordfollowingthe‘<<’which theshellusestoterminatethetexttobegiventothecommandisquotedthenthesesubstitutions willnotbeperformed.Inthiscasesinceweusedtheform‘1,$’inoureditorscriptweneededto insurethatthis‘$’wasnotvariablesubstituted.Wecouldalsohaveinsuredthisbyprecedingthe ‘$’herewitha‘\’,i.e.: 1,\$s/↑[]*// butquotingthe‘EOF’terminatorisamorereliablewayofachievingthesamething. 3.9.Catchinginterrupts Ifourshellscriptcreatestemporaryfiles,wemaywishtocatchinterruptionsoftheshell scriptsothatwecancleanupthesefiles.Wecanthendo onintrlabel wherelabelisalabelinourprogram.Ifaninterruptisreceivedtheshellwilldoa‘gotolabel’and wecanremovethetemporaryfilesandthendoanexitcommand(whichisbuiltintotheshell)to exitfromtheshellscript.Ifwewishtoexitwithanon-zerostatuswecando exit(1) e.g.toexitwithstatus‘1’. 3.10.Whatelse? Thereareotherfeaturesoftheshellusefultowritersofshellprocedures.Theverboseand echooptionsandtherelated−vand−xcommandlineoptionscanbeusedtohelptracethe actionsoftheshell.The−noptioncausestheshellonlytoreadcommandsandnottoexecute themandmaysometimesbeofuse. Oneotherthingtonoteisthatcshwillnotexecuteshellscriptswhichdonotbeginwiththe character‘#’,thatisshellscriptsthatdonotbeginwithacomment.Similarly,the‘/bin/sh’on yoursystemmaywelldeferto‘csh’tointerpretshellscriptswhichbeginwith‘#’.Thisallows shellscriptsforbothshellstoliveinharmony. Thereisalsoanotherquotationmechanismusing‘"’whichallowsonlysomeoftheexpansionmechanismswehavesofardiscussedtooccuronthequotedstringandservestomakethis stringintoasinglewordas‘´ ’does.

-31-4.Other,lesscommonlyused,shellfeatures 4.1.Loopsattheterminal;variablesasvectors Itisoccasionallyusefultousetheforeachcontrolstructureattheterminaltoaidinperforminganumberofsimilarcommands.Forinstance,therewereatonepointthreeshellsinuse ontheCoryUNIXsystematCoryHall,‘/bin/sh’,‘/bin/nsh’,and‘/bin/csh’.Tocountthe numberofpersonsusingeachshellonecouldhaveissuedthecommands %grep−ccsh$/etc/passwd 27 %grep−cnsh$/etc/passwd 128 %grep−c−vsh$/etc/passwd 430 % Sincethesecommandsareverysimilarwecanuseforeachtodothismoreeasily. %foreachi(´ sh$´ ´ csh$´ ´ −vsh$´ ) ?grep−c$i/etc/passwd ?end 27 128 430 % Noteherethattheshellpromptsforinputwith‘?’whenreadingthebodyoftheloop. Veryusefulwithloopsarevariableswhichcontainlistsoffilenamesorotherwords.You can,forexample,do %seta=(` ls` ) %echo$a csh.ncsh.rm %ls csh.n csh.rm %echo$#a 2 % Thesetcommandheregavethevariableaalistofallthefilenamesinthecurrentdirectoryas value.Wecantheniterateoverthesenamestoperformanychosenfunction. Theoutputofacommandwithin‘` ’charactersisconvertedbytheshelltoalistofwords. Youcanalsoplacethe‘` ’quotedstringwithin‘"’characterstotakeeach(non-empty)lineasa componentofthevariable;preventingthelinesfrombeingsplitintowordsatblanksandtabs.A modifier‘:x’existswhichcanbeusedlatertoexpandeachcomponentofthevariableintoanother variablesplittingitintoseparatewordsatembeddedblanksandtabs. 4.2.Braces{...}inargumentexpansion Anotherformoffilenameexpansion,alludedtobeforeinvolvesthecharacters‘{’and‘}’. Thesecharactersspecifythatthecontainedstrings,separatedby‘,’aretobeconsecutivelysubstitutedintothecontainingcharactersandtheresultsexpandedlefttoright.Thus A{str1,str2,...strn}B expandsto -32-Astr1BAstr2B...AstrnB Thisexpansionoccursbeforetheotherfilenameexpansions,andmaybeappliedrecursively(i.e. nested).Theresultsofeachexpandedstringaresortedseparately,lefttorightorderbeingpreserved.Theresultingfilenamesarenotrequiredtoexistifnootherexpansionmechanismsare used.Thismeansthatthismechanismcanbeusedtogenerateargumentswhicharenotfilenames,butwhichhavecommonparts. Atypicaluseofthiswouldbe mkdir˜ /{hdrs,retrofit,csh} tomakesubdirectories‘hdrs’,‘retrofit’and‘csh’inyourhomedirectory.Thismechanismismost usefulwhenthecommonprefixislongerthaninthisexample,i.e. chownroot/usr/{ucb/{ex,edit},lib/{ex?.?*,howex}} 4.3.Commandsubstitution Acommandenclosedin‘` ’charactersisreplaced,justbeforefilenamesareexpanded,bythe outputfromthatcommand.Thusitispossibletodo setpwd=` pwd` tosavethecurrentdirectoryinthevariablepwdortodo ex` grep−lTRACE*.c` toruntheeditorexsupplyingasargumentsthosefileswhosenamesendin‘.c’whichhavethe string‘TRACE’inthem.* 4.4.Otherdetailsnotcoveredhere Inparticularcircumstancesitmaybenecessarytoknowtheexactnatureandorderofdifferentsubstitutionsperformedbytheshell.Theexactmeaningofcertaincombinationsofquotationsisalsooccasionallyimportant.Thesearedetailedfullyinitsmanualsection. TheshellhasanumberofcommandlineoptionflagsmostlyofuseinwritingUNIXprograms,anddebuggingshellscripts.Seetheshellsmanualsectionforalistoftheseoptions. *Commandexpansionalsooccursininputredirectedwith‘<<’andwithin‘"’quotations.Referto theshellmanualsectionforfulldetails.

-33-Appendix−Specialcharacters ThefollowingtableliststhespecialcharactersofcshandtheUNIXsystem,givingforeachthesection(s)inwhichitisdiscussed.Anumberofthesecharactersalsohavespecialmeaninginexpressions.Seethecshmanualsectionforacompletelist. Syntacticmetacharacters ;2.4separatescommandstobeexecutedsequentially |1.5separatescommandsinapipeline ()2.2,3.6bracketsexpressionsandvariablevalues &2.5followscommandstobeexecutedwithoutwaitingforcompletion Filenamemetacharacters /1.6separatescomponentsofafile’spathname ?1.6expansioncharactermatchinganysinglecharacter *1.6expansioncharactermatchinganysequenceofcharacters []1.6expansionsequencematchinganysinglecharacterfromaset ˜ 1.6usedatthebeginningofafilenametoindicatehomedirectories {}4.2usedtospecifygroupsofargumentswithcommonparts Quotationmetacharacters \1.7preventsmeta-meaningoffollowingsinglecharacter ´ 1.7preventsmeta-meaningofagroupofcharacters "4.3like´ ,butallowsvariableandcommandexpansion Input/outputmetacharacters <1.5indicatesredirectedinput >1.3indicatesredirectedoutput Expansion/substitutionmetacharacters $3.4indicatesvariablesubstitution !2.3indicateshistorysubstitution :3.6precedessubstitutionmodifiers ↑2.3usedinspecialformsofhistorysubstitution ` 4.3indicatescommandsubstitution Othermetacharacters #1.3,3.6beginsscratchfilenames;indicatesshellcomments −1.2prefixesoption(flag)argumentstocommands %2.6prefixesjobnamespecifications -34-Glossary Thisglossaryliststhemostimportanttermsintroducedintheintroductiontotheshelland givesreferencestosectionsoftheshelldocumentforfurtherinformationaboutthem.References oftheform‘pr(1)’indicatethatthecommandprisintheUNIXprogrammer’smanualinsection 1.Youcangetanonlinecopyofitsmanualpagebydoing man1pr Referencesoftheform(2.5)indicatethatmoreinformationcanbefoundinsection2.5ofthis manual. .Yourcurrentdirectoryhasthename‘.’aswellasthenameprintedbythecommandpwd;seealsodirs.Thecurrentdirectory‘.’isusuallythefirstcomponent ofthesearchpathcontainedinthevariablepath,thuscommandswhicharein‘.’ arefoundfirst(2.2).Thecharacter‘.’isalsousedinseparatingcomponentsof filenames(1.6).Thecharacter‘.’atthebeginningofacomponentofapathname istreatedspeciallyandnotmatchedbythefilenameexpansionmetacharacters ‘?’,‘*’,and‘[’‘]’pairs(1.6). ..Eachdirectoryhasafile‘..’initwhichisareferencetoitsparentdirectory. Afterchangingintothedirectorywithchdir,i.e. chdirpaper youcanreturntotheparentdirectorybydoing chdir.. Thecurrentdirectoryisprintedbypwd(2.7). a.outCompilerswhichcreateexecutableimagescreatethem,bydefault,inthefile a.out.forhistoricalreasons(2.3). absolutepathname Apathnamewhichbeginswitha‘/’isabsolutesinceitspecifiesthepathofdirectoriesfromthebeginningoftheentiredirectorysystem−calledtherootdirectory.Pathnameswhicharenotabsolutearecalledrelative(seedefinitionofrelativepathname)(1.6). aliasAnaliasspecifiesashorterordifferentnameforaUNIXcommand,oratransformationonacommandtobeperformedintheshell.Theshellhasacommand aliaswhichestablishesaliasesandcanprinttheircurrentvalues.Thecommand unaliasisusedtoremovealiases(2.4). argumentCommandsinUNIXreceivealistofargumentwords.Thusthecommand echoabc consistsofthecommandname‘echo’andthreeargumentwords‘a’,‘b’and‘c’. Thesetofargumentsafterthecommandnameissaidtobetheargumentlistof thecommand(1.1). argvThelistofargumentstoacommandwrittenintheshelllanguage(ashellscript orshellprocedure)isstoredinavariablecalledargvwithintheshell.Thisname istakenfromtheconventionalnameintheCprogramminglanguage(3.4). backgroundCommandsstartedwithoutwaitingforthemtocompletearecalledbackground commands(2.6). baseAfilenameissometimesthoughtofasconsistingofabasepart,beforeany‘.’ character,andanextension−thepartafterthe‘.’.Seefilenameandextension (1.6) bgThebgcommandcausesasuspendedjobtocontinueexecutioninthebackground (2.6).

-35-binAdirectorycontainingbinariesofprogramsandshellscriptstobeexecutedis typicallycalledabindirectory.Thestandardsystembindirectoriesare‘/bin’ containingthemostheavilyusedcommandsand‘/usr/bin’whichcontainsmost otheruserprograms.ProgramsdevelopedatUCBerkeleylivein‘/usr/ucb’, whilelocallywrittenprogramslivein‘/usr/local’.Gamesarekeptinthedirectory‘/usr/games’.Youcanplacebinariesinanydirectory.Ifyouwishtoexecutethemoften,thenameofthedirectoriesshouldbeacomponentofthevariablepath. breakBreakisabuiltincommandusedtoexitfromloopswithinthecontrolstructure oftheshell(3.7). breakswThebreakswbuiltincommandisusedtoexitfromaswitchcontrolstructure,like abreakexitsfromloops(3.7). builtinAcommandexecuteddirectlybytheshelliscalledabuiltincommand.Most commandsinUNIXarenotbuiltintotheshell,butratherexistasfilesinbin directories.Thesecommandsareaccessiblebecausethedirectoriesinwhichthey residearenamedinthepathvariable. caseAcasecommandisusedasalabelinaswitchstatementintheshell’scontrol structure,similartothatofthelanguageC.Detailsaregivenintheshelldocumentation‘csh(1)’(3.7). catThecatprogramcatenatesalistofspecifiedfilesonthestandardoutput.Itis usuallyusedtolookatthecontentsofasinglefileontheterminal,to‘catafile’ (1.8,2.3). cdThecdcommandisusedtochangetheworkingdirectory.Withnoarguments, cdchangesyourworkingdirectorytobeyourhomedirectory(2.4,2.7). chdirThechdircommandisasynonymforcd.Cdisusuallyusedbecauseitiseasier totype. chshThechshcommandisusedtochangetheshellwhichyouuseonUNIX.By default,youuseandifferentversionoftheshellwhichresidesin‘/bin/sh’.You canchangeyourshellto‘/bin/csh’bydoing chshyour-login-name/bin/csh ThusIwoulddo chshbill/bin/csh Itisonlynecessarytodothisonce.ThenexttimeyoulogintoUNIXafterdoing thiscommand,youwillbeusingcshratherthantheshellin‘/bin/sh’(1.9). cmpCmpisaprogramwhichcomparesfiles.Itisusuallyusedonbinaryfiles,orto seeiftwofilesareidentical(3.6).Forcomparingtextfilestheprogramdiff, describedin‘diff(1)’isused. commandAfunctionperformedbythesystem,eitherbytheshell(abuiltincommand)or byaprogramresidinginafileinadirectorywithintheUNIXsystem,iscalleda command(1.1). commandname Whenacommandisissued,itconsistsofacommandname,whichisthefirst wordofthecommand,followedbyarguments.TheconventiononUNIXisthat thefirstwordofacommandnamesthefunctiontobeperformed(1.1). commandsubstitution Thereplacementofacommandenclosedin‘` ’charactersbythetextoutputby thatcommandiscalledcommandsubstitution(4.3). componentApartofapathnamebetween‘/’charactersiscalledacomponentofthatpathname.Avariablewhichhasmultiplestringsasvalueissaidtohaveseveral -36-components;eachstringisacomponentofthevariable. continueAbuiltincommandwhichcausesexecutionoftheenclosingforeachorwhileloop tocycleprematurely.SimilartothecontinuecommandintheprogramminglanguageC(3.6). control-Certainspecialcharacters,calledcontrolcharacters,areproducedbyholding downtheCONTROLkeyonyourterminalandsimultaneouslypressinganother character,muchliketheSHIFTkeyisusedtoproduceuppercasecharacters. Thuscontrol-cisproducedbyholdingdowntheCONTROLkeywhilepressingthe ‘c’key.UsuallyUNIXprintsanup-arrow(↑)followedbythecorrespondingletter whenyoutypeacontrolcharacter(e.g.‘↑C’forcontrol-c(1.8). coredumpWhenaprogramterminatesabnormally,thesystemplacesanimageofitscurrentstateinafilenamed‘core’.Thiscoredumpcanbeexaminedwiththesystemdebugger‘adb(1)’or‘sdb(1)’inordertodeterminewhatwentwrongwith theprogram(1.8).Iftheshellproducesamessageoftheform Illegalinstruction(coredumped) (where‘Illegalinstruction’isonlyoneofseveralpossiblemessages),youshould reportthistotheauthoroftheprogramorasystemadministrator,savingthe ‘core’file. cpThecp(copy)programisusedtocopythecontentsofonefileintoanotherfile. ItisoneofthemostcommonlyusedUNIXcommands(1.6). cshThenameoftheshellprogramthatthisdocumentdescribes. .cshrcThefile.cshrcinyourhomedirectoryisreadbyeachshellasitbeginsexecution. Itisusuallyusedtochangethesettingofthevariablepathandtosetalias parameterswhicharetotakeeffectglobally(2.1). cwdThecwdvariableintheshellholdstheabsolutepathnameofthecurrentworking directory.Itischangedbytheshellwheneveryourcurrentworkingdirectory changesandshouldnotbechangedotherwise(2.2). dateThedatecommandprintsthecurrentdateandtime(1.3). debuggingDebuggingistheprocessofcorrectingmistakesinprogramsandshellscripts. Theshellhasseveraloptionsandvariableswhichmaybeusedtoaidinshell debugging(4.4). default:Thelabeldefault:isusedwithinshellswitchstatements,asitisintheClanguagetolabelthecodetobeexecutedifnoneofthecaselabelsmatchesthe valueswitchedon(3.7). DELETETheDELETEorRUBOUTkeyontheterminalnormallycausesaninterrupttobe senttothecurrentjob.Manyuserschangetheinterruptcharactertobe↑C. detachedAcommandthatcontinuesrunninginthebackgroundafteryoulogoutissaidto bedetached. diagnosticAnerrormessageproducedbyaprogramisoftenreferredtoasadiagnostic. Mosterrormessagesarenotwrittentothestandardoutput,sincethatisoften directedawayfromtheterminal(1.3,1.5).Errormesssagesareinsteadwritten tothediagnosticoutputwhichmaybedirectedawayfromtheterminal,butusuallyisnot.Thusdiagnosticswillusuallyappearontheterminal(2.5). directoryAstructurewhichcontainsfiles.Atanytimeyouareinoneparticulardirectory whosenamescanbeprintedbythecommandpwd.Thechdircommandwill changeyoutoanotherdirectory,andmakethefilesinthatdirectoryvisible.The directoryinwhichyouarewhenyoufirstloginisyourhomedirectory(1.1,2.7). directorystackTheshellsavesthenamesofpreviousworkingdirectoriesinthedirectorystack whenyouchangeyourcurrentworkingdirectoryviathepushdcommand.The -37-directorystackcanbeprintedbyusingthedirscommand,whichincludesyour currentworkingdirectoryasthefirstdirectorynameontheleft(2.7). dirsThedirscommandprintstheshell’sdirectorystack(2.7). duTheducommandisaprogram(describedin‘du(1)’)whichprintsthenumberof diskblocksisalldirectoriesbelowandincludingyourcurrentworkingdirectory (2.6). echoTheechocommandprintsitsarguments(1.6,3.6). elseTheelsecommandispartofthe‘if-then-else-endif’controlcommandconstruct (3.6). endifIfanifstatementisendedwiththewordthen,alllinesfollowingtheifuptoa linestartingwiththewordendiforelseareexecutediftheconditionbetween parenthesesaftertheifistrue(3.6). EOFAnend-of-fileisgeneratedbytheterminalbyacontrol-d,andwheneveracom-mandreadstotheendofafilewhichithasbeengivenasinput.Commands receivinginputfromapipereceiveanend-of-filewhenthecommandsending theminputcompletes.Mostcommandsterminatewhentheyreceiveanend-of-file.Theshellhasanoptiontoignoreend-of-filefromaterminalinputwhich mayhelpyoukeepfromloggingoutaccidentallybytypingtoomanycontrol-d’s (1.1,1.8,3.8). escapeAcharacter‘\’usedtopreventthespecialmeaningofametacharacterissaidto escapethecharacterfromitsspecialmeaning.Thus echo\* willechothecharacter‘*’whilejust echo* willechothenamesofthefileinthecurrentdirectory.Inthisexample,\ escapes‘*’(1.7).Thereisalsoanon-printingcharactercalledescape,usually labelledESCorALTMODEonterminalkeyboards.SomeolderUNIXsystemsuse thischaractertoindicatethatoutputistobesuspended.Mostsystemsusecontrol-stostoptheoutputandcontrol-qtostartit. /etc/passwdThisfilecontainsinformationabouttheaccountscurrentlyonthesystem.It consistsofalineforeachaccountwithfieldsseparatedby‘:’characters(1.8). Youcanlookatthisfilebysaying cat/etc/passwd Thecommandsfingerandgrepareoftenusedtosearchforinformationinthis file.See‘finger(1)’,‘passwd(5)’,and‘grep(1)’formoredetails. exitTheexitcommandisusedtoforceterminationofashellscript,andisbuiltinto theshell(3.9). exitstatusAcommandwhichdiscoversaproblemmayreflectthisbacktothecommand (suchasashell)whichinvoked(executed)it.Itdoesthisbyreturninganonzeronumberasitsexitstatus,astatusofzerobeingconsidered‘normaltermination’.Theexitcommandcanbeusedtoforceashellcommandscripttogivea non-zeroexitstatus(3.6). expansionThereplacementofstringsintheshellinputwhichcontainmetacharactersby otherstringsisreferredtoastheprocessofexpansion.Thusthereplacementof theword‘*’byasortedlistoffilesinthecurrentdirectoryisa‘filenameexpansion’.Similarlythereplacementofthecharacters‘!!’bythetextofthelastcommandisa‘historyexpansion’.Expansionsarealsoreferredtoassubstitutions (1.6,3.4,4.2).

-38-expressionsExpressionsareusedintheshelltocontroltheconditionalstructuresusedinthe writingofshellscriptsandincalculatingvaluesforthesescripts.Theoperators availableinshellexpressionsarethoseofthelanguageC(3.5). extensionFilenamesoftenconsistofabasenameandanextensionseparatedbythecharacter‘.’.Byconvention,groupsofrelatedfilesoftensharethesamerootname. Thusif‘prog.c’wereaCprogram,thentheobjectfileforthisprogramwouldbe storedin‘prog.o’.Similarlyapaperwrittenwiththe‘−me’nroffmacropackage mightbestoredin‘paper.me’whileaformattedversionofthispapermightbe keptin‘paper.out’andalistofspellingerrorsin‘paper.errs’(1.6). fgThejobcontrolcommandfgisusedtorunabackgroundorsuspendedjobinthe foreground(1.8,2.6). filenameEachfileinUNIXhasanameconsistingofupto14charactersandnotincluding thecharacter‘/’whichisusedinpathnamebuilding.Mostfilenamesdonot beginwiththecharacter‘.’,andcontainonlylettersanddigitswithperhapsa‘.’ separatingthebaseportionofthefilenamefromanextension(1.6). filenameexpansion Filenameexpansionusesthemetacharacters‘*’,‘?’and‘[’and‘]’toprovidea convenientmechanismfornamingfiles.Usingfilenameexpansionitiseasyto nameallthefilesinthecurrentdirectory,orallfileswhichhaveacommonroot name.Otherfilenameexpansionmechanismsusethemetacharacter‘˜ ’andallow filesinotherusers’directoriestobenamedeasily(1.6,4.2). flagManyUNIXcommandsacceptargumentswhicharenotthenamesoffilesor otherusersbutareusedtomodifytheactionofthecommands.Theseare referredtoasflagoptions,andbyconventionconsistofoneormorelettersprecededbythecharacter‘−’(1.2).Thusthels(listfiles)commandhasanoption ‘−s’tolistthesizesoffiles.Thisisspecified ls−s foreachTheforeachcommandisusedinshellscriptsandattheterminaltospecifyrepetitionofasequenceofcommandswhilethevalueofacertainshellvariable rangesthroughaspecifiedlist(3.6,4.1). foregroundWhencommandsareexecutinginthenormalwaysuchthattheshelliswaiting forthemtofinishbeforepromptingforanothercommandtheyaresaidtobe foregroundjobsorrunningintheforeground.Thisisasopposedtobackground. Foregroundjobscanbestoppedbysignalsfromtheterminalcausedbytyping differentcontrolcharactersatthekeyboard(1.8,2.6). gotoTheshellhasacommandgotousedinshellscriptstotransfercontroltoagiven label(3.7). grepThegrepcommandsearchesthroughalistofargumentfilesforaspecifiedstring. Thus grepbill/etc/passwd willprinteachlineinthefile/etc/passwdwhichcontainsthestring‘bill’.Actually,grepscansforregularexpressionsinthesenseoftheeditors‘ed(1)’and ‘ex(1)’.Grepstandsfor‘globallyfindregularexpressionandprint’(2.4). headTheheadcommandprintsthefirstfewlinesofoneormorefiles.Ifyouhavea bunchoffilescontainingtextwhichyouarewonderingaboutitissometimesusefultorunheadwiththesefilesasarguments.Thiswillusuallyshowenoughof whatisinthesefilestoletyoudecidewhichyouareinterestedin(1.5). Headisalsousedtodescribethepartofapathnamebeforeandincludingthelast ‘/’character.Thetailofapathnameisthepartafterthelast‘/’.The‘:h’and ‘:t’modifiersallowtheheadortailofapathnamestoredinashellvariabletobe -39-used(3.6). historyThehistorymechanismoftheshellallowspreviouscommandstoberepeated, possiblyaftermodificationtocorrecttypingmistakesortochangethemeaning ofthecommand.Theshellhasahistorylistwherethesecommandsarekept, andahistoryvariablewhichcontrolshowlargethislistis(2.3). homedirectory Eachuserhasahomedirectory,whichisgiveninyourentryinthepasswordfile, /etc/passwd.Thisisthedirectorywhichyouareplacedinwhenyoufirstlogin. Thecdorchdircommandwithnoargumentstakesyoubacktothisdirectory, whosenameisrecordedintheshellvariablehome.Youcanalsoaccessthehome directoriesofotherusersinformingfilenamesusingafilenameexpansionnotationandthecharacter‘˜ ’(1.6). ifAconditionalcommandwithintheshell,theifcommandisusedinshellcommandscriptstomakedecisionsaboutwhatcourseofactiontotakenext(3.6). ignoreeofNormally,yourshellwillexit,printing‘logout’ifyoutypeacontrol-data promptof‘%’.Thisisthewayyouusuallylogoffthesystem.Youcansetthe ignoreeofvariableifyouwishinyour.loginfileandthenusethecommandlogout tologout.Thisisusefulifyousometimesaccidentallytypetoomanycontrol-d characters,loggingyourselfoff(2.2). inputManycommandsonUNIXtakeinformationfromtheterminalorfromfileswhich theythenacton.Thisinformationiscalledinput.Commandsnormallyreadfor inputfromtheirstandardinputwhichis,bydefault,theterminal.Thisstandard inputcanberedirectedfromafileusingashellmetanotationwiththecharacter ‘<’.Manycommandswillalsoreadfromafilespecifiedasargument.Commandsplacedinpipelineswillreadfromtheoutputofthepreviouscommandin thepipeline.Theleftmostcommandinapipelinereadsfromtheterminalifyou neitherredirectitsinputnorgiveitafilenametouseasstandardinput.Special mechanismsexistforsupplyinginputtocommandsinshellscripts(1.5,3.8). interruptAninterruptisasignaltoaprogramthatisgeneratedbyhittingtheRUBOUTor DELETEkey(althoughuserscanandoftendochangetheinterruptcharacter, usuallyto↑C).Itcausesmostprogramstostopexecution.Certainprograms, suchastheshellandtheeditors,handleaninterruptinspecialways,usuallyby stoppingwhattheyaredoingandpromptingforanothercommand.Whilethe shellisexecutinganothercommandandwaitingforittofinish,theshelldoes notlistentointerrupts.Theshelloftenwakesupwhenyouhitinterruptbecause manycommandsdiewhentheyreceiveaninterrupt(1.8,3.9). jobOneormorecommandstypedonthesameinputlineseparatedby‘|’or‘;’charactersareruntogetherandarecalledajob.Simplecommandsrunbythemselveswithoutany‘|’or‘;’charactersarethesimplestjobs.Jobsareclassifiedas foreground,background,orsuspended(2.6). jobcontrolThebuiltinfunctionsthatcontroltheexecutionofjobsarecalledjobcontrol commands.Thesearebg,fg,stop,kill(2.6). jobnumberWheneachjobisstarteditisassignedasmallnumbercalledajobnumberwhich isprintednexttothejobintheoutputofthejobscommand.Thisnumber,precededbya‘%’character,canbeusedasanargumenttojobcontrolcommands toindicateaspecificjob(2.6). jobsThejobscommandprintsatableshowingjobsthatareeitherrunninginthe backgroundoraresuspended(2.6). killAcommandwhichsendsasignaltoajobcausingittoterminate(2.6). .loginThefile.logininyourhomedirectoryisreadbytheshelleachtimeyouloginto UNIXandthecommandsthereareexecuted.Thereareanumberofcommands -40-whichareusefullyplacedhere,especiallysetcommandstotheshellitself(2.1). loginshellTheshellthatisstartedonyourterminalwhenyouloginiscalledyourlogin shell.Itisdifferentfromothershellswhichyoumayrun(e.g.onshellscripts)in thatitreadsthe.loginfilebeforereadingcommandsfromtheterminalandit readsthe.logoutfileafteryoulogout(2.1). logoutThelogoutcommandcausesaloginshelltoexit.Normally,aloginshellwillexit whenyouhitcontrol-dgeneratinganend-of-file,butifyouhavesetignoreeofin you.loginfilethenthiswillnotworkandyoumustuselogouttologofftheUNIX system(2.8). .logoutWhenyoulogoffofUNIXtheshellwillexecutecommandsfromthefile.logoutin yourhomedirectoryafteritprints‘logout’. lprThecommandlpristhelineprinterdaemon.Thestandardinputoflprspooled andprintedontheUNIXlineprinter.Youcanalsogivelpralistoffilenamesas argumentstobeprinted.Itismostcommontouselprasthelastcomponentof apipeline(2.3). lsThels(listfiles)commandisoneofthemostcommonlyusedUNIXcommands. Withnoargumentfilenamesitprintsthenamesofthefilesinthecurrentdirectory.Ithasanumberofusefulflagarguments,andcanalsobegiventhenames ofdirectoriesasarguments,inwhichcaseitliststhenamesofthefilesinthese directories(1.2). mailThemailprogramisusedtosendandreceivemessagesfromotherUNIXusers (1.1,2.1). makeThemakecommandisusedtomaintainoneormorerelatedfilesandtoorganize functionstobeperformedonthesefiles.Inmanywaysmakeiseasiertouse, andmorehelpfulthanshellcommandscripts(3.2). makefileThefilecontainingcommandsformakeiscalledmakefile(3.2). manualThemanualoftenreferredtoisthe‘UNIXprogrammer’smanual’.Itcontainsa numberofsectionsandadescriptionofeachUNIXprogram.Anonlineversionof themanualisaccessiblethroughthemancommand.Itsdocumentationcanbe obtainedonlinevia manman metacharacter Manycharacterswhichareneitherlettersnordigitshavespecialmeaningeither totheshellortoUNIX.Thesecharactersarecalledmetacharacters.Ifitisnecessarytoplacethesecharactersinargumentstocommandswithoutthemhaving theirspecialmeaningthentheymustbequoted.Anexampleofametacharacter isthecharacter‘>’whichisusedtoindicateplacementofoutputintoafile.For thepurposesofthehistorymechanism,mostunquotedmetacharactersformseparatewords(1.4).Theappendixtothisuser’smanualliststhemetacharactersin groupsbytheirfunction. mkdirThemkdircommandisusedtocreateanewdirectory. modifierSubstitutionswiththehistorymechanism,keyedbythecharacter‘!’orofvariablesusingthemetacharacter‘$’,areoftensubjectedtomodifications,indicated byplacingthecharacter‘:’afterthesubstitutionandfollowingthiswiththe modifieritself.Thecommandsubstitutionmechanismcanalsobeusedtoperformmodificationinasimilarway,butthisnotationislessclear(3.6). moreTheprogrammorewritesafileonyourterminalallowingyoutocontrolhow muchtextisdisplayedatatime.Morecanmovethroughthefilescreenfulby screenful,linebyline,searchforwardforastring,orstartagainatthebeginning ofthefile.Itisgenerallytheeasiestwayofviewingafile(1.8).

-41-noclobberTheshellhasavariablenoclobberwhichmaybesetinthefile.logintoprevent accidentaldestructionoffilesbythe‘>’outputredirectionmetasyntaxofthe shell(2.2,2.5). noglobTheshellvariablenoglobissettosuppressthefilenameexpansionofarguments containingthemetacharacters‘˜ ’,‘*’,‘?’,‘[’and‘]’(3.6). notifyThenotifycommandtellstheshelltoreportontheterminationofaspecific backgroundjobattheexacttimeitoccursasopposedtowaitinguntiljustbefore thenextprompttoreportthetermination.Thenotifyvariable,ifset,causesthe shelltoalwaysreporttheterminationofbackgroundjobsexactlywhenthey occur(2.6). onintrTheonintrcommandisbuiltintotheshellandisusedtocontroltheactionofa shellcommandscriptwhenaninterruptsignalisreceived(3.9). outputManycommandsinUNIXresultinsomelinesoftextwhicharecalledtheiroutput.Thisoutputisusuallyplacedonwhatisknownasthestandardoutput whichisnormallyconnectedtotheuser’sterminal.Theshellhasasyntaxusing themetacharacter‘>’forredirectingthestandardoutputofacommandtoafile (1.3).Usingthepipemechanismandthemetacharacter‘|’itisalsopossiblefor thestandardoutputofonecommandtobecomethestandardinputofanother command(1.5).Certaincommandssuchasthelineprinterdaemonpdonot placetheirresultsonthestandardoutputbutratherinmoreusefulplacessuch asonthelineprinter(2.3).Similarlythewritecommandplacesitsoutputon anotheruser’sterminalratherthanitsstandardoutput(2.3).Commandsalso haveadiagnosticoutputwheretheywritetheirerrormessages.Normallythese gototheterminalevenifthestandardoutputhasbeensenttoafileoranother command,butitispossibletodirecterrordiagnosticsalongwithstandardoutputusingaspecialmetanotation(2.5). pushdThepushdcommand,whichmeans‘pushdirectory’,changestheshell’sworking directoryandalsoremembersthecurrentworkingdirectorybeforethechangeis made,allowingyoutoreturntothesamedirectoryviathepopdcommandlater withoutretypingitsname(2.7). pathTheshellhasavariablepathwhichgivesthenamesofthedirectoriesinwhichit searchesforthecommandswhichitisgiven.Italwayschecksfirsttoseeifthe commanditisgivenisbuiltintotheshell.Ifitis,thenitneednotsearchfor thecommandasitcandoitinternally.Ifthecommandisnotbuiltin,thenthe shellsearchesforafilewiththenamegivenineachofthedirectoriesinthepath variable,lefttoright.Sincethenormaldefinitionofthepathvariableis path(./usr/ucb/bin/usr/bin) theshellnormallylooksinthecurrentdirectory,andtheninthestandardsystemdirectories‘/usr/ucb’,‘/bin’and‘/usr/bin’forthenamedcommand(2.2). Ifthecommandcannotbefoundtheshellwillprintanerrordiagnostic.Scripts ofshellcommandswillbeexecutedusinganothershelltointerpretthemifthey have‘execute’permissionset.Thisisnormallytruebecauseacommandofthe form chmod755script wasexecutedtoturnthisexecutepermissionon(3.3).Ifyouaddnewcommandstoadirectoryinthepath,youshouldissuethecommandrehash(2.2). pathnameAlistofnames,separatedby‘/’characters,formsapathname.Eachcomponent, betweensuccessive‘/’characters,namesadirectoryinwhichthenextcomponent fileresides.Pathnameswhichbeginwiththecharacter‘/’areinterpretedrelativetotherootdirectoryinthefilesystem.Otherpathnamesareinterpreted -42-relativetothecurrentdirectoryasreportedbypwd.Thelastcomponentofa pathnamemaynameadirectory,butusuallynamesafile. pipelineAgroupofcommandswhichareconnectedtogether,thestandardoutputofeach connectedtothestandardinputofthenext,iscalledapipeline.Thepipemechanismusedtoconnectthesecommandsisindicatedbytheshellmetacharacter‘|’ (1.5,2.3). popdThepopdcommandchangestheshell’sworkingdirectorytothedirectoryyou mostrecentlyleftusingthepushdcommand.Itreturnstothedirectorywithout havingtotypeitsname,forgettingthenameofthecurrentworkingdirectory beforedoingso(2.7). portThepartofacomputersystemtowhicheachterminalisconnectediscalleda port.Usuallythesystemhasafixednumberofports,someofwhichareconnectedtotelephonelinesfordial-upaccess,andsomeofwhicharepermanently wireddirectlytospecificterminals. prTheprcommandisusedtopreparelistingsofthecontentsoffileswithheaders givingthenameofthefileandthedateandtimeatwhichthefilewaslastmodified(2.3). printenvTheprintenvcommandisusedtoprintthecurrentsettingofvariablesinthe environment(2.8). processAninstanceofarunningprogramiscalledaprocess(2.6).UNIXassignseach processauniquenumberwhenitisstarted−calledtheprocessnumber.Process numberscanbeusedtostopindividualprocessesusingthekillorstopcommands whentheprocessesarepartofadetachedbackgroundjob. programUsuallysynonymouswithcommand;abinaryfileorshellcommandscriptwhich performsausefulfunctionisoftencalledaprogram. programmer’smanual Alsoreferredtoasthemanual.Seetheglossaryentryfor‘manual’. promptManyprogramswillprintapromptontheterminalwhentheyexpectinput. Thustheeditor‘ex(1)’willprinta‘:’whenitexpectsinput.Theshellprompts forinputwith‘%’andoccasionallywith‘?’whenreadingcommandsfromthe terminal(1.1).Theshellhasavariablepromptwhichmaybesettoadifferent valuetochangetheshell’smainprompt.Thisismostlyusedwhendebugging theshell(2.8). psThepscommandisusedtoshowtheprocessesyouarecurrentlyrunning.Each processisshownwithitsuniqueprocessnumber,anindicationoftheterminal nameitisattachedto,anindicationofthestateoftheprocess(whetheritis running,stopped,awaitingsomeevent(sleeping),andwhetheritisswapped out),andtheamountofCPUtimeithasusedsofar.Thecommandisidentified byprintingsomeofthewordsusedwhenitwasinvoked(2.6).Shells,suchas thecshyouusetorunthepscommand,arenotnormallyshownintheoutput. pwdThepwdcommandprintsthefullpathnameofthecurrentworkingdirectory. Thedirsbuiltincommandisusuallyabetterandfasterchoice. quitThequitsignal,generatedbyacontrol-\,isusedtoterminateprogramswhich arebehavingunreasonably.Itnormallyproducesacoreimagefile(1.8). quotationTheprocessbywhichmetacharactersarepreventedtheirspecialmeaning,usuallybyusingthecharacter‘´ inpairs,orbyusingthecharacter‘\’,isreferredto asquotation(1.7). redirectionTheroutingofinputoroutputfromortoafileisknownasredirectionofinput oroutput(1.3).

-43-rehashTherehashcommandtellstheshelltorebuilditsinternaltableofwhichcom-mandsarefoundinwhichdirectoriesinyourpath.Thisisnecessarywhenanew programisinstalledinoneofthesedirectories(2.8). relativepathname Apathnamewhichdoesnotbeginwitha‘/’iscalledarelativepathnamesinceit isinterpretedrelativetothecurrentworkingdirectory.Thefirstcomponentof suchapathnamereferstosomefileordirectoryintheworkingdirectory,and subsequentcomponentsbetween‘/’charactersrefertodirectoriesbelowthe workingdirectory.Pathnamesthatarenotrelativearecalledabsolutepathnames (1.6). repeatTherepeatcommanditeratesanothercommandaspecifiednumberoftimes. rootThedirectorythatisatthetopoftheentiredirectorystructureiscalledtheroot directorysinceitisthe‘root’oftheentiretreestructureofdirectories.The nameusedinpathnamestoindicatetherootis‘/’.Pathnamesstartingwith‘/’ aresaidtobeabsolutesincetheystartattherootdirectory.Rootisalsousedas thepartofapathnamethatisleftafterremovingtheextension.Seefilenamefor afurtherexplanation(1.6). RUBOUTTheRUBOUTorDELETEkeysendsaninterrupttothecurrentjob.Mostinteractivecommandsreturntotheircommandleveluponreceiptofaninterrupt,while non-interactivecommandsusuallyterminate,returningcontroltotheshell. Usersoftenchangeinterrupttobegeneratedby↑CratherthanDELETEbyusing thesttycommand. scratchfileFileswhosenamesbeginwitha‘#’arereferredtoasscratchfiles,sincetheyare automaticallyremovedbythesystemafteracoupleofdaysofnon-use,ormore frequentlyifdiskspacebecomestight(1.3). scriptSequencesofshellcommandsplacedinafilearecalledshellcommandscripts.It isoftenpossibletoperformsimpletasksusingthesescriptswithoutwritinga programinalanguagesuchasC,byusingtheshelltoselectivelyrunotherprograms(3.3,3.10). setThebuiltinsetcommandisusedtoassignnewvaluestoshellvariablesandto showthevaluesofthecurrentvariables.Manyshellvariableshavespecialmeaningtotheshellitself.Thusbyusingthesetcommandthebehavioroftheshell canbeaffected(2.1). setenvVariablesintheenvironment‘environ(5)’canbechangedbyusingthesetenv builtincommand(2.8).Theprintenvcommandcanbeusedtoprintthevalueof thevariablesintheenvironment. shellAshellisacommandlanguageinterpreter.Itispossibletowriteandrunyour ownshell,asshellsarenodifferentthananyotherprogramsasfarasthesystem isconcerned.Thismanualdealswiththedetailsofoneparticularshell,called csh. shellscriptSeescript(3.3,3.10). signalAsignalinUNIXisashortmessagethatissenttoarunningprogramwhich causessomethingtohappentothatprocess.Signalsaresenteitherbytyping specialcontrolcharactersonthekeyboardorbyusingthekillorstopcommands (1.8,2.6). sortThesortprogramsortsasequenceoflinesinwaysthatcanbecontrolledby argumentflags(1.5). sourceThesourcecommandcausestheshelltoreadcommandsfromaspecifiedfile.It ismostusefulforreadingfilessuchas.cshrcafterchangingthem(2.8).

-44-specialcharacter Seemetacharactersandtheappendixtothismanual. standardWereferoftentothestandardinputandstandardoutputofcommands.See inputandoutput(1.3,3.8). statusAcommandnormallyreturnsastatuswhenitfinishes.Byconventionastatusof zeroindicatesthatthecommandsucceeded.Commandsmayreturnnon-zero statustoindicatethatsomeabnormaleventhasoccurred.Theshellvariable statusissettothestatusreturnedbythelastcommand.Itismostusefulin shellcommmandscripts(3.6). stopThestopcommandcausesabackgroundjobtobecomesuspended(2.6). stringAsequentialgroupofcharacterstakentogetheriscalledastring.Stringscan containanyprintablecharacters(2.2). sttyThesttyprogramchangescertainparametersinsideUNIXwhichdeterminehow yourterminalishandled.See‘stty(1)’foracompletedescription(2.6). substitutionTheshellimplementsanumberofsubstitutionswheresequencesindicatedby metacharactersarereplacedbyothersequences.Notableexamplesofthisare historysubstitutionkeyedbythemetacharacter‘!’andvariablesubstitutionindicatedby‘$’.Wealsorefertosubstitutionsasexpansions(3.4). suspendedAjobbecomessuspendedafteraSTOPsignalissenttoit,eitherbytypingacontrol-zattheterminal(forforegroundjobs)orbyusingthestopcommand(for backgroundjobs).Whensuspended,ajobtemporarilystopsrunninguntilitis restartedbyeitherthefgorbgcommand(2.6). switchTheswitchcommandoftheshellallowstheshelltoselectoneofanumberof sequencesofcommandsbasedonanargumentstring.Itissimilartotheswitch statementinthelanguageC(3.7). terminationWhenacommandwhichisbeingexecutedfinisheswesayitundergoesterminationorterminates.Commandsnormallyterminatewhentheyreadanend-of-file fromtheirstandardinput.Itisalsopossibletoterminatecommandsbysending themaninterruptorquitsignal(1.8).Thekillprogramterminatesspecifiedjobs (2.6). thenThethencommandispartoftheshell’s‘if-then-else-endif’controlconstructused incommandscripts(3.6). timeThetimecommandcanbeusedtomeasuretheamountofCPUandrealtime consumedbyaspecifiedcommandaswellastheamountofdiski/o,memoryutilized,andnumberofpagefaultsandswapstakenbythecommand(2.1,2.8). tsetThetsetprogramisusedtosetstandarderaseandkillcharactersandtotellthe systemwhatkindofterminalyouareusing.Itisofteninvokedina.loginfile (2.1). ttyThewordttyisahistoricalabbreviationfor‘teletype’whichisfrequentlyusedin UNIXtoindicatetheporttowhichagiventerminalisconnected.Thettycommandwillprintthenameofthettyorporttowhichyourterminalispresently connected. unaliasTheunaliascommandremovesaliases(2.8). UNIXUNIXisanoperatingsystemonwhichcshruns.UNIXprovidesfacilitieswhich allowcshtoinvokeotherprogramssuchaseditorsandtextformatterswhichyou maywishtouse. unsetTheunsetcommandremovesthedefinitionsofshellvariables(2.2,2.8). variableexpansion Seevariablesandexpansion(2.2,3.4).

-45-variablesVariablesincshholdoneormorestringsasvalue.Themostcommonuseof variablesisincontrollingthebehavioroftheshell.Seepath,noclobber,and ignoreeofforexamples.Variablessuchasargvarealsousedinwritingshellprograms(shellcommandscripts)(2.2). verboseTheverboseshellvariablecanbesettocausecommandstobeechoedafterthey arehistoryexpanded.Thisisoftenusefulindebuggingshellscripts.Theverbosevariableissetbytheshell’s−vcommandlineoption(3.10). wcThewcprogramcalculatesthenumberofcharacters,words,andlinesinthefiles whosenamesaregivenasarguments(2.6). whileThewhilebuiltincontrolconstructisusedinshellcommandscripts(3.7). wordAsequenceofcharacterswhichformsanargumenttoacommandiscalleda word.Manycharacterswhichareneitherletters,digits,‘−’,‘.’nor‘/’form wordsallbythemselveseveniftheyarenotsurroundedbyblanks.Anysequence ofcharactersmaybemadeintoawordbysurroundingitwith‘´ ’characters exceptforthecharacters‘´ ’and‘!’whichrequirespecialtreatment(1.1).This processofplacingspecialcharactersinwordswithouttheirspecialmeaningis calledquoting. workingdirectory Atanygiventimeyouareinoneparticulardirectory,calledyourworking directory.Thisdirectory’snameisprintedbythepwdcommandandthefiles listedbylsaretheonesinthisdirectory.Youcanchangeworkingdirectories usingchdir. writeThewritecommandisusedtocommunicatewithotheruserswhoareloggedin toUNIX.