UNIXForBeginners—SecondEdition BrianW.Kernighan ABSTRACT ThispaperismeanttohelpnewusersgetstartedontheUNIX◯roperating system.Itincludes: •basicsneededforday-to-dayuseofthesystem—typingcommands,correcting typingmistakes,logginginandout,mail,inter-terminalcommunication,the filesystem,printingfiles,redirectingI/O,pipes,andtheshell. •documentpreparation—abriefdiscussionofthemajorformattingprograms andmacropackages,hintsonpreparingdocuments,andcapsuledescriptions ofsomesupportingsoftware. •UNIXprogramming—usingtheeditor,programmingtheshell,programming inC,otherlanguagesandtools. •AnannotatedUNIXbibliography. 8April1993 UNIXForBeginners—SecondEdition BrianW.Kernighan INTRODUCTION Fromtheuser’spointofview,theUNIXoperatingsystemiseasytolearnanduse,andpresents fewoftheusualimpedimentstogettingthejob done.Itishard,however,forthebeginnerto knowwheretostart,andhowtomakethebest useofthefacilitiesavailable.Thepurposeofthis introductionistohelpnewusersgetusedtothe mainideasoftheUNIXsystemandstartmaking effectiveuseofitquickly. Youshouldhaveacoupleofotherdocuments withyouforeasyreferenceasyoureadthisone. ThemostimportantisTheUNIXProgrammer’s Manual;it’softeneasiertotellyoutoreadabout somethinginthemanualthantorepeatitscontentshere.TheotherusefuldocumentisATutorialIntroductiontotheUNIXTextEditor,which willtellyouhowtousetheeditortogettext— programs,data,documents—intothecomputer. Awordofwarning:theUNIXsystemhas becomequitepopular,andthereareseveralmajor variantsinwidespreaduse.Ofcoursedetailsalso changewithtime.Soalthoughthebasicstructure ofUNIXandhowtouseitiscommontoallversions,therewillcertainlybeafewthingswhich aredifferentonyoursystemfromwhatis describedhere.Wehavetriedtominimizethe problem,butbeawareofit.Incasesofdoubt, thispaperdescribesVersion7UNIX. Thispaperhasfivesections: 1.GettingStarted:Howtologin,howtotype, whattodoaboutmistakesintyping,howto logout.Someofthisisdependentonwhich systemyouloginto(phonenumbers,for example)andwhatterminalyouuse,sothis sectionmustnecessarilybesupplementedby localinformation. 2.Day-to-dayUse:Thingsyouneedeverydayto usethesystemeffectively:generallyuseful commands;thefilesystem. 3.DocumentPreparation:Preparingmanuscriptsisoneofthemostcommonusesfor UNIXsystems.Thissectioncontainsadvice, butnotextensiveinstructionsonanyofthe formattingtools. 4.WritingPrograms:UNIXisanexcellentsystemfordevelopingprograms.Thissection talksaboutsomeofthetools,butagainisnot atutorialinanyoftheprogramminglanguagesprovidedbythesystem. 5.AUNIXReadingList.Anannotatedbibliographyofdocumentsthatnewusersshouldbe awareof. I.GETTINGSTARTED LoggingIn YoumusthaveaUNIXloginname,whichyou cangetfromwhoeveradministersyoursystem. Youalsoneedtoknowthephonenumber,unless yoursystemusespermanentlyconnectedterminals.TheUNIXsystemiscapableofdealingwith awidevarietyofterminals:Terminet300’s;Execuport,TIandsimilarportables;video(CRT)terminalsliketheHP2640,etc.;high-pricedgraphics terminalsliketheTektronix4014;plottingterminalslikethosefromGSIandDASI;andeventhe venerableTeletypeinitsvariousforms.Butnote: UNIXisstronglyorientedtowardsdeviceswith lowercase.Ifyourterminalproducesonlyupper case(e.g.,model33Teletype,somevideoand portableterminals),lifewillbesodifficultthat youshouldlookforanotherterminal. Besuretosettheswitchesappropriatelyon yourdevice.Switchesthatmightneedtobe adjustedincludethespeed,upper/lowercase mode,fullduplex,evenparity,andanyothersthat localwisdomadvises.Establishaconnection usingwhatevermagicisneededforyourterminal; thismayinvolvedialingatelephonecallormerely flippingaswitch.Ineithercase,UNIXshouldtype ‘‘login:’’atyou.Ifittypesgarbage,youmaybe atthewrongspeed;checktheswitches.Ifthat fails,pushthe‘‘break’’or‘‘interrupt’’keyafew times,slowly.Ifthatfailstoproducealoginmessage,consultaguru. Whenyougetalogin:message,typeyour loginnameinlowercase.FollowitbyaRETURN; thesystemwillnotdoanythinguntilyoutypea RETURN.Ifapasswordisrequired,youwillbe askedforit,and(ifpossible)printingwillbe turnedoffwhileyoutypeit.Don’tforget RETURN. Theculminationofyourlogineffortsisa ‘‘promptcharacter,’’asinglecharacterthatindicatesthatthesystemisreadytoacceptcommands fromyou.Thepromptcharacterisusuallya -2-dollarsign$orapercentsign%.(Youmayalso getamessageofthedayjustbeforetheprompt character,oranotificationthatyouhavemail.) TypingCommands Onceyou’veseenthepromptcharacter,you cantypecommands,whicharerequeststhatthe systemdosomething.Trytyping date followedbyRETURN.Youshouldgetbacksomethinglike MonJan1614:17:10EST1978 Don’tforgettheRETURNafterthecommand,or nothingwillhappen.Ifyouthinkyou’rebeing ignored,typeaRETURN;somethingshouldhappen.RETURNwon’tbementionedagain,but don’tforgetit—ithastobethereattheendof eachline. Anothercommandyoumighttryiswho, whichtellsyoueveryonewhoiscurrentlylogged in: who givessomethinglike mbtty01Jan1609:11 skitty05Jan1609:33 gamtty11Jan1613:07 Thetimeiswhentheuserloggedin;‘‘ttyxx’’isthe system’sideaofwhatterminaltheuserison. Ifyoumakeamistaketypingthecommand name,andrefertoanon-existentcommand,you willbetold.Forexample,ifyoutype whom youwillbetold whom:notfound Ofcourse,ifyouinadvertentlytypethenameof someothercommand,itwillrun,withmoreorless mysteriousresults. StrangeTerminalBehavior Sometimesyoucangetintoastatewhere yourterminalactsstrangely.Forexample,each lettermaybetypedtwice,ortheRETURNmay notcausealinefeedorareturntotheleftmargin. Youcanoftenfixthisbyloggingoutandlogging backin.Oryoucanreadthedescriptionofthe commandsttyinsectionIofthemanual.Toget intelligenttreatmentoftabcharacters(whichare muchusedinUNIX)ifyourterminaldoesn’thave tabs,typethecommand stty−tabs andthesystemwillconverteachtabintotheright numberofblanksforyou.Ifyourterminaldoes havecomputer-settabletabs,thecommandtabs willsetthestopscorrectlyforyou. MistakesinTyping Ifyoumakeatypingmistake,andseeit beforeRETURNhasbeentyped,therearetwo waystorecover.Thesharp-character#erasesthe lastcharactertyped;infactsuccessiveusesof# erasecharactersbacktothebeginningoftheline (butnotbeyond).Soifyoutypebadly,youcan correctasyougo: dd#atte##e isthesameasdate. Theat-sign@erasesallofthecharacters typedsofaronthecurrentinputline,soiftheline isirretrievablyfouledup,typean@andstartthe lineover. Whatifyoumustenterasharporat-signas partofthetext?Ifyouprecedeeither#or@by abackslash\,itlosesitserasemeaning.Soto enterasharporat-signinsomething,type\#or \@.Thesystemwillalwaysechoanewlineatyou afteryourat-sign,evenifprecededbyabackslash. Don’tworry—theat-signhasbeenrecorded. Toeraseabackslash,youhavetotypetwo sharpsortwoat-signs,asin\##.Thebackslash isusedextensivelyinUNIXtoindicatethatthe followingcharacterisinsomewayspecial. Read-ahead UNIXhasfullread-ahead,whichmeansthat youcantypeasfastasyouwant,wheneveryou want,evenwhensomecommandistypingatyou. Ifyoutypeduringoutput,yourinputcharacters willappearintermixedwiththeoutputcharacters, buttheywillbestoredawayandinterpretedin thecorrectorder.Soyoucantypeseveralcommandsoneafteranotherwithoutwaitingforthe firsttofinishorevenbegin. StoppingaProgram Youcanstopmostprogramsbytypingthe character‘‘DEL’’(perhapscalled‘‘delete’’or ‘‘rubout’’onyourterminal).The‘‘interrupt’’or ‘‘break’’keyfoundonmostterminalscanalsobe used.Inafewprograms,likethetexteditor,DEL stopswhatevertheprogramisdoingbutleaves youinthatprogram.Hangingupthephonewill stopmostprograms. LoggingOut Theeasiestwaytologoutistohangupthe phone.Youcanalsotype −3− login andletsomeoneelseusetheterminalyouwereon. Itisusuallynotsufficientjusttoturnofftheterminal.MostUNIXsystemsdonotuseatime-out mechanism,soyou’llbethereforeverunlessyou hangup. Mail Whenyoulogin,youmaysometimesgetthe message Youhavemail. UNIXprovidesapostalsystemsoyoucancommunicatewithotherusersofthesystem.Toread yourmail,typethecommand mail Yourmailwillbeprinted,onemessageatatime, mostrecentmessagefirst.Aftereachmessage, mailwaitsforyoutosaywhattodowithit.The twobasicresponsesared,whichdeletesthemessage,andRETURN,whichdoesnot(soitwillstill betherethenexttimeyoureadyourmailbox). Otherresponsesaredescribedinthemanual. (Earlierversionsofmaildonotprocessonemessageatatime,butareotherwisesimilar.) Howdoyousendmailtosomeoneelse?Supposeitistogoto‘‘joe’’(assuming‘‘joe’’issomeone’sloginname).Theeasiestwayisthis: mailjoe nowtypeinthetextoftheletter onasmanylinesasyoulike... Afterthelastlineoftheletter typethecharacter‘‘control−d’’, thatis,holddown‘‘control’’andtype aletter‘‘d’’. Andthat’sit.The‘‘control-d’’sequence,often called‘‘EOF’’forend-of-file,isusedthroughout thesystemtomarktheendofinputfromaterminal,soyoumightaswellgetusedtoit. Forpractice,sendmailtoyourself.(Thisisn’t asstrangeasitmightsound—mailtooneselfisa handyremindermechanism.) Thereareotherwaystosendmail—youcan sendapreviouslypreparedletter,andyoucan mailtoanumberofpeopleallatonce.Formore detailsseemail(1).(Thenotationmail(1)means thecommandmailinsection1oftheUNIX Programmer’sManual.) Writingtootherusers Atsomepoint,outofthebluewillcomea messagelike Messagefromjoetty07... accompaniedbyastartlingbeep.Itmeansthat Joewantstotalktoyou,butunlessyoutake explicitactionyouwon’tbeabletotalkback.To respond,typethecommand writejoe Thisestablishesatwo-waycommunicationpath. NowwhateverJoetypesonhisterminalwill appearonyoursandviceversa.Thepathisslow, ratherliketalkingtothemoon.(Ifyouareinthe middleofsomething,youhavetogettoastate whereyoucantypeacommand.Normally,whateverprogramyouarerunninghastoterminateor beterminated.Ifyou’reediting,youcanescape temporarilyfromtheeditor—readtheeditor tutorial.) Aprotocolisneededtokeepwhatyoutype fromgettinggarbledupwithwhatJoetypes. Typicallyit’slikethis: Joetypeswritesmithandwaits. Smithtypeswritejoeandwaits. Joenowtypeshismessage(asmanylines ashelikes).Whenhe’sreadyforareply, hesignalsitbytyping(o),whichstands for‘‘over’’. NowSmithtypesareply,alsoterminated by(o). Thiscyclerepeatsuntilsomeonegetstired; hethensignalshisintenttoquitwith(oo), for‘‘overandout’’. Toterminatetheconversation,eachside musttypea‘‘control-d’’characteraloneon aline.(‘‘Delete’’alsoworks.)Whenthe otherpersontypeshis‘‘control-d’’,youwill getthemessageEOFonyourterminal. Ifyouwritetosomeonewhoisn’tloggedin,or whodoesn’twanttobedisturbed,you’llbetold. Ifthetargetisloggedinbutdoesn’tansweraftera decentinterval,simplytype‘‘control-d’’. On-lineManual TheUNIXProgrammer’sManualistypically kepton-line.Ifyougetstuckonsomething,and can’tfindanexperttoassistyou,youcanprinton yourterminalsomemanualsectionthatmight help.Thisisalsousefulforgettingthemostupto-dateinformationonacommand.Toprinta manualsection,type‘‘mancommand-name’’. Thustoreaduponthewhocommand,type manwho and,ofcourse, manman tellsallaboutthemancommand.

-4-ComputerAidedInstruction YourUNIXsystemmayhaveavailableaprogramcalledlearn,whichprovidescomputeraided instructiononthefilesystemandbasiccommands, theeditor,documentpreparation,andevenCprogramming.Trytypingthecommand learn Iflearnexistsonyoursystem,itwilltellyou whattodofromthere. II.DAY-TO-DAYUSE CreatingFiles—TheEditor Ifyouhavetotypeapaperoraletterora program,howdoyougettheinformationstoredin themachine?Mostofthesetasksaredonewith theUNIX‘‘texteditor’’ed.Sinceedisthoroughly documentedined(1)andexplainedinATutorial IntroductiontotheUNIXTextEditor,wewon’t spendanytimeheredescribinghowtouseit.All wewantitforrightnowistomakesomefiles.(A fileisjustacollectionofinformationstoredinthe machine,asimplisticbutadequatedefinition.) Tocreateafilecalledjunkwithsometextin it,dothefollowing: edjunk(invokesthetexteditor) a(commandto‘‘ed’’,toaddtext) nowtypein whatevertextyouwant... .(signalstheendofaddingtext) The‘‘.’’thatsignalstheendofaddingtextmust beatthebeginningofalinebyitself.Don’tforgetit,foruntilitistyped,nootheredcommands willberecognized—everythingyoutypewillbe treatedastexttobeadded. Atthispointyoucandovariouseditingoperationsonthetextyoutypedin,suchascorrecting spellingmistakes,rearrangingparagraphsandthe like.Finally,youmustwritetheinformationyou havetypedintoafilewiththeeditorcommandw: w edwillrespondwiththenumberofcharactersit wroteintothefilejunk. Untilthewcommand,nothingisstoredpermanently,soifyouhangupandgohomethe informationislost.†Butafterwtheinformation istherepermanently;youcanre-accessitanytime bytyping †Thisisnotstrictlytrue—ifyouhangup whileediting,thedatayouwereworkingonis savedinafilecalleded.hup,whichyoucan continuewithatyournextsession. edjunk Typeaqcommandtoquittheeditor.(Ifyoutry toquitwithoutwriting,edwillprinta?to remindyou.Asecondqgetsyououtregardless.) Nowcreateasecondfilecalledtempinthe samemanner.Youshouldnowhavetwofiles, junkandtemp. Whatfilesareoutthere? Thels(for‘‘list’’)commandliststhenames (notcontents)ofanyofthefilesthatUNIXknows about.Ifyoutype ls theresponsewillbe junk temp whichareindeedthetwofilesjustcreated.The namesaresortedintoalphabeticalorderautomatically,butothervariationsarepossible.Forexample,thecommand ls−t causesthefilestobelistedintheorderinwhich theywerelastchanged,mostrecentfirst.The−l optiongivesa‘‘long’’listing: ls−l willproducesomethinglike −rw−rw−rw−1bwk41Jul222:56junk −rw−rw−rw−1bwk78Jul222:57temp Thedateandtimeareofthelastchangetothe file.The41and78arethenumberofcharacters (whichshouldagreewiththenumbersyougot fromed).bwkistheownerofthefile,thatis,the personwhocreatedit.The−rw−rw−rw−tells whohaspermissiontoreadandwritethefile,in thiscaseeveryone. Optionscanbecombined:ls−ltgivesthe samethingasls−l,butsortedintotimeorder. Youcanalsonamethefilesyou’reinterestedin, andlswilllisttheinformationaboutthemonly. Moredetailscanbefoundinls(1). Theuseofoptionalargumentsthatbegin withaminussign,like−tand−lt,isacommon conventionforUNIXprograms.Ingeneral,ifa programacceptssuchoptionalarguments,they precedeanyfilenamearguments.Itisalsovital thatyouseparatethevariousargumentswith spaces:ls−lisnotthesameasls−l. PrintingFiles Nowthatyou’vegotafileoftext,howdoyou printitsopeoplecanlookatit?Thereareahost ofprogramsthatdothat,probablymorethanare -5-needed. Onesimplethingistousetheeditor,since printingisoftendonejustbeforemakingchanges anyway.Youcansay edjunk 1,$p edwillreplywiththecountofthecharactersin junkandthenprintallthelinesinthefile.After youlearnhowtousetheeditor,youcanbeselectiveaboutthepartsyouprint. Therearetimeswhenit’snotfeasibletouse theeditorforprinting.Forexample,thereisa limitonhowbigafileedcanhandle(several thousandlines).Secondly,itwillonlyprintone fileatatime,andsometimesyouwanttoprint several,oneafteranother.Sohereareacoupleof alternatives. Firstiscat,thesimplestofalltheprinting programs.catsimplyprintsontheterminalthe contentsofallthefilesnamedinalist.Thus catjunk printsonefile,and catjunktemp printstwo.Thefilesaresimplyconcatenated (hencethename‘‘cat’’)ontotheterminal. prproducesformattedprintoutsoffiles.As withcat,prprintsallthefilesnamedinalist. Thedifferenceisthatitproducesheadingswith date,time,pagenumberandfilenameatthetop ofeachpage,andextralinestoskipoverthefold inthepaper.Thus, prjunktemp willprintjunkneatly,thenskiptothetopofa newpageandprinttempneatly. prcanalsoproducemulti-columnoutput: pr−3junk printsjunkin3-columnformat.Youcanuseany reasonablenumberinplaceof‘‘3’’andprwilldo itsbest.prhasothercapabilitiesaswell;see pr(1). Itshouldbenotedthatprisnotaformatting programinthesenseofshufflinglinesaroundand justifyingmargins.Thetrueformattersarenroff andtroff,whichwewillgettointhesectionon documentpreparation. Therearealsoprogramsthatprintfilesona high-speedprinter.Lookinyourmanualunder oprandlpr.Whichtousedependsonwhat equipmentisattachedtoyourmachine.

ShufflingFilesAbout Nowthatyouhavesomefilesinthefilesystemandsomeexperienceinprintingthem,you cantrybiggerthings.Forexample,youcanmove afilefromoneplacetoanother(whichamountsto givingitanewname),likethis: mvjunkprecious Thismeansthatwhatusedtobe‘‘junk’’isnow ‘‘precious’’.Ifyoudoanlscommandnow,you willget precious temp Bewarethatifyoumoveafiletoanotheronethat alreadyexists,thealreadyexistingcontentsare lostforever. Ifyouwanttomakeacopyofafile(thatis, tohavetwoversionsofsomething),youcanuse thecpcommand: cpprecioustemp1 makesaduplicatecopyofpreciousintemp1. Finally,whenyougettiredofcreatingand movingfiles,thereisacommandtoremovefiles fromthefilesystem,calledrm. rmtemptemp1 willremovebothofthefilesnamed. Youwillgetawarningmessageifoneofthe namedfileswasn’tthere,butotherwiserm,like mostUNIXcommands,doesitsworksilently. Thereisnopromptingorchatter,anderrormessagesareoccasionallycurt.Thistersenessis sometimesdisconcertingtonewcomers,butexperiencedusersfinditdesirable. What’sinaFilename Sofarwehaveusedfilenameswithoutever sayingwhat’salegalname,soit’stimeforacoupleofrules.First,filenamesarelimitedto14 characters,whichisenoughtobedescriptive.Second,althoughyoucanusealmostanycharacterin afilename,commonsensesaysyoushouldstickto onesthatarevisible,andthatyoushouldprobably avoidcharactersthatmightbeusedwithother meanings.Wehavealreadyseen,forexample, thatinthelscommand,ls−tmeanstolistin timeorder.Soifyouhadafilewhosenamewas −t,youwouldhaveatoughtimelistingitby name.Besidestheminussign,thereareother characterswhichhavespecialmeaning.Toavoid pitfalls,youwoulddowelltouseonlyletters, numbersandtheperioduntilyou’refamiliarwith thesituation. Ontosomemorepositivesuggestions.Supposeyou’retypingalargedocumentlikeabook.

-6-Logicallythisdividesintomanysmallpieces,like chaptersandperhapssections.Physicallyitmust bedividedtoo,foredwillnothandlereallybig files.Thusyoushouldtypethedocumentasa numberoffiles.Youmighthaveaseparatefilefor eachchapter,called chap1 chap2 etc... Or,ifeachchapterwerebrokenintoseveralfiles, youmighthave chap1.1 chap1.2 chap1.3 ... chap2.1 chap2.2 ... Youcannowtellataglancewhereaparticularfile fitsintothewhole. Thereareadvantagestoasystematicnaming conventionwhicharenotobvioustothenovice UNIXuser.Whatifyouwantedtoprintthewhole book?Youcouldsay prchap1.1chap1.2chap1.3...... butyouwouldgettiredprettyfast,andwould probablyevenmakemistakes.Fortunately,there isashortcut.Youcansay prchap* The*means‘‘anythingatall,’’sothistranslates into‘‘printallfileswhosenamesbeginwithchap’’, listedinalphabeticalorder. Thisshorthandnotationisnotapropertyof theprcommand,bytheway.Itissystem-wide,a serviceoftheprogramthatinterpretscommands (the‘‘shell,’’sh(1)).Usingthatfact,youcansee howtolistthenamesofthefilesinthebook: lschap* produces chap1.1 chap1.2 chap1.3 ... The*isnotlimitedtothelastpositioninafilename—itcanbeanywhereandcanoccurseveral times.Thus rm*junk**temp* removesallfilesthatcontainjunkortempasany partoftheirname.Asaspecialcase,*byitself matcheseveryfilename,so pr* printsallyourfiles(alphabeticalorder),and rm* removesallfiles.(Youhadbetterbeverysure that’swhatyouwantedtosay!) The*isnottheonlypattern-matchingfea-tureavailable.Supposeyouwanttoprintonly chapters1through4and9.Thenyoucansay prchap[12349]* The[...]meanstomatchanyofthecharacters insidethebrackets.Arangeofconsecutiveletters ordigitscanbeabbreviated,soyoucanalsodo thiswith prchap[1−49]* Letterscanalsobeusedwithinbrackets:[a−z] matchesanycharacterintherangeathroughz. The?patternmatchesanysinglecharacter, so ls? listsallfileswhichhavesingle-characternames, and ls−lchap?.1 listsinformationaboutthefirstfileofeachchapter (chap1.1,chap2.1,etc.). Oftheseniceties,*iscertainlythemostuseful,andyoushouldgetusedtoit.Theothersare frills,butworthknowing. Ifyoushouldeverhavetoturnoffthespecial meaningof*,?,etc.,enclosetheentireargument insinglequotes,asin ls′?′ We’llseesomemoreexamplesofthisshortly. What’sinaFilename,Continued Whenyoufirstmadethatfilecalledjunk, howdidthesystemknowthattherewasn’t anotherjunksomewhereelse,especiallysincethe personinthenextofficeisalsoreadingthistutorial?Theansweristhatgenerallyeachuserhasa privatedirectory,whichcontainsonlythefilesthat belongtohim.Whenyoulogin,youare‘‘in’’ yourdirectory.Unlessyoutakespecialaction, whenyoucreateanewfile,itismadeinthedirectorythatyouarecurrentlyin;thisismostoften yourowndirectory,andthusthefileisunrelated toanyotherfileofthesamenamethatmightexist insomeoneelse’sdirectory. Thesetofallfilesisorganizedintoa(usually big)tree,withyourfileslocatedseveralbranches intothetree.Itispossibleforyouto‘‘walk’’ -7-aroundthistree,andtofindanyfileinthesystem, bystartingattherootofthetreeandwalking alongthepropersetofbranches.Conversely,you canstartwhereyouareandwalktowardtheroot. Let’strythelatterfirst.Thebasictoolsis thecommandpwd(‘‘printworkingdirectory’’), whichprintsthenameofthedirectoryyouare currentlyin. Althoughthedetailswillvaryaccordingto thesystemyouareon,ifyougivethecommand pwd,itwillprintsomethinglike /usr/your-name Thissaysthatyouarecurrentlyinthedirectory your-name,whichisinturninthedirectory /usr,whichisinturnintherootdirectorycalled byconventionjust/.(Evenifit’snotcalled/usr onyoursystem,youwillgetsomethinganalogous. Makethecorrespondingchangesandreadon.) Ifyounowtype ls/usr/your-name youshouldgetexactlythesamelistoffilenames asyougetfromaplainls:withnoarguments,ls liststhecontentsofthecurrentdirectory;given thenameofadirectory,itliststhecontentsof thatdirectory. Next,try ls/usr Thisshouldprintalongseriesofnames,among whichisyourownloginnameyour-name.On manysystems,usrisadirectorythatcontainsthe directoriesofallthenormalusersofthesystem, likeyou. Thenextstepistotry ls/ Youshouldgetaresponsesomethinglikethis (althoughagainthedetailsmaybedifferent): bin dev etc lib tmp usr Thisisacollectionofthebasicdirectoriesoffiles thatthesystemknowsabout;weareattherootof thetree. Nowtry cat/usr/your-name/junk (ifjunkisstillaroundinyourdirectory).The name /usr/your-name/junk iscalledthepathnameofthefilethatyounormallythinkofas‘‘junk’’.‘‘Pathname’’hasan obviousmeaning:itrepresentsthefullnameofthe pathyouhavetofollowfromtherootthroughthe treeofdirectoriestogettoaparticularfile.Itisa universalruleintheUNIXsystemthatanywhere youcanuseanordinaryfilename,youcanusea pathname. Hereisapicturewhichmaymakethisclearer: (root) /|\ /|\ /|\ binetcusrdevtmp /|\/|\/|\/|\/|\ /|\ /|\ adamevemary //\\ /\junk junktemp NoticethatMary’sjunkisunrelatedtoEve’s. Thisisn’ttooexcitingifallthefilesofinterest areinyourowndirectory,butifyouworkwith someoneelseoronseveralprojectsconcurrently,it becomeshandyindeed.Forexample,yourfriends canprintyourbookbysaying pr/usr/your-name/chap* Similarly,youcanfindoutwhatfilesyourneighborhasbysaying ls/usr/neighbor-name ormakeyourowncopyofoneofhisfilesby cp/usr/your-neighbor/his-fileyourfile Ifyourneighbordoesn’twantyoupoking aroundinhisfiles,orviceversa,privacycanbe arranged.Eachfileanddirectoryhasread-write-executepermissionsfortheowner,agroup,and everyoneelse,whichcanbesettocontrolaccess. Seels(1)andchmod(1)fordetails.Asamatter ofobservedfact,mostusersmostofthetimefind opennessofmorebenefitthanprivacy. Asafinalexperimentwithpathnames,try ls/bin/usr/bin Dosomeofthenameslookfamiliar?Whenyou runaprogram,bytypingitsnameafterthe promptcharacter,thesystemsimplylooksfora fileofthatname.Itnormallylooksfirstinyour directory(whereittypicallydoesn’tfindit),then in/binandfinallyin/usr/bin.Thereisnothing magicaboutcommandslikecatorls,exceptthat theyhavebeencollectedintoacoupleofplacesto beeasytofindandadminister.

-8-Whatifyouworkregularlywithsomeoneelse oncommoninformationinhisdirectory?You couldjustloginasyourfriendeachtimeyouwant to,butyoucanalsosay‘‘Iwanttoworkonhis filesinsteadofmyown’’.Thisisdonebychanging thedirectorythatyouarecurrentlyin: cd/usr/your-friend (Onsomesystems,cdisspelledchdir.)Now whenyouuseafilenameinsomethinglikecator pr,itreferstothefileinyourfriend’sdirectory. Changingdirectoriesdoesn’taffectanypermissions associatedwithafile—ifyoucouldn’taccessa filefromyourowndirectory,changingtoanother directorywon’talterthatfact.Ofcourse,ifyou forgetwhatdirectoryyou’rein,type pwd tofindout. Itisusuallyconvenienttoarrangeyourown filessothatallthefilesrelatedtoonethingarein adirectoryseparatefromotherprojects.For example,whenyouwriteyourbook,youmight wanttokeepallthetextinadirectorycalled book.Somakeonewith mkdirbook thengotoitwith cdbook thenstarttypingchapters.Thebookisnowfound in(presumably) /usr/your-name/book Toremovethedirectorybook,type rmbook/* rmdirbook Thefirstcommandremovesallfilesfromthedirectory;thesecondremovestheemptydirectory. Youcangouponelevelinthetreeoffilesby saying cd.. ‘‘..’’isthenameoftheparentofwhateverdirectoryyouarecurrentlyin.Forcompleteness,‘‘.’’is analternatenameforthedirectoryyouarein. UsingFilesinsteadoftheTerminal Mostofthecommandswehaveseensofar produceoutputontheterminal;some,liketheeditor,alsotaketheirinputfromtheterminal.Itis universalinUNIXsystemsthattheterminalcan bereplacedbyafileforeitherorbothofinput andoutput.Asoneexample, ls makesalistoffilesonyourterminal.Butifyou say ls>filelist alistofyourfileswillbeplacedinthefilefilelist (whichwillbecreatedifitdoesn’talreadyexist,or overwrittenifitdoes).Thesymbol>means‘‘put theoutputonthefollowingfile,ratherthanonthe terminal.’’Nothingisproducedontheterminal. Asanotherexample,youcouldcombineseveral filesintoonebycapturingtheoutputofcatina file: catf1f2f3>temp Thesymbol>>operatesverymuchlike> does,exceptthatitmeans‘‘addtotheendof.’’ Thatis, catf1f2f3>>temp meanstoconcatenatef1,f2andf3totheendof whateverisalreadyintemp,insteadofoverwritingtheexistingcontents.Aswith>,iftemp doesn’texist,itwillbecreatedforyou. Inasimilarway,thesymbol<meanstotake theinputforaprogramfromthefollowingfile, insteadoffromtheterminal.Thus,youcould makeupascriptofcommonlyusededitingcommandsandputthemintoafilecalledscript. Thenyoucanrunthescriptonafilebysaying edfile<script Asanotherexample,youcanuseedtopreparea letterinfilelet,thensendittoseveralpeople with mailadamevemaryjoe<let Pipes OneofthenovelcontributionsoftheUNIX systemistheideaofapipe.Apipeissimplya waytoconnecttheoutputofoneprogramtothe inputofanotherprogram,sothetworunasa sequenceofprocesses—apipeline. Forexample, prfgh willprintthefilesf,g,andh,beginningeachona newpage.Supposeyouwantthemruntogether instead.Youcouldsay catfgh>temp pr<temp rmtemp butthisismoreworkthannecessary.Clearly whatwewantistotaketheoutputofcatand connectittotheinputofpr.Soletususeapipe: catfgh|pr −9− Theverticalbar|meanstotaketheoutputfrom cat,whichwouldnormallyhavegonetotheterminal,andputitintoprtobeneatlyformatted. Therearemanyotherexamplesofpipes.For example, ls|pr−3 printsalistofyourfilesinthreecolumns.The programwccountsthenumberoflines,wordsand charactersinitsinput,andaswesawearlier,who printsalistofcurrently-loggedonpeople,oneper line.Thus who|wc tellshowmanypeopleareloggedon.Andof course ls|wc countsyourfiles. Anyprogramthatreadsfromtheterminal canreadfromapipeinstead;anyprogramthat writesontheterminalcandriveapipe.Youcan haveasmanyelementsinapipelineasyouwish. ManyUNIXprogramsarewrittensothatthey willtaketheirinputfromoneormorefilesiffile argumentsaregiven;ifnoargumentsaregiven theywillreadfromtheterminal,andthuscanbe usedinpipelines.prisoneexample: pr−3abc printsfilesa,bandcinorderinthreecolumns. Butin catabc|pr−3 prprintstheinformationcomingdownthe pipeline,stillinthreecolumns. TheShell Wehavealreadymentionedonceortwicethe mysterious‘‘shell,’’whichisinfactsh(1).The shellistheprogramthatinterpretswhatyoutype ascommandsandarguments.Italsolooksafter translating*,etc.,intolistsoffilenames,and<, >,and|intochangesofinputandoutputstreams. Theshellhasothercapabilitiestoo.For example,youcanruntwoprogramswithonecommandlinebyseparatingthecommandswitha semicolon;theshellrecognizesthesemicolonand breaksthelineintotwocommands.Thus date;who doesbothcommandsbeforereturningwitha promptcharacter. Youcanalsohavemorethanoneprogram runningsimultaneouslyifyouwish.Forexample, ifyouaredoingsomethingtime-consuming,like theeditorscriptofanearliersection,andyou don’twanttowaitaroundfortheresultsbefore startingsomethingelse,youcansay edfile<script& Theampersandattheendofacommandlinesays ‘‘startthiscommandrunning,thentakefurther commandsfromtheterminalimmediately,’’that is,don’twaitforittocomplete.Thusthescript willbegin,butyoucandosomethingelseatthe sametime.Ofcourse,tokeeptheoutputfrom interferingwithwhatyou’redoingontheterminal, itwouldbebettertosay edfile<script>script.out& whichsavestheoutputlinesinafilecalled script.out. Whenyouinitiateacommandwith&,the systemreplieswithanumbercalledtheprocess number,whichidentifiesthecommandincaseyou laterwanttostopit.Ifyoudo,youcansay killprocess-number Ifyouforgettheprocessnumber,thecommandps willtellyouabouteverythingyouhaverunning. (Ifyouaredesperate,kill0willkillallyourprocesses.)Andifyou’recuriousaboutotherpeople, psawilltellyouaboutallprogramsthatarecurrentlyrunning. Youcansay (command-1;command-2;command-3)& tostartthreecommandsinthebackground,oryou canstartabackgroundpipelinewith command-1|command-2& Justasyoucantelltheeditororsomesimilar programtotakeitsinputfromafileinsteadof fromtheterminal,youcantelltheshelltoreada filetogetcommands.(Whynot?Theshell,after all,isjustaprogram,albeitacleverone.)For instance,supposeyouwanttosettabsonyourterminal,andfindoutthedateandwho’sonthesystemeverytimeyoulogin.Thenyoucanputthe threenecessarycommands(tabs,date,who)into afile,let’scallitstartup,andthenrunitwith shstartup Thissaystoruntheshellwiththefilestartupas input.Theeffectisasifyouhadtypedthecontentsofstartupontheterminal. Ifthisistobearegularthing,youcaneliminatetheneedtotypesh:simplytype,onceonly, thecommand chmod+xstartup andthereafteryouneedonlysay −10− startup torunthesequenceofcommands.Thechmod(1) commandmarksthefileexecutable;theshellrecognizesthisandrunsitasasequenceofcommands. Ifyouwantstartuptorunautomatically everytimeyoulogin,createafileinyourlogin directorycalled.profile,andplaceinittheline startup.Whentheshellfirstgainscontrolwhen youlogin,itlooksforthe.profilefileanddoes whatevercommandsitfindsinit.We’llgetback totheshellinthesectiononprogramming. III.DOCUMENTPREPARATION UNIXsystemsareusedextensivelyfordocumentpreparation.Therearetwomajorformattingprograms,thatis,programsthatproducea textwithjustifiedrightmargins,automaticpage numberingandtitling,automatichyphenation, andthelike.nroffisdesignedtoproduceoutput onterminalsandline-printers.troff(pronounced ‘‘tee-roff’’)insteaddrivesaphototypesetter,which producesveryhighqualityoutputonphotographic paper.Thispaperwasformattedwithtroff. FormattingPackages Thebasicideaofnroffandtroffisthatthe texttobeformattedcontainswithinit‘‘formatting commands’’thatindicateindetailhowtheformattedtextistolook.Forexample,theremightbe commandsthatspecifyhowlonglinesare,whether tousesingleordoublespacing,andwhatrunning titlestouseoneachpage. Becausenroffandtroffarerelativelyhardto learntouseeffectively,several‘‘packages’’of cannedformattingrequestsareavailabletoletyou specifyparagraphs,runningtitles,footnotes, multi-columnoutput,andsoon,withlittleeffort andwithouthavingtolearnnroffandtroff. Thesepackagestakeamodestefforttolearn,but therewardsforusingthemaresogreatthatitis timewellspent. Inthissection,wewillprovideahastylookat the‘‘manuscript’’packageknownas−ms.Formattingrequeststypicallyconsistofaperiodand twoupper-caseletters,suchas.TL,whichisused tointroduceatitle,or.PPtobeginanewparagraph. Adocumentistypedsoitlookssomething likethis:

.TL titleofdocument .AU authorname .SH sectionheading .PP paragraph... .PP anotherparagraph... .SH anothersectionheading .PP etc. Thelinesthatbeginwithaperiodaretheformattingrequests.Forexample,.PPcallsforstarting anewparagraph.Theprecisemeaningof.PP dependsonwhatoutputdeviceisbeingused (typesetterorterminal,forinstance),andonwhat publicationthedocumentwillappearin.For example,−msnormallyassumesthataparagraph isprecededbyaspace(onelineinnroff,1/2linein troff),andthefirstwordisindented.Theserules canbechangedifyoulike,buttheyarechanged bychangingtheinterpretationof.PP,notbyretypingthedocument. Toactuallyproduceadocumentinstandard formatusing−ms,usethecommand troff−msfiles... forthetypesetter,and nroff−msfiles... foraterminal.The−msargumenttellstroffand nrofftousethemanuscriptpackageofformatting requests. Thereareseveralsimilarpackages;checkwith alocalexperttodeterminewhichonesareincommonuseonyourmachine. SupportingTools Inadditiontothebasicformatters,thereisa hostofsupportingprogramsthathelpwithdocumentpreparation.Thelistinthenextfewparagraphsisfarfromcomplete,sobrowsethroughthe manualandcheckwithpeoplearoundyoufor otherpossibilities. eqnandneqnletyouintegratemathematics intothetextofadocument,inaneasy-to-learn languagethatcloselyresemblesthewayyouwould speakitaloud.Forexample,theeqninput sumfromi=0tonxsubi˜ =˜ piover2 producestheoutput ni=0Σxi=π2 -11-Theprogramtblprovidesananalogousser-viceforpreparingtabularmaterial;itdoesallthe computationsnecessarytoaligncomplicated columnswithelementsofvaryingwidths. referpreparesbibliographiccitationsfroma database,inwhateverstyleisdefinedbytheformattingpackage.Itlooksafterallthedetailsof numberingreferencesinsequence,fillinginpage andvolumenumbers,gettingtheauthor’sinitials andthejournalnameright,andsoon. spellandtypodetectpossiblespellingmistakesinadocument.spellworksbycomparing thewordsinyourdocumenttoadictionary,printingthosethatarenotinthedictionary.Itknows enoughaboutEnglishspellingtodetectplurals andthelike,soitdoesaverygoodjob.typo looksforwordswhichare‘‘unusual’’,andprints those.Spellingmistakestendtobemoreunusual, andthusshowupearlywhenthemostunusual wordsareprintedfirst. greplooksthroughasetoffilesforlinesthat containaparticulartextpattern(ratherlikethe editor’scontextsearchdoes,butonabunchof files).Forexample, grep′ing$′chap* willfindalllinesthatendwiththelettersingin thefileschap*.(Itisalmostalwaysagoodpracticetoputsinglequotesaroundthepatternyou’re searchingfor,incaseitcontainscharacterslike* or$thathaveaspecialmeaningtotheshell.) grepisoftenusefulforfindingoutinwhichofa setoffilesthemisspelledwordsdetectedbyspell areactuallylocated. diffprintsalistofthedifferencesbetween twofiles,soyoucancomparetwoversionsofsomethingautomatically(whichcertainlybeatsproofreadingbyhand). wccountsthewords,linesandcharactersina setoffiles.trtranslatescharactersintoother characters;forexampleitwillconvertupperto lowercaseandviceversa.Thistranslatesupper intolower: trA−Za−z<input>output sortsortsfilesinavarietyofways;cref makescross-references;ptxmakesapermuted index(keyword-in-contextlisting).sedprovides manyoftheeditingfacilitiesofed,butcanapply themtoarbitrarilylonginputs.awkprovidesthe abilitytodobothpatternmatchingandnumeric computations,andtoconvenientlyprocessfields withinlines.Theseprogramsareformore advancedusers,andtheyarenotlimitedtodocumentpreparation.Putthemonyourlistofthings tolearnabout.

Mostoftheseprogramsareeitherindependentlydocumented(likeeqnandtbl),oraresufficientlysimplethatthedescriptionintheUNIX Programmer’sManualisadequateexplanation. HintsforPreparingDocuments Mostdocumentsgothroughseveralversions (alwaysmorethanyouexpected)beforetheyare finallyfinished.Accordingly,youshoulddowhateverpossibletomakethejobofchangingthem easy. First,whenyoudothepurelymechanical operationsoftyping,typesothatsubsequenteditingwillbeeasy.Starteachsentenceonanew line.Makelinesshort,andbreaklinesatnatural places,suchasaftercommasandsemicolons, ratherthanrandomly.Sincemostpeoplechange documentsbyrewritingphrasesandadding,deletingandrearrangingsentences,theseprecautions simplifyanyeditingyouhavetodolater. Keeptheindividualfilesofadocumentdown tomodestsize,perhapstentofifteenthousand characters.Largerfileseditmoreslowly,andof courseifyoumakeadumbmistakeit’sbetterto haveclobberedasmallfilethanabigone.Split intofilesatnaturalboundariesinthedocument, forthesamereasonsthatyoustarteachsentence onanewline. Thesecondaspectofmakingchangeeasyisto notcommityourselftoformattingdetailstoo early.Oneoftheadvantagesofformattingpackageslike−msisthattheypermityoutodelay decisionstothelastpossiblemoment.Indeed, untiladocumentisprinted,itisnotevendecided whetheritwillbetypesetorputonalineprinter. Asaruleofthumb,forallbutthemosttrivial jobs,youshouldtypeadocumentintermsofaset ofrequestslike.PP,andthendefinethemappropriately,eitherbyusingoneofthecannedpackages(thebetterway)orbydefiningyourown nroffandtroffcommands.Aslongasyouhave enteredthetextinsomesystematicway,itcan alwaysbecleanedupandre-formattedbyajudi-ciouscombinationofeditingcommandsand requestdefinitions. IV.PROGRAMMING Therewillbenoattemptmadetoteachany oftheprogramminglanguagesavailablebutafew wordsofadviceareinorder.Oneofthereasons whytheUNIXsystemisaproductiveprogramming environmentisthatthereisalreadyarichsetof toolsavailable,andfacilitieslikepipes,I/Oredirection,andthecapabilitiesoftheshelloftenmake itpossibletodoajobbypastingtogetherprogramsthatalreadyexistinsteadofwritingfrom scratch.

-12-TheShell Thepipemechanismletsyoufabricatequite complicatedoperationsoutofsparepartsthat alreadyexist.Forexample,thefirstdraftofthe spellprogramwas(roughly) cat...collectthefiles |tr...puteachwordonanewline |tr...deletepunctuation,etc. |sortintodictionaryorder |uniqdiscardduplicates |commprintwordsintext butnotindictionary Morepieceshavebeenaddedsubsequently,but thisgoesalongwayforsuchasmalleffort. Theeditorcanbemadetodothingsthat wouldnormallyrequirespecialprogramsonother systems.Forexample,tolistthefirstandlast linesofeachofasetoffiles,suchasabook,you couldlaboriouslytype ed echap1.1 1p $p echap1.2 1p $p etc. Butyoucandothejobmuchmoreeasily.One wayistotype lschap*>temp togetthelistoffilenamesintoafile.Thenedit thisfiletomakethenecessaryseriesofediting commands(usingtheglobalcommandsofed), andwriteitintoscript.Nowthecommand ed<script willproducethesameoutputasthelaborious handtyping.Alternately(andmoreeasily),you canusethefactthattheshellwillperformloops, repeatingasetofcommandsoverandoveragain forasetofarguments: foriinchap* do ed$i<script done Thissetstheshellvariableitoeachfilenamein turn,thendoesthecommand.Youcantypethis commandattheterminal,orputitinafilefor laterexecution. ProgrammingtheShell Anoptionoftenoverlookedbynewcomersis thattheshellisitselfaprogramminglanguage, withvariables,controlflow(if-else,while,for, case),subroutines,andinterrupthandling.Since therearemanybuilding-blockprograms,youcan sometimesavoidwritinganewprogrammerelyby piecingtogethersomeofthebuildingblockswith shellcommandfiles. Wewillnotgointoanydetailshere;examples andrulescanbefoundinAnIntroductiontothe UNIXShell,byS.R.Bourne. ProgramminginC Ifyouareundertakinganythingsubstantial,C istheonlyreasonablechoiceofprogramminglanguage:everythingintheUNIXsystemistunedto it.ThesystemitselfiswritteninC,asaremost oftheprogramsthatrunonit.Itisalsoaeasy languagetouseonceyougetstarted.CisintroducedandfullydescribedinTheCProgramming LanguagebyB.W.KernighanandD.M.Ritchie (Prentice-Hall,1978).Severalsectionsoftheman-ualdescribethesysteminterfaces,thatis,howyou doI/Oandsimilarfunctions.ReadUNIXProgrammingformorecomplicatedthings. MostinputandoutputinCisbesthandled withthestandardI/Olibrary,whichprovidesaset ofI/Ofunctionsthatexistincompatibleformon mostmachinesthathaveCcompilers.Ingeneral, it’swisesttoconfinethesysteminteractionsina programtothefacilitiesprovidedbythislibrary. Cprogramsthatdon’tdependtoomuchon specialfeaturesofUNIX(suchaspipes)canbe movedtoothercomputersthathaveCcompilers. Thelistofsuchmachinesgrowsdaily;inaddition totheoriginalPDP-11,itcurrentlyincludesat leastHoneywell6000,IBM370,Interdata8/32, DataGeneralNovaandEclipse,HP2100,Harris /7,VAX11/780,SEL86,andZilogZ80.Callsto thestandardI/Olibrarywillworkonallofthese machines. Thereareanumberofsupportingprograms thatgowithC.lintchecksCprogramsforpotentialportabilityproblems,anddetectserrorssuch asmismatchedargumenttypesanduninitialized variables. Forlargerprograms(anythingwhosesourceis onmorethanonefile)makeallowsyoutospecify thedependenciesamongthesourcefilesandthe processingstepsneededtomakeanewversion;it thenchecksthetimesthatthepieceswerelast changedanddoestheminimalamountofrecompilingtocreateaconsistentupdatedversion. Thedebuggeradbisusefulfordigging throughthedeadbodiesofCprograms,butis ratherhardtolearntouseeffectively.Themost effectivedebuggingtoolisstillcarefulthought, coupledwithjudiciouslyplacedprintstatements. TheCcompilerprovidesalimitedinstrumentationservice,soyoucanfindoutwhereprograms -13-spendtheirtimeandwhatpartsareworthopti-mizing.Compiletheroutineswiththe−poption; afterthetestrun,useproftoprintanexecution profile.Thecommandtimewillgiveyouthe grossrun-timestatisticsofaprogram,butthey arenotsuperaccurateorreproducible. OtherLanguages IfyouhavetouseFortran,therearetwopossibilities.YoumightconsiderRatfor,whichgives youthedecentcontrolstructuresandfree-form inputthatcharacterizeC,yetletsyouwritecode thatisstillportabletootherenvironments.Bear inmindthatUNIXFortrantendstoproducelarge andrelativelyslow-runningprograms.Further-more,supportingsoftwarelikeadb,prof,etc.,are allvirtuallyuselesswithFortranprograms.There mayalsobeaFortran77compileronyoursystem. Ifso,thisisaviablealternativetoRatfor,andhas thenon-trivialadvantagethatitiscompatible withCandrelatedprograms.(TheRatforprocessorandCtoolscanbeusedwithFortran77too.) Ifyourapplicationrequiresyoutotranslatea languageintoasetofactionsoranotherlanguage, youareineffectbuildingacompiler,thoughprobablyasmallone.Inthatcase,youshouldbe usingtheyacccompiler-compiler,whichhelpsyou developacompilerquickly.Thelexlexicalanalyzergeneratordoesthesamejobforthesimpler languagesthatcanbeexpressedasregularexpressions.Itcanbeusedbyitself,orasafrontendto recognizeinputsforayacc-basedprogram.Both yaccandlexrequiresomesophisticationtouse, buttheinitialeffortoflearningthemcanbe repaidmanytimesoverinprogramsthatareeasy tochangelateron. MostUNIXsystemsalsomakeavailableother languages,suchasAlgol68,APL,Basic,Lisp, Pascal,andSnobol.Whethertheseareuseful dependslargelyonthelocalenvironment:ifsomeonecaresaboutthelanguageandhasworkedon it,itmaybeingoodshape.Ifnot,theoddsare strongthatitwillbemoretroublethanit’sworth. V.UNIXREADINGLIST General: K.L.ThompsonandD.M.Ritchie,TheUNIX Programmer’sManual,BellLaboratories,1978. Listscommands,systemroutinesandinterfaces, fileformats,andsomeofthemaintenanceprocedures.Youcan’tlivewithoutthis,althoughyou willprobablyonlyneedtoreadsection1. DocumentsforUsewiththeUNIXTime-sharing System.Volume2oftheProgrammer’sManual. Thiscontainsmoreextensivedescriptionsofmajor commands,andtutorialsandreferencemanuals. Allofthepaperslistedbelowareinit,asare descriptionsofmostoftheprogramsmentioned above. D.M.RitchieandK.L.Thompson,‘‘TheUNIX Time-sharingSystem,’’CACM,July1974.An overviewofthesystem,forpeopleinterestedin operatingsystems.Worthreadingbyanyonewho programs.Containsaremarkablenumberofonesentenceobservationsonhowtodothingsright. TheBellSystemTechnicalJournal(BSTJ)Special IssueonUNIX,July/August,1978,containsmany papersdescribingrecentdevelopments,andsome retrospectivematerial. The2ndInternationalConferenceonSoftware Engineering(October,1976)containsseveral papersdescribingtheuseoftheProgrammer’s Workbench(PWB)versionofUNIX. DocumentPreparation: B.W.Kernighan,‘‘ATutorialIntroductiontothe UNIXTextEditor’’and‘‘AdvancedEditingon UNIX,’’BellLaboratories,1978.Beginnersneed theintroduction;theadvancedmaterialwillhelp yougetthemostoutoftheeditor. M.E.Lesk,‘‘TypingDocumentsonUNIX,’’Bell Laboratories,1978.Describesthe−msmacro package,whichisolatesthenovicefromthe vagariesofnroffandtroff,andtakescareofmost formattingsituations.Ifthisspecificpackageisn’t availableonyoursystem,somethingsimilarprobablyis.Themostlikelyalternativeisthe PWB/UNIXmacropackage−mm;seeyourlocal guruifyouusePWB/UNIX. B.W.KernighanandL.L.Cherry,‘‘ASystemfor TypesettingMathematics,’’BellLaboratories ComputingScienceTech.Rep.17. M.E.Lesk,‘‘Tbl—AProgramtoFormat Tables,’’BellLaboratoriesCSTR49,1976. J.F.Ossanna,Jr.,‘‘NROFF/TROFFUser’sManual,’’BellLaboratoriesCSTR54,1976.troffis thebasicformatterusedby−ms,eqnandtbl. Thereferencemanualisindispensableifyouare goingtowriteormaintaintheseorsimilarprograms.Butstartwith: B.W.Kernighan,‘‘ATROFFTutorial,’’BellLaboratories,1976.Anattempttounraveltheintricaciesoftroff. Programming: B.W.KernighanandD.M.Ritchie,TheCProgrammingLanguage,Prentice-Hall,1978.Con-tainsatutorialintroduction,completediscussions ofalllanguagefeatures,andthereferencemanual. B.W.KernighanandD.M.Ritchie,‘‘UNIXProgramming,’’BellLaboratories,1978.Describes howtointerfacewiththesystemfromCprograms: I/Ocalls,signals,processes.

-14-S.R.Bourne,‘‘AnIntroductiontotheUNIX Shell,’’BellLaboratories,1978.Anintroduction andreferencemanualfortheVersion7shell. Mandatoryreadingifyouintendtomakeeffective useoftheprogrammingpowerofthisshell. S.C.Johnson,‘‘Yacc—YetAnotherCompiler-Compiler,’’BellLaboratoriesCSTR32,1978. M.E.Lesk,‘‘Lex—ALexicalAnalyzerGenerator,’’BellLaboratoriesCSTR39,1975. S.C.Johnson,‘‘Lint,aCProgramChecker,’’Bell LaboratoriesCSTR65,1977. S.I.Feldman,‘‘MAKE—AProgramforMaintainingComputerPrograms,’’BellLaboratories CSTR57,1977. J.F.MaranzanoandS.R.Bourne,‘‘ATutorial IntroductiontoADB,’’BellLaboratoriesCSTR 62,1977.Anintroductiontoapowerfulbutcomplexdebuggingtool. S.I.FeldmanandP.J.Weinberger,‘‘APortable Fortran77Compiler,’’BellLaboratories,1978.A fullFortran77forUNIXsystems.