Unix Beginers
-
Upload
sarojaraju -
Category
Documents
-
view
249 -
download
1
Transcript of Unix Beginers
-
7/31/2019 Unix Beginers
1/173
IntroductiontoUnix
FrankG.Fiamingo
LindaDeBula
LindaCondron
UniversityTechnologyServicesTheOhioStateUniversity
September23,1998
-
7/31/2019 Unix Beginers
2/173
1996-1998UniversityTechnologyServices,TheOhioStateUniversity,BakerSystemsEngineeringBuilding,1971NeilAvenue,Columbus,OH43210.
Allrightsreserved.Redistributionanduse,withorwithoutmodification,arepermittedprovidedthatthefollowingconditionsaremet:
1.Redistributionsmustretaintheabovecopyrightnotice,thislistofconditions,andthefollowingdisclaimer.2.NeitherthenameoftheUniversitynorthenamesofitscontributorsmaybeusedtoendorseorpromoteproductsorservicesderivedfromthisdocumentwithoutspecificpriorwrittenpermission.THISPUBLICATIONISPROVIDED"ASIS"WITHOUTWARRANTYOFANYKIND.THISPUBLICATIONMAYINCLUDETECHNICALINACCURACIESORTYPOGRAPHICALERRORS.
UNIXisaregisteredtrademarkofTheOpenGroup,AT&TisatrademarkofAmericanTelephoneandTelegraph,Inc.
Thispublicationisprovidedasiswithoutwarrantyofanykind.Thispublication
mayincludetechnicalinaccuraciesortypographicalerrors.
CopyrightandURLsrevisedSeptember1998
Theauthorsemailaddressesare:[email protected]@[email protected]
Thisdocumentcanbeobtainedvia:http://wks.uts.ohio-state.edu/unix_course/unix.htmlor
ftp://wks.uts.ohio-state.edu/unix_course/unix_book.ps
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
3/173
TableofContents
1HistoryofUnix..............................................................................72UnixStructure...............................................................................9
2.1TheOperatingSystem..................................................................9
2.2TheFileSystem...........................................................................11
2.3UnixDirectories,FilesandInodes.............................................12
2.4UnixPrograms............................................................................13
3GettingStarted............................................................................14
3.1Loggingin....................................................................................14
3.1.1TerminalType.............................................................14
3.1.2Passwords................................................................
....15
3.1.3Exiting.........................................................................15
3.1.4Identity........................................................................16
3.2UnixCommandLineStructure.................................................16
3.3ControlKeys................................................................................17
3.4stty-terminalcontrol.................................................................17
-
7/31/2019 Unix Beginers
4/173
3.5GettingHelp................................................................................19
3.6DirectoryNavigationandControl.............................................20
3.6.1pwd-printworkingdirectory.....................................21
3.6.2cd-changedirectory...................................................21
3.6.3mkdir-makeadirectory.............................................22
3.6.4rmdir-removedirectory.............................................22
3.6.5ls-listdirectorycontents............................................23
3.7FileMaintenanceCommands....................................................25
3.7.1cp-copyafile.............................................................26
3.7.2mv-moveafile..........................................................26
3.7.3rm-removeafile........................................................27
3.7.4FilePermissions..........................................................27
3.7.5chmod-changefilepermissions.................................28
3.7.6chown-changeownership..........................................29
3.7.7chgrp-changegroup..................................................29
3.8DisplayCommands.....................................................................30
3.8.1echo-echoastatement...............................................30
-
7/31/2019 Unix Beginers
5/173
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
6/173
3.8.2cat-concatenateafile.................................................31
3.8.3more,less,andpg-pagethroughafile......................31
3.8.4head-displaythestartofafile...................................32
3.8.5tail-displaytheendofafile......................................32
4
SystemResources&Printing....................................................33
4.1SystemResources........................................................................33
4.1.1df-summarizediskblockandfileusage....................34
4.1.2du-reportdiskspaceinuse........................................34
4.1.3ps-showstatusofactiveprocesses............................35
4.1.4kill-terminateaprocess.............................................36
4.1.5who-listcurrentusers................................................37
4.1.6whereis-reportprogramlocations............................37
4.1.7which-reportthecommandfound.............................38
4.1.8hostname/uname-nameofmachine...........................38
4.1.9script-recordyourscreenI/O....................................38
4.1.10date-currentdateandtime.........................................40
4.2PrintCommands.........................................................................41
-
7/31/2019 Unix Beginers
7/173
4.2.1lp/lpr-submitaprintjob............................................41
4.2.2lpstat/lpq-checkthestatusofaprintjob...................42
4.2.3cancel/lprm-cancelaprintjob...................................42
4.2.4pr-preparefilesforprinting.......................................43
5Shells............................................................................................45
5.1Built-inCommands.....................................................................46
5.1.1Sh................................................................................46
5.1.2Csh..............................................................................47
5.2EnvironmentVariables..............................................................48
5.3TheBourneShell,sh...................................................................49
5.4TheCShell,csh...........................................................................50
5.5JobControl..................................................................................51
5.6History..........................................................................................52
5.7ChangingyourShell........................................................
...........546SpecialUnixFeatures........................................................
.........55
6.1FileDescriptors...........................................................................55
6.2FileRedirection...........................................................
-
7/31/2019 Unix Beginers
8/173
................55
6.2.1Csh..............................................................................56
6.2.2Sh................................................................................57
6.3OtherSpecialCommandSymbols.............................................58
6.4WildCards...................................................................................587
TextProcessing............................................................................59
7.1RegularExpressionSyntax..................................................
......59
7.2TextProcessingCommands.......................................................61
7.2.1grep.............................................................................61
7.2.2sed...............................................................................65
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
9/173
7.2.3awk,nawk,gawk.........................................................67
8
OtherUsefulCommands............................................................70
8.1WorkingWithFiles....................................................................70
8.1.1cmp-comparefilecontents........................................71
8.1.2diff-differencesinfiles..............................................72
8.1.3cut-selectpartsofaline............................................73
8.1.4paste-mergefiles.......................................................74
8.1.5touch-createafile......................................................76
8.1.6wc-countwordsinafile............................................77
8.1.7ln-linktoanotherfile................................................78
8.1.8sort-sortfilecontents.................................................79
8.1.9tee-copycommandoutput.........................................82
8.1.10uniq-removeduplicatelines......................................84
8.1.11strings-findASCIIstrings.........................................85
8.1.12file-filetype...............................................................86
8.1.13tr-translatecharacters................................................86
-
7/31/2019 Unix Beginers
10/173
8.1.14find-findfiles............................................................89
8.2FileArchiving,CompressionandConversion.........................91
8.2.1FileCompression........................................................91
8.2.2tar-archivefiles.........................................................93
8.2.3uuencode/uudecode-encodeafile.............................94
8.2.4dd-blockcopyandconvert........................................95
8.2.5od-octaldumpofafile..............................................96
8.3RemoteConnections...................................................................98
8.3.1TELNETandFTP-remoteloginandfiletransferprotocols98
8.3.2finger-getinformationaboutusers..........................100
8.3.3Remotecommands....................................................101
9ShellProgramming...................................................................103
9.1ShellScripts...............................................................................103
9.2SettingParameterValues.........................................................103
9.3Quoting......................................................................................104
9.4Variables....................................................................................105
9.5ParameterSubstitution.....................................................
-
7/31/2019 Unix Beginers
11/173
.......107
9.6HereDocument..........................................................................109
9.7InteractiveInput.......................................................................110
9.7.1Sh..............................................................................110
9.7.2Csh............................................................................110
9.8Functions....................................................................................111
9.9ControlCommands...........................................................
........113
9.9.1Conditionalif............................................................113
9.9.1.1Sh........................................................................113
9.9.1.2Csh......................................................................114
9.9.2Conditionalswitchandcase......................................115
9.9.2.1Sh........................................................................115
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
12/173
9.9.2.2Csh......................................................................116
9.9.3forandforeach..........................................................117
9.9.3.1Sh........................................................................117
9.9.3.2Csh......................................................................117
9.9.4while..........................................................................118
9.9.4.1Sh........................................................................118
9.9.4.2Csh......................................................................119
9.9.5until...........................................................................119
9.9.6test.............................................................................120
9.9.7CShellLogicalandRelationalOperators................122
10Editors........................................................................................123
10.1ConfiguringYourviSession....................................................124
10.2ConfiguringYouremacsSession.............................................125
10.3viQuickReferenceGuide........................................................126
10.4emacsQuickReferenceGuide..............................................12711UnixCommandSummary.......................................................128
-
7/31/2019 Unix Beginers
13/173
11.1UnixCommands........................................................................12812AShortUnixBibliography......................................................131
12.1HighlyRecommended...............................................................131
12.2AssortedOthers.........................................................................131
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
14/173
CHAPTER1
HistoryofUnix
1965BellLaboratoriesjoinswithMITandGeneralElectricinthedevelopmenteffortforthenewoperatingsystem,Multics,whichwouldprovidemulti-user,multi-processor,andmulti-level(hierarchical)filesystem,amongitsmanyforward-lookingfeatures.
1969AT&TwasunhappywiththeprogressanddropsoutoftheMulticsproject.SomeoftheBellLabsprogrammerswhohadworkedonthisproject,KenThompson,DennisRitchie,RuddCanaday,andDougMcIlroydesignedandimplementedthefirstversionoftheUnixFileSystemonaPDP-7alongwithafewutilities.ItwasgiventhenameUNIXbyBrianKernighanasapunonMultics.
1970,Jan1timezeroforUNIX
1971ThesystemnowrunsonaPDP-11,with16Kbytesofmemory,including8Kbytesforuser
programsanda512Kbytedisk.ItsfirstrealuseisasatextprocessingtoolforthepatentdepartmentatBellLabs.Thatutilizationjustifiedfurtherresearchanddevelopmentbytheprogramminggroup.UNIXcaughtonamongprogrammersbecauseitwasdesignedwiththesefeatures:
programmersenvironmentsimpleuserinterfacesimpleutilitiesthatcanbecombinedtoperformpowerfulfunctionshierarchicalfilesystemsimpleinterfacetodevicesconsistentwithfileformat
multi-user,multi-processsystemarchitectureindependentandtransparenttotheuser.1973Unixisre-writtenmostlyinC,anewlanguagedevelopedbyDennisRitchie.Beingwritteninthishigh-levellanguagegreatlydecreasedtheeffortneededtoportittonewmachines.
1974ThompsonandRitchiepublishapaperintheCommunicationsoftheACMdescribingthenewUnixOS.ThisgeneratesenthusiasmintheAcademiccommunitywhichseesapotentiallygreatteachingtoolforstudyingprogrammingsystemsdevelopment.SinceAT&Tispreventedfrom
marketingtheproductduetothe1956ConsentDecreetheylicenseittoUniversitiesforeducationalpurposesandtocommercialentities.
1977Therearenowabout500Unixsitesworld-wide.
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
15/173
HistoryofUnix
1980BSD4.1(BerkeleySoftwareDevelopment)1983SunOS,BSD4.2,SysV
1984Therearenowabout100,000Unixsitesrunningonmanydifferenthardwareplatforms,ofvastlydifferentcapabilities.
1988AT&TandSunMicrosystemsjointlydevelopSystemVRelease4(SVR4).ThiswouldlaterbedevelopedintoUnixWareandSolaris2.
1993NovellbuysUNIXfromAT&T1994Novellgivesthename"UNIX"toX/OPEN
1995SantaCruzOperationsbuysUnixWarefromNovell.SantaCruzOperationsandHewlett-Packardannouncethattheywilljointlydevelopa64-bitversionofUnix.
1996InternationalDataCorporationforecaststhatin1997therewillbe3millionUnixsystemsshippedworld-wide.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
16/173
TheOperatingSystem
CHAPTER2UnixStructure
2.1TheOperatingSystemUnixisalayeredoperatingsystem.TheinnermostlayeristhehardwarethatprovidestheservicesfortheOS.Theoperatingsystem,referredtoinUnixasthekernel,interactsdirectlywiththehardwareandprovidestheservicestotheuserprograms.Theseuserprogramsdontneedtoknowanythingaboutthehardware.Theyjustneedtoknowhowtointeractwiththekernelanditsuptothekerneltoprovidethedesiredservice.OneofthebigappealsofUnixtoprogrammershasbeenthatmostwellwrittenuserprogramsareindependentoftheunderlyinghardware,makingthemreadilyportabletonewsystems.
Userprogramsinteractwiththekernelthroughasetofstandardsystemcalls.Thesesystemcallsrequestservicestobeprovidedbythekernel.Suchserviceswouldincludeacces
singafile:openclose,read,write,link,orexecuteafile;startingorupdatingaccountingrecords;changingownershipofafileordirectory;changingtoanewdirectory;creating,suspending,orkillingaprocess;enablingaccesstohardwaredevices;andsettinglimitsonsystemresources.
Unixisamulti-user,multi-taskingoperatingsystem.Youcanhavemanyusersloggedintoasystemsimultaneously,eachrunningmanyprograms.Itsthekernelsjobtokeepeachprocessanduserseparateandtoregulateaccesstosystemhardware,includingcpu,memory,diskandotherI/O
devices.
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
17/173
UnixStructure
FIGURE2.1UnixSystemStructure
HardwareKernelSystemCallsPrograms1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
18/173
TheFileSystem
2.2TheFileSystemTheUnixfilesystemlookslikeaninvertedtreestructure.Youstartwiththerootdirectory,denotedby/,atthetopandworkdownthroughsub-directoriesunderneathit.
FIGURE2.2UnixFileStructure
/
bindevetclibtmpusrhome
shdatecshttyacua0passwdgroupbinliblocalcondronfranklindadb
sourcemailbin
xntptraceroute
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
19/173
UnixStructure
Eachnodeiseitherafileoradirectoryoffiles,wherethelattercancontainotherfilesanddirectories.Youspecifyafileordirectorybyitspathname,eitherthefull,orabsolute,pathnameortheonerelativetoalocation.Thefullpathnamestartswiththeroot,/,andfollowsthebranchesofthefilesystem,eachseparatedby/,untilyoureachthedesiredfile,e.g.:
/home/condron/source/xntp
Arelativepathnamespecifiesthepathrelativetoanother,usuallythecurrentworkingdirectorythatyouareat.Twospecialdirectoryentriesshouldbeintroducednow:
.thecurrentdirectory
..theparentofthecurrentdirectory
SoifImat/home/frankandwishtospecifythepathaboveinarelativefashionIcoulduse:../condron/source/xntp
ThisindicatesthatIshouldfirstgouponedirectorylevel,thencomedownthroughthecondrondirectory,followedbythesourcedirectoryandthentoxntp.
2.3UnixDirectories,FilesandInodesEverydirectoryandfileislistedinitsparentdirectory.Inthecaseoftherootdirectory,thatparentisitself.Adirectoryisafilethatcontainsatablelistingthefilescontainedwithinit,givingfilenamestotheinodenumbersinthelist.Aninodeisaspecialfiledesignedtobereadbythekerneltolearntheinformationabouteachfile.Itspecifiesthepermissionsonthefile,
ownership,dateofcreationandoflastaccessandchange,andthephysicallocationofthedatablocksonthediskcontainingthefile.
Thesystemdoesnotrequireanyparticularstructureforthedatainthefileitself.ThefilecanbeASCIIorbinaryoracombination,andmayrepresenttextdata,ashellscript,compiledobjectcodeforaprogram,directorytable,junk,oranythingyouwouldlike.
Theresnoheader,trailer,labelinformationorEOFcharacteraspartofthefile.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
20/173
UnixPrograms
2.4UnixProgramsAprogram,orcommand,interactswiththekerneltoprovidetheenvironmentandperformthefunctionscalledforbytheuser.Aprogramcanbe:anexecutableshellfile,knownasashellscript;abuilt-inshellcommand;orasourcecompiled,objectcodefile.
Theshellisacommandlineinterpreter.Theuserinteractswiththekernelthroughtheshell.YoucanwriteASCII(text)scriptstobeacteduponbyashell.
Systemprogramsareusuallybinary,havingbeencompiledfromCsourcecode.Thesearelocatedinplaceslike/bin,/usr/bin,/usr/local/bin,/usr/ucb,etc.TheyprovidethefunctionsthatyounormallythinkofwhenyouthinkofUnix.Someofthesearesh,csh,date,who,more,andtherearemanyothers.
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
21/173
GettingStarted
CHAPTER3
GettingStarted
3.1LogginginAfterconnectingwithaUnixsystem,auserispromptedforaloginusername,thenapassword.Theloginusernameistheuser'suniquenameonthesystem.Thepasswordisachangeablecodeknownonlytotheuser.Attheloginprompt,theusershouldentertheusername;atthepasswordprompt,thecurrentpasswordshouldbetyped.
Note:Unixiscasesensitive.Therefore,theloginandpasswordshouldbetypedexactlyasissued;thelogin,atleast,willnormallybeinlowercase.
3.1.1TerminalTypeMostsystemsaresetupsotheuserisbydefaultpromptedforaterminaltype,whichshouldbesettomatchtheterminalinusebeforeproceeding.Mostcomputersworkifyouchoose"
vt100".UsersconnectingusingaSunworkstationmaywanttouse"sun";thoseusinganX-Terminalmaywanttouse"xterms"or"xterm".
TheterminaltypeindicatestotheUnixsystemhowtointeractwiththesessionjustopened.
Shouldyouneedtoresettheterminaltype,enterthecommand:
setenvTERM-ifusingtheC-shell(seeChapter4.)
(Onsomesystems,e.g.MAGNUS,itsalsonecessarytotype"unsetenvTERMCAP".)
-or
TERM=;exportTERM-ifusingtheBourneshell(seeChapter4.)
whereistheterminaltype,suchasvt100,thatyouwouldlikeset.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
22/173
Loggingin
3.1.2PasswordsWhenyouraccountisissued,youwillbegivenaninitialpassword.Itisimportantforsystemandpersonalsecuritythatthepasswordforyouraccountbechangedtosomethingofyourchoosing.Thecommandforchangingapasswordis"passwd".Youwillbeaskedbothforyouroldpasswordandtotypeyournewselectedpasswordtwice.Ifyoumistypeyouroldpasswordordonottypeyournewpasswordthesamewaytwice,thesystemwillindicatethatthepasswordhasnotbeenchanged.
Somesystemadministratorshaveinstalledprogramsthatcheckforappropriatenessofpassword(isitcrypticenoughforreasonablesystemsecurity).Apasswordchangemayberejectedbythisprogram.
Whenchoosingapassword,itisimportantthatitbesomethingthatcouldnotbeguessed--eitherbysomebodyunknowntoyoutryingtobreakin,orbyanacquaintancewhoknowsyou.Suggestionsfor
choosingandusingapasswordfollow:Don'tuseaword(orwords)inanylanguage
useapropername
useinformationthatcanbefoundinyourwallet
useinformationcommonlyknownaboutyou(carlicense,petname,etc)
usecontrolcharacters.Somesystemscan'thandlethem
writeyourpasswordanywhere
evergiveyourpasswordto*anybody*
Douseamixtureofcharactertypes(alphabetic,numeric,special)
useamixtureofuppercaseandlowercase
useatleast6characters
chooseapasswordyoucanremember
changeyourpasswordoften
makesurenobodyislookingoveryourshoulderwhenyouareenteringyourpassword
3.1.3Exiting^D-indicatesendofdatastream;canlogauseroff.Thelatterisdisabledonmanysystems^C-interruptlogout-leavethesystemexit-leavetheshell
-
7/31/2019 Unix Beginers
23/173
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
24/173
GettingStarted
3.1.4IdentityThesystemidentifiesyoubytheuserandgroupnumbers(useridandgroupid,respectively)assignedtoyoubyyoursystemadministrator.Youdontnormallyneedtoknowyouruseridorgroupidasthesystemtranslatesusernameuserid,andgroupnamegroupidautomatically.Youprobablyalreadyknowyourusername;itsthenameyoulogonwith.Thegroupnameisnotasobvious,andindeed,youmaybelongtomorethanonegroup.Yourprimarygroupistheoneassociatedwithyourusernameinthepassworddatabasefile,assetupbyyoursystemadministrator.Similarly,thereisagroupdatabasefilewherethesystemadministratorcanassignyourightstoadditionalgroupsonthesystem.
Intheexamplesbelow%isyourshellprompt;youdonttypethisin.
Youcandetermineyouruseridandthelistofgroupsyoubelongtowiththeidandgroups
commands.Onsomesystemsiddisplaysyouruserandprimarygroupinformation,e.g.:
%iduid=1101(frank)gid=10(staff)
onothersystemsitalsodisplaysinformationforanyadditionalgroupsyoubelongto:
%iduid=1101(frank)gid=10(staff)groups=10(staff),5(operator),14(sysadmin),110(uts)
Thegroupscommanddisplaysthegroupinformationforallthegroupsyoubelongto,e.g.:
%groupsstaffsysadminutsoperator
3.2UnixCommandLineStructureAcommandisaprogramthattellstheUnixsystemtodosomething.Ithastheform:command[options][arguments]
whereanargumentindicatesonwhatthecommandistoperformitsaction,usuallyafileorseriesoffiles.Anoptionmodifiesthecommand,changingthewayitperforms.Commandsarecasesensitive.commandandCommandarenotthesame.Optionsaregenerallyprecededbyahyphen(-),andformostcommands,morethanoneoptioncanbe
strungtogether,intheform:command-[option][option][option]
-
7/31/2019 Unix Beginers
25/173
e.g.:ls-alR
willperformalonglistonallfilesinthecurrentdirectoryandrecursivelyperformthelistthroughallsub-directories.Formostcommandsyoucanseparatetheoptions,precedingeachwithahyphen,e.g.:
command-option1-option2-option3
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
26/173
ControlKeys
asin:
ls-a-l-RSomecommandshaveoptionsthatrequireparameters.Optionsrequiringparametersareusuallyspecifiedseparately,e.g.:
lpr-Pprinter3-#2filewillsend2copiesoffiletoprinter3.
Thesearethestandardconventionsforcommands.However,notallUnixcommandswillfollowthestandard.Somedontrequirethehyphenbeforeoptionsandsomewontletyougroupoptionstogether,i.e.theymayrequirethateachoptionbeprecededbyahyphenandseparatedbywhitespacefromotheroptionsandarguments.
Optionsandsyntaxforacommandarelistedinthemanpageforthecommand.
3.3ControlKeys
Controlkeysareusedtoperformspecialfunctionsonthecommandlineorwithinaneditor.YoutypethesebyholdingdowntheControlkeyandsomeotherkeysimultaneously.Thisisusuallyrepresentedas^Key.Control-Swouldbewrittenas^S.Withcontrolkeysupperandlowercasearethesame,so^Sisthesameas^s.Thisparticularexampleisastopsignalandtellstheterminaltostopacceptinginput.Itwillremainthatwayuntilyoutypeastartsignal,^Q.
Control-Uisnormallythe"line-kill"signalforyourterminal.Whentypediterasestheentireinput
line.
Inthevieditoryoucantypeacontrolkeyintoyourtextfilebyfirsttyping^Vfollowedbythecontrolcharacterdesired,sototype^Hintoadocumenttype^V^H.
3.4stty-terminalcontrolsttyreportsorsetsterminalcontroloptions.The"tty"isanabbreviationthatharksbacktothedaysofteletypewriters,whichwereassociatedwithtransmissionoftelegraphmessages,andwhichweremodelsforearlycomputerterminals.
Fornewusers,themostimportantuseofthesttycommandissettingtheerasefunctiontotheappropriatekeyontheirterminal.Forsystemsprogrammersorshellscriptwriters,thesttycommandprovidesaninvaluabletoolforconfiguringmanyaspectsofI/Ocontrolforagivendevice,includingthefollowing:
-eraseandline-killcharacters-datatransmissionspeed
-
7/31/2019 Unix Beginers
27/173
-paritycheckingondatatransmission-hardwareflowcontrol-newline(NL)versuscarriagereturnpluslinefeed(CR-LF)IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
28/173
GettingStarted
-interpretingtabcharacters-editedversusrawinput-mappingofuppercasetolowercaseThiscommandisverysystemspecific,soconsultthemanpagesforthedetailsofthesttycommandonyoursystem.Syntaxstty[options]Options(none)reporttheterminalsettingsall(or-a)reportonalloptionsechoeechoERASEasBS-space-BSdecsetmodessuitableforDigitalEquipmentCorporationoperatingsystems(whichdistinguishesbetweenERASEandBACKSPACE)(Notavailableonallsystems)killsettheLINE-KILLcharactererasesettheERASEcharacterintrsettheINTERRUPTcharacter
Examples
Youcandisplayandchangeyourterminalcontrolsettingswiththesttycommand.Todisplayall(-a)ofthecurrentlinesettings:%stty-aspeed38400baud,24rows,80columnsparenb-paroddcs7-cstopb-hupclcread-clocal-crtscts-ignbrkbrkintignpar-parmrk-inpckistrip-inlcr-igncricrnl-iuclcixon-ixany-ixoffimaxbelisigiextenicanon-xcaseechoechoeechok-echonl-noflsh-tostopechoctl-echoprtechokeopost-olcuconlcr-ocrnl-onocr-onlret-ofill-ofdelerasekillweraserprntflushlnextsuspintrquitstopeof^H^U^W^R^O^V^Z/^Y^C^\^S/^Q^D
Youcanchangesettingsusingstty,e.g.,tochangetheerasecharacterfrom^?(thedeletekey)to^H:%sttyerase^H
Thiswillsettheterminaloptionsforthecurrentsessiononly.Tohavethisdoneforyouautomaticallyeachtimeyoulogin,itcanbeinsertedintothe.loginor.profilefilethatwelllookatlater.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
29/173
GettingHelp
3.5GettingHelpTheUnixmanual,usuallycalledmanpages,isavailableon-linetoexplaintheusageoftheUnixsystemandcommands.Touseamanpage,typethecommand"man"atthesystempromptfollowedbythecommandforwhichyouneedinformation.
Syntax
man[options]command_name
CommonOptions-kkeywordlistcommandsynopsislineforallkeywordmatches-Mpathpathtomanpages-ashowallmatchingmanpages(SVR4)
Examples
Youcanusemantoprovideaonelinesynopsisofanycommandsthatcontainthekeywordthatyouwanttosearchonwiththe"-k"option,e.g.tosearchonthekeywordpassword,
type:%man-kpasswordpasswd(5)-passwordfilepasswd(1)-changepasswordinformation
Thenumberinparenthesesindicatesthesectionofthemanpageswherethesereferenceswerefound.Youcanthenaccessthemanpage(bydefaultitwillgiveyouthelowernumberedentry,butyoucanuseacommandlineoptiontospecifyadifferentone)with:
%manpasswdPASSWD(1)USERCOMMANDSPASSWD(1)
NAME
passwd-changepasswordinformationSYNOPSIS
passwd[-elogin_shell][username]DESCRIPTION
passwdchanges(orsets)auser'spassword.
passwdpromptstwiceforthenewpassword,withoutdisplaying
it.Thisistoallowforthepossibilityoftypingmistakes.
Onlytheuserandthesuper-usercanchangetheuser'spassword.OPTIONS
-eChangetheuser'sloginshell.
Hereweveparaphrasedandtruncatedtheoutputforspaceandcopyrightconcerns.
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
30/173
-
7/31/2019 Unix Beginers
31/173
GettingStarted
3.6DirectoryNavigationandControlTheUnixfilesystemissetuplikeatreebranchingoutfromtheroot.Thetherootdirectoryofthesystemissymbolizedbytheforwardslash(/).Systemanduserdirectoriesareorganizedundertheroot.TheuserdoesnothavearootdirectoryinUnix;usersgenerallylogintotheirownhomedirectory.Userscanthencreateotherdirectoriesundertheirhome.Thefollowingtablesummarizessomedirectorynavigationcommands.
TABLE3.1NavigationandDirectoryControlCommands
Command/SyntaxWhatitwilldocd[directory]changedirectoryls[options][directoryorfile]listdirectorycontentsorfilepermissionsmkdir[options]directorymakeadirectorypwdprintworking(current)directoryrmdir[options]directoryremoveadirectory
IfyourefamiliarwithDOSthefollowingtablecomparingsimilarcommandsmighth
elptoprovidetheproperreferenceframe.
TABLE3.2UnixvsDOSNavigationandDirectoryControlCommands
CommandUnixDOSlistdirectorycontentslsdirmakedirectorymkdirmd&mkdirchangedirectorycdcd&chdirdelete(remove)directoryrmdirrd&rmdirreturntousershomedirectorycdcd\locationinpath(presentworkingdirectory)
pwdcd
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
32/173
DirectoryNavigationandControl
3.6.1pwd-printworkingdirectoryAtanytimeyoucandeterminewhereyouareinthefilesystemhierarchywiththepwd,printworkingdirectory,command,e.g.:
%pwd/home/frank/src
3.6.2cd-changedirectoryYoucanchangetoanewdirectorywiththecd,changedirectory,command.cdwillacceptbothabsoluteandrelativepathnames.
Syntax
cd[directory]
Examples
cd(alsochdirinsomeshells)changedirectory
cdchangestouser'shomedirectorycd/changesdirectorytothesystem'srootcd..goesuponedirectorylevelcd../..goesuptwodirectorylevelscd/full/path/name/from/rootchangesdirectorytoabsolutepathnamed(notetheleadingslash)cdpath/from/current/locationchangesdirectorytopathrelativetocurrentlocation(noleading
slash)cd~username/directorychangesdirectorytothenamedusername'sindicateddirectory(Note:the~isnotvalidintheBourneshell;seeChapter5.)
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
33/173
GettingStarted
3.6.3mkdir-makeadirectoryYouextendyourhomehierarchybymakingsub-directoriesunderneathit.Thisisdonewiththemkdir,makedirectory,command.Again,youspecifyeitherthefullorrelativepathofthedirectory:
Syntax
mkdir[options]directory
CommonOptions-pcreatetheintermediate(parent)directories,asneeded-mmodeaccesspermissions(SVR4).(WelllookatmodeslaterinthisChapter).Examples
%mkdir/home/frank/data
or,ifyourpresentworkingdirectoryis/home/frankthefollowingwouldbeequivalent:%mkdirdata
3.6.4rmdir-removedirectoryAdirectoryneedstobeemptybeforeyoucanremoveit.Ifitsnot,youneedtoremovethefilesfirst.Also,youcantremoveadirectoryifitisyourpresentworkingdirectory;youmustfirstchangeoutofit.
Syntax
rmdirdirectory
Examples
Toremovetheemptydirectory/home/frank/datawhilein/home/frankuse:%rmdirdataor%rmdir/home/frank/data
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
34/173
DirectoryNavigationandControl
3.6.5ls-listdirectorycontentsThecommandtolistyourdirectoriesandfilesisls.Withoptionsitcanprovideinformationaboutthesize,typeoffile,permissions,datesoffilecreation,changeandaccess.
Syntax
ls[options][argument]
CommonOptions
Whennoargumentisused,thelistingwillbeofthecurrentdirectory.Therearemanyveryusefuloptionsforthelscommand.Alistingofmanyofthemfollows.Whenusingthecommand,stringthedesiredoptionstogetherprecededby"-".
-alistsallfiles,includingthosebeginningwithadot(.).-dlistsonlynamesofdirectories,notthefilesinthedirectory-Findicatestypeofentrywithatrailingsymbol:directories/
sockets=symboliclinks@executables*-gdisplaysUnixgroupassignedtothefile,requiresthe-loption(BSDonly)-or-onanSVR4machine,e.g.Solaris,thisoptionhastheoppositeeffect-Lifthefileisasymboliclink,liststheinformationforthefileordirectorythelinkreferences,nottheinformationforthelinkitself-llonglisting:liststhemode,linkinformation,owner,size,lastmodification(time).Ifthefileisasymboliclink,anarrow(-->)precedesthepathnameofthelinked-tofile.
Themodefieldisgivenbythe-loptionandconsistsof10characters.Thefirstcharacterisoneofthefollowing:
CHARACTERIFENTRYISAddirectory-plainfilebblock-typespecialfilec
character-typespecialfile
l
symboliclinkssocket
Thenext9charactersarein3setsof3characterseach.Theyindicatethefileaccesspermissions:thefirst3charactersrefertothepermissionsfortheuser,thenextthreefortheusersintheUnixgroupassignedtothefile,andthelast3tothepermissionsforotherusersonthesystem.
-
7/31/2019 Unix Beginers
35/173
Designationsareasfollows:
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
36/173
GettingStarted
rreadpermissionwwritepermissionx
executepermission-nopermission
Thereareafewlesscommonlyusedpermissiondesignationsforspecialcircumstances.Theseareexplainedinthemanpageforls.
Examples
Tolistthefilesinadirectory:%lsdemofilesfranklindaTolistallfilesinadirectory,includingthehidden(dot)filestry:
%ls-a..cshrc.history.plan.rhostsfrank...emacs.login.profiledemofileslinda
Togetalonglisting:%ls-al
total24drwxr-sr-x5workshopacs512Jun711:12.drwxr-xr-x6rootsys512May2909:59..-rwxr-xr-x1workshopacs532May2015:31.cshrc-rw-------1workshopacs525May2021:29.emacs-rw-------1workshopacs622May2412:13.history-rwxr-xr-x1workshopacs238May1409:44.login-rw-r--r--1workshopacs273May2223:53.plan-rwxr-xr-x1workshopacs413May1409:36.profile
-rw-------1workshopacs49May2020:23.rhostsdrwx------3workshopacs512May2411:18demofilesdrwx------2workshopacs512May2110:48frankdrwx------3workshopacs512May2410:59linda
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
37/173
FileMaintenanceCommands
3.7FileMaintenanceCommandsTocreate,copy,removeandchangepermissionsonfilesyoucanusethefollowingcommands.
TABLE3.3FileMaintenanceCommands
Command/SyntaxWhatitwilldochgrp[options]groupfilechangethegroupofthefilechmod[options]filechangefileordirectoryaccesspermissionschown[options]ownerfilechangetheownershipofafile;canonlybedonebythesuperusercp[options]file1file2copyfile1intofile2;file2shouldn'talreadyexist.Thiscommandcreatesoroverwritesfile2.mv[options]file1file2movefile1intofile2rm[options]fileremove(delete)afileordirectory(-rrecursivelydeletesthedirectoryanditscontents)(-ipromptsbeforeremovingfiles)
IfyourefamiliarwithDOSthefollowingtablecomparingsimilarcommandsmighthelptoprovide
theproperreferenceframe.TABLE3.4UnixvsDOSFileMaintenanceCommands
CommandUnixDOScopyfilecpcopymovefilemvmove(notsupportedonallversionsofDOS)renamefilemvrename&rendelete(remove)filermerase&deldisplayfiletoscreenentirefileonepageatatimecat
more,less,pgtypetype/p(notsupportedonallversionsofDOS)
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
38/173
GettingStarted
3.7.1cp-copyafileCopythecontentsofonefiletoanotherwiththecpcommand.
Syntax
cp[options]old_filenamenew_filename
CommonOptions-i-rinteractive(promptandwaitforconfirmationbeforeproceeding)recursivelycopyadirectoryExamples
%cpold_filenamenew_filename
Younowhavetwocopiesofthefile,eachwithidenticalcontents.Theyarecompletelyindependentofeachotherandyoucaneditandmodifyeitherasneeded.Theyeachhavetheirowninode,datablocks,anddirectorytableentries.
3.7.2mv-moveafileRenameafilewiththemovecommand,mv.
Syntax
mv[options]old_filenamenew_filename
CommonOptions-i-finteractive(promptandwaitforconfirmationbeforeproceeding)dontprompt,evenwhencopyingoveranexistingtargetfile(overrides-i)
Examples
%mvold_filenamenew_filename
Younowhaveafilecallednew_filenameandthefileold_filenameisgone.Actuallyallyouvedoneistoupdatethedirectorytableentrytogivethefileanewname.Thecontentsofthefileremainwheretheywere.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
39/173
FileMaintenanceCommands
3.7.3rm-removeafileRemoveafilewiththerm,remove,command.
Syntax
rm[options]filename
CommonOptions-iinteractive(promptandwaitforconfirmationbeforeproceeding)-rrecursivelyremoveadirectory,firstremovingthefilesandsubdirectoriesbeneathit-fdontpromptforconfirmation(overrides-i)
Examples
%rmold_filename
Alistingofthedirectorywillnowshowthatthefilenolongerexists.Actually,allyouvedoneistoremovethedirectorytableentryandmarktheinodeasunused.Thefilecontentsarestillonthedisk,
butthesystemnowhasnowayofidentifyingthosedatablockswithafilename.Thereisnocommandto"unremove"afilethathasbeenremovedinthisway.Forthisreasonmanynoviceusersaliastheirremovecommandtobe"rm-i",wherethe-ioptionpromptsthemtoansweryesornobeforethefileisremoved.Suchaliasesarenormallyplacedinthe.cshrcfilefortheCshell;seeChapter5)
3.7.4FilePermissionsEachfile,directory,andexecutablehaspermissionssetforwhocanread,write,and/orexecuteit.
Tofindthepermissionsassignedtoafile,thelscommandwiththe-loptionshouldbeused.Also,usingthe-goptionwith"ls-l"willhelpwhenitisnecessarytoknowthegroupforwhichthepermissionsareset(BSDonly).
Whenusingthe"ls-lg"commandonafile(ls-lonSysV),theoutputwillappearasfollows:
-rwxr-x---userunixgroupsizeMonthnnhh:mmfilename
Theareaabovedesignatedbylettersanddashes(-rwxr-x---)istheareashowingthefiletypeand
permissionsasdefinedinthepreviousSection.Therefore,apermissionstring,forexample,of-rwxr-x---allowstheuser(owner)ofthefiletoread,write,andexecuteit;thoseintheunixgroupofthefilecanreadandexecuteit;otherscannotaccessitatall.
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
40/173
GettingStarted
3.7.5chmod-changefilepermissionsThecommandtochangepermissionsonanitem(file,directory,etc)ischmod(changemode).Thesyntaxinvolvesusingthecommandwiththreedigits(representingtheuser(owner,u)permissions,thegroup(g)permissions,andother(o)user'spermissions)followedbytheargument(whichmaybeafilenameorlistoffilesanddirectories).Orbyusingsymbolicrepresentationforthepermissionsandwhotheyapplyto.
Eachofthepermissiontypesisrepresentedbyeitheranumericequivalent:
read=4,write=2,execute=1
orasingleletter:
read=r,write=w,execute=x
Apermissionof4orrwouldspecifyreadpermissions.Ifthepermissionsdesiredarereadandwrite,
the4(representingread)andthe2(representingwrite)areaddedtogethertomakeapermissionof6.Therefore,apermissionsettingof6wouldallowreadandwritepermissions.
Alternatively,youcouldusesymbolicnotationwhichusestheoneletterrepresentationforwhoandforthepermissionsandanoperator,wheretheoperatorcanbe:
+addpermissions-removepermissions=setpermissions
Sotosetreadandwritefortheownerwecoulduse"u=rw"insymbolicnotation.
Syntax
chmodnnn[argumentlist]numericmodechmod[who]op[perm][argumentlist]symbolicmode
wherennnarethethreenumbersrepresentinguser,group,andotherpermissions,whoisanyofu,g,o,ora(all)andpermisanyofr,w,x.Insymbolicnotationyoucanseparatepermissionspecificationsbycommas,asshownintheexamplebelow.
CommonOptions-fforce(noerrormessageisgeneratedifthechangeisunsuccessful)
-RrecursivelydescendthroughthedirectorystructureandchangethemodesExamplesIfthepermissiondesiredforfile1isuser:read,write,execute,group:read,execute,other:read,
execute,thecommandtousewouldbechmod755file1orchmodu=rwx,go=rxfile1
-
7/31/2019 Unix Beginers
41/173
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
42/173
FileMaintenanceCommands
Reminder:Whengivingpermissionstogroupandothertouseafile,itisnecessarytoallowatleastexecutepermissiontothedirectoriesforthepathinwhichthefileislocated.Theeasiestwaytodothisistobeinthedirectoryforwhichpermissionsneedtobegranted:
chmod711.orchmodu=rw,+x.orchmodu=rwx,go=x.
wherethedot(.)indicatesthisdirectory.
3.7.6chown-changeownershipOwnershipofafilecanbechangedwiththechowncommand.OnmostversionsofUnixthiscanonlybedonebythesuper-user,i.e.anormalusercantgiveawayownershipoftheirfiles.chownisusedasbelow,where#representstheshellpromptforthesuper-user:
Syntax
chown[options]user[:group]file(SVR4)chown[options]user[.group]file(BSD)
CommonOptions-Rrecursivelydescendthroughthedirectorystructure-fforce,anddontreportanyerrorsExamples
#chownnew_ownerfile
3.7.7chgrp-changegroupAnyonecanchangethegroupoffilestheyown,toanothergrouptheybelongto,withthechgrpcommand.
Syntax
chgrp[options]groupfile
CommonOptions-Rrecursivelydescendthroughthedirectorystructure-fforce,anddontreportanyerrorsExamples
%chgrpnew_groupfile
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUnivers
ity
-
7/31/2019 Unix Beginers
43/173
GettingStarted
3.8DisplayCommandsThereareanumberofcommandsyoucanusetodisplayorviewafile.Someoftheseareeditorswhichwewilllookatlater.Herewewillillustratesomeofthecommandsnormallyusedtodisplayafile.
TABLE3.5DisplayCommands
Command/SyntaxWhatitwilldocat[options]fileconcatenate(list)afileecho[textstring]echothetextstringtostdouthead[-number]filedisplaythefirst10(ornumberof)linesofafilemore(orlessorpg)[options]filepagethroughatextfiletail[options]filedisplaythelastfewlines(orparts)ofafile
3.8.1echo-echoastatementTheechocommandisusedtorepeat,orecho,theargumentyougiveitbacktothestandardoutputdevice.Itnormallyendswithaline-feed,butyoucanspecifyanoptiontopreventthis.
Syntax
echo[string]
CommonOptions-ndontprint(BSD,shellbuilt-in)\cdontprint(SVR4)\0nwherenisthe8-bitASCIIcharactercode(SVR4)
\ttab(SVR4)\fform-feed(SVR4)\nnew-line(SVR4)
\vverticaltab(SVR4)Examples%echoHelloClassorecho"HelloClass"
Topreventthelinefeed:%echo-nHelloClassorecho"HelloClass\c"wherethestyletouseinthelastexampledependsontheechocommandinuse.The\xoptionsmustbewithinpairsofsingleordoublequotes,withorwithoutotherstringcharacters.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
44/173
-
7/31/2019 Unix Beginers
45/173
GettingStarted
InternalControlsmoredisplays(onescreenatatime)thefilerequestedtoviewnextscreenortoviewonemorelineqtoquitviewingthefilehhelpbgobackuponescreenful/wordsearchforwordintheremainderofthefileSeethemanpageforadditionaloptionslesssimilartomore;seethemanpageforoptionspgtheSVR4equivalentofmore(page)
3.8.4head-displaythestartofafileheaddisplaysthehead,orstart,ofthefile.
Syntax
head[options]file
CommonOptions-nnumbernumberoflinestodisplay,countingfromthetopofthefile
-numbersameasaboveExamples
Bydefaultheaddisplaysthefirst10lines.Youcandisplaymorewiththe"-nnumber",or"-number"options,e.g.,todisplaythefirst40lines:%head-40filenameorhead-n40filename
3.8.5tail-displaytheendofafiletaildisplaysthetail,orend,ofthefile.
Syntax
tail[options]file
CommonOptions-numbernumberoflinestodisplay,countingfromthebottomofthefileExamples
Thedefaultistodisplaythelast10lines,butyoucanspecifydifferentlineorbytenumbers,oradifferentstartingpointwithinthefile.Todisplaythelast30linesofafileusethe-numberstyle:
%tail-30filename
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
46/173
SystemResources
CHAPTER4SystemResources&Printing
4.1SystemResourcesCommandstoreportormanagesystemresources.
TABLE4.1SystemResourceCommands
Command/SyntaxWhatitwilldochsh(passwd-e/-s)usernamelogin_shellchangetheusersloginshell(oftenonlybythesuperuser)date[options]reportthecurrentdateandtimedf[options][resource]reportthesummaryofdiskblocksandinodesfreeandinusedu[options][directoryorfile]reportamountofdiskspaceinuse+hostname/unamedisplayorset(super-useronly)thenameofthecurrentmachinekill[options][-SIGNAL][pid#][%job]sendasignaltotheprocesswiththeprocessidnumber(pid#)orjobcontrolnumber(%n).Thedefaultsignalistokilltheprocess.man[options]commandshowthemanual(man)pageforacommandpasswd[options]setorchangeyourpassword
ps[options]showstatusofactiveprocessesscriptfilesaveseverythingthatappearsonthescreentofileuntilexitisexecutedstty[options]setordisplayterminalcontroloptionswhereis[options]commandreportthebinary,source,andmanpagelocationsforthecommandnamedwhichcommandreportsthepathtothecommandortheshellaliasinusewhoorwreportwhoisloggedinandwhatprocessesarerunning
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
47/173
SystemResources&Printing
4.1.1df-summarizediskblockandfileusagedfisusedtoreportthenumberofdiskblocksandinodesusedandfreeforeachfilesystem.TheoutputformatandvalidoptionsareveryspecifictotheOSandprogramversioninuse.
Syntax
df[options][resource]
CommonOptions-llocalfilesystemsonly(SVR4)-kreportinkilobytes(SVR4)
Examples
{unixprompt1}dfFilesystemkbytesusedavailcapacityMountedon/dev/sd0a20895192240102%//dev/sd0h31905513129315585746%/usr/dev/sd1g63772634880922514561%/usr/local
/dev/sd1a2401111654895061177%
/home/guardianperi:/usr/local/backup
195257397655878075856%/usr/local/backupperi:/home/peri72688439118926300760%/home/periperi:/usr/spool/mail19238310811720641%
/var/spool/mailperi:/acs/peri/272393452160412993780%/acs/peri/2
4.1.2du-reportdiskspaceinusedureportstheamountofdiskspaceinuseforthefilesordirectoriesyouspecify.
Syntax
du[options][directoryorfile]
CommonOptions
-adisplaydiskusageforeachfile,notjustsubdirectories-sdisplayasummarytotalonly-kreportinkilobytes(SVR4)
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
48/173
SystemResources
Examples
{unixprompt3}du1./.elm1
./Mail1
./News20./uc
86.{unixprompt4}du-auc7uc/unixgrep.txt5uc/editors.txt1uc/.emacs1uc/.exrc4uc/telnet.ftp1uc/uniq.tee.txt20uc
4.1.3ps-showstatusofactiveprocessespsisusedtoreportonprocessescurrentlyrunningonthesystem.TheoutputformatandvalidoptionsareveryspecifictotheOSandprogramversioninuse.
Syntax
ps[options]
CommonOptions
BSDSVR4
-a-eallprocesses,allusers-eenvironment/everything-gprocessgroupleadersaswell-l-llongformat-u-uuseruserorientedreport-x-eevenprocessesnotexecutedfromterminals-ffulllisting-wreportfirst132charactersperline
note--Becausethepscommandishighlysystem-specific,itisrecommendedthatyouconsultthemanpagesofyoursystemfordetailsofoptionsandinterpretationofpsoutput.
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
49/173
SystemResources&Printing
Examples
{unixprompt5}ps
PIDTTSTATTIMECOMMAND15549p0IW0:00-tcsh(tcsh)15588p0IW0:00mannice15594p0IW0:00sh-cless/tmp/man1558815595p0IW0:00less/tmp/man1558815486p1S0:00-tcsh(tcsh)15599p1T0:00emacsunixgrep.txt15600p1R0:00ps
4.1.4kill-terminateaprocesskillsendsasignaltoaprocess,usuallytoterminateit.
Syntax
kill[-signal]process-id
CommonOptions-ldisplaystheavailablekillsignals:Examples
{unixprompt9}kill-l
HUPINTQUITILLTRAPIOTEMTFPEKILLBUSSEGVSYSPIPEALRMTERMURGSTOP
TSTPCONTCHLDTTINTTOUIOXCPUXFSZVTALRMPROFWINCHLOSTUSR1USR2
The-KILLsignal,alsospecifiedas-9(becauseitis9thontheabovelist),isthemostcommonly
usedkillsignal.Onceseen,itcantbeignoredbytheprogramwhereastheothersignalscan.
{unixprompt10}kill-915599
[1]+Killedemacsunixgrep.txt1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
50/173
SystemResources
4.1.5who-listcurrentuserswhoreportswhoisloggedinatthepresenttime.
Syntax
who[ami]
Examples
beautycondron>who
wmtellttyp1Apr2120:15(apple.acs.ohio-s)fbwalkttyp2Apr2123:21(worf.acs.ohio-st)stwangttyp3Apr2123:22(127.99.25.8)davidttyp4Apr2122:27(slip1-61.acs.ohi)tgardnerttyp5Apr2123:07(picard.acs.ohio-)awallacettyp6Apr2123:00(ts31-4.homenet.o)gtl27ttyp7Apr2123:24(data.acs.ohio-st)ccchangttyp8Apr2123:32(slip3-10.acs.ohi)condronttypcApr2123:38(lcondron-mac.acs)
dgildmanttypeApr2122:30(slip3-36.acs.ohi)fcbetzttyq2Apr2121:12(ts24-10.homenet.)
beautycondron>whoamibeauty!condronttypcApr2123:38(lcondron-mac.acs)
4.1.6whereis-reportprogramlocationswhereisreportsthefilenamesofsource,binary,andmanualpagefilesassociatedwithcommand(s).
Syntax
whereis[options]command(s)
CommonOptions-breportbinaryfilesonly-mreportmanualsectionsonly-sreportsourcefilesonly
Examples
brigadier:condron[69]>whereisMailMail:/usr/ucb/Mail/usr/lib/Mail.help/usr/lib/Mail.rc/usr/man/man1/Mail.1
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUnivers
ity
-
7/31/2019 Unix Beginers
51/173
SystemResources&Printing
brigadier:condron[70]>whereis-bMailMail:/usr/ucb/Mail/usr/lib/Mail.help/usr/lib/Mail.rc
brigadier:condron[71]>whereis-mMailMail:/usr/man/man1/Mail.1
4.1.7which-reportthecommandfoundwhichwillreportthenameofthefilethatisbeexecutedwhenthecommandisinvoked.Thiswillbethefullpathnameorthealiasthatsfoundfirstinyourpath.
Syntax
whichcommand(s)
example-brigadier:condron[73]>whichMail/usr/ucb/Mail
4.1.8hostname/uname-nameofmachinehostname(uname-nonSysV)reportsthehostnameofthemachinetheuserisloggedinto,e.g.:brigadier:condron[91]>hostnamebrigadier
unamehasadditionaloptionstoprintinformationaboutsystemhardwaretypeandsoftwareversion.
4.1.9script-recordyourscreenI/Oscriptcreatesascriptofyoursessioninputandoutput.Usingthescriptcommand,youcancaptureallthedatatransmissionfromandtoyourterminalscreenuntilyouexitthesc
riptprogram.Thiscanbeusefulduringtheprogramming-and-debuggingprocess,todocumentthecombinationofthingsyouhavetried,ortogetaprintedcopyofitallforlaterperusal.
Syntax
script[-a][file]exit
CommonOptions-aappendtheoutputtofile
typescriptisthenameofthedefaultfileusedbyscript.
Youmustremembertotypeexittoendyourscriptsessionandcloseyourtypescriptfile.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
52/173
-
7/31/2019 Unix Beginers
53/173
-
7/31/2019 Unix Beginers
54/173
SystemResources&Printing
4.1.10date-currentdateandtimedatedisplaysthecurrentdataandtime.Asuperusercansetthedateandtime.
Syntax
date[options][+format]
CommonOptions-uuseUniversalTime(orGreenwichMeanTime)+formatspecifytheoutputformat%aweekdayabbreviation,SuntoSat%hmonthabbreviation,JantoDec%jdayofyear,001to366%n%t%ylast2digitsofyear,00to99%DMM/DD/YYdate%Hhour,00to23%Mminute,00to59%Ssecond,00to59%THH:MM:SStime
Examples
beautycondron>dateMonJun1009:01:05EDT1996
beautycondron>date-uMonJun1013:01:33GMT1996
beautycondron>date+%a%t%DMon06/10/96
beautycondron>date'+%y:%j'
96:1621998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
55/173
-
7/31/2019 Unix Beginers
56/173
-
7/31/2019 Unix Beginers
57/173
PrintCommands
4.2.4pr-preparefilesforprintingprprintsheaderandtrailerinformationsurroundingtheformattedfile.Youcanspecifythenumberofpages,linesperpage,columns,linespacing,pagewidth,etc.toprint,alongwithheaderandtrailerinformationandhowtotreatcharacters.
Syntaxpr[options]fileCommonOptions+page_numberstartprintingwithpagepage_numberoftheformattedinputfile-columnnumberofcolumns-amodify-columnoptiontofillcolumnsinround-robinorder-ddoublespacing-e[char][gap]tabspacing-hheader_stringheaderforeachpage-llineslinesperpage-tdontprinttheheaderandtraileroneachpage-wwidthwidthofpage
Examples
ThefilecontainingthelistofP.G.WodehousesLordEmsworthbookscouldbeprinted,at14linesperpage(including5headerand5(empty)trailerlines)below,wherethe-eoptionspecifiestheconversionstyle:
%pr-l14-e42wodehouse
Apr2911:111996wodehouse_emsworth_booksPage1
SomethingFresh[1915]UncleDynamite[1948]LeaveittoPsmith[1923]PigsHaveWings[1952]SummerLightning[1929]CocktailTime[1958]HeavyWeather[1933]ServicewithaSmile[1961]
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
58/173
-
7/31/2019 Unix Beginers
59/173
-
7/31/2019 Unix Beginers
60/173
-
7/31/2019 Unix Beginers
61/173
-
7/31/2019 Unix Beginers
62/173
Shells
5.2EnvironmentVariablesEnvironmentalvariablesareusedtoprovideinformationtotheprogramsyouuse.Youcanhavebothglobalenvironmentandlocalshellvariables.Globalenvironmentvariablesaresetbyyourloginshellandnewprogramsandshellsinherittheenvironmentoftheirparentshell.Localshellvariablesareusedonlybythatshellandarenotpassedontootherprocesses.Achildprocesscannotpassavariablebacktoitsparentprocess.
Thecurrentenvironmentvariablesaredisplayedwiththe"env"or"printenv"commands.Somecommononesare:
DISPLAYThegraphicaldisplaytouse,e.g.nyssa:0.0EDITORThepathtoyourdefaulteditor,e.g./usr/bin/viGROUPYourlogingroup,e.g.staff
HOMEPathtoyourhomedirectory,e.g./home/frankHOSTThehostnameofyoursystem,e.g.nyssaIFSInternalfieldseparators,usuallyanywhitespace(defaultstotab,spaceand)LOGNAMEThenameyouloginwith,e.g.frankPATHPathstobesearchedforcommands,e.g./usr/bin:/usr/ucb:/usr/local/binPS1Theprimarypromptstring,Bourneshellonly(defaultsto$)
PS2Thesecondarypromptstring,Bourneshellonly(defaultsto>)SHELLTheloginshellyoureusing,e.g./usr/bin/cshTERMYourterminaltype,e.g.xtermUSERYourusername,e.g.frankManyenvironmentvariableswillbesetautomaticallywhenyoulogin.Youcanmodifythemordefineotherswithentriesinyourstartupfilesoratanytimewithintheshell.SomevariablesyoumightwanttochangearePATHandDISPLAY.ThePATHvariablespecifiesthedirectoriestobeautomatically
searchedforthecommandyouspecify.Examplesofthisareintheshellstartupscriptsbelow.YousetaglobalenvironmentvariablewithacommandsimilartothefollowingfortheCshell:
%setenvNAMEvalueandforBourneshell:
$NAME=value;exportNAMEYoucanlistyourglobalenvironmentalvariableswiththeenvorprintenvcomman
-
7/31/2019 Unix Beginers
63/173
ds.Youunsetthemwiththeunsetenv(Cshell)orunset(Bourneshell)commands.
TosetalocalshellvariableusethesetcommandwiththesyntaxbelowforCshell.Withoutoptionssetdisplaysallthelocalvariables.
%setname=valueFortheBourneshellsetthevariablewiththesyntax:
$name=value
Thecurrentvalueofthevariableisaccessedviathe"$name",or"${name}",notation.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
64/173
-
7/31/2019 Unix Beginers
65/173
-
7/31/2019 Unix Beginers
66/173
Shells
5.4TheCShell,cshCshusesthestartupfiles.cshrcand.login.Someversionsuseasystem-widestartupfile,e.g./etc/csh.login.Your.loginfileissourced(executed)onlywhenyoulogin.Your.cshrcfileissourcedeverytimeyoustartacsh,includingwhenyoulogin.Ithasmanysimilarfeaturesto.profile,butadifferentstyleofdoingthings.Hereweusethesetorsetenvcommandstoinitializeavariable,wheresetisusedforthisshellandsetenvforthisandanysubshells.Theenvironmentvariables:USER,TERM,andPATH,areautomaticallyimportedtoandexportedfromtheuser,term,andpathvariablesofthecsh.Sosetenvdoesntneedtobedoneforthese.TheCshellusesthesymbol,~,toindicatetheusershomedirectoryinapath,asin~/.cshrc,ortospecifyanotheruserslogindirectory,asin~username/.cshrc.
PredefinedvariablesusedbytheCshellinclude:
argvThelistofargumentsofthecurrentshellcwdThecurrentworkingdirectoryhistorySetsthesizeofthehistorylisttosavehomeThehomedirectoryoftheuser;startswith$HOMEignoreeofWhensetignoreEOF(^D)fromterminalsnoclobberWhensetpreventoutputredirectionfromoverwritingexistingfilesnoglob
WhensetpreventfilenameexpansionwithwildcardpatternmatchingpathThecommandsearchpath;startswith$PATHpromptSetthecommandlineprompt(defaultis%)savehistnumberoflinestosaveinthehistorylisttosaveinthe.historyfileshellThefullpathnameofthecurrentshell;startswith$SHELLstatusTheexitstatusofthelastcommand(0=normalexit,1=failedcommand)term
Yourterminaltype,startswith$TERMuserYourusername,startswith$USERAsimple.cshrccouldbe:setpath=(/usr/bin/usr/ucb/usr/local/bin~/bin.)#setthepathsetprompt="{hostnamewhoami!}"#settheprimaryprompt;defaultis"%"setnoclobber#dontredirectoutputtoexistingfilessetignoreeof#ignoreEOF(^D)forthisshellsethistory=100savehist=50#keepahistorylistandsaveitbetweenlogins#aliasesaliashhistory#aliashto"history"
-
7/31/2019 Unix Beginers
67/173
aliasls"/usr/bin/ls-sbF"#aliaslsto"ls-sbF"aliasllls-al#aliasllto"ls-sbFal"(combiningtheseoptionswiththosefor"ls"above)aliascdcd\!*;pwd#aliascdsothatitprintsthecurrentworkingdirectoryafterthechangeumask077
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
68/173
JobControl
Somenewfeaturesherethatwedidntseein.profilearenoclobber,ignoreeof,andhistory.Noclobberindicatesthatoutputwillnotberedirectedtoexistingfiles,whileignoreeofspecifiesthatEOF(^D)willnotcausetheloginshelltoexitandlogyouoffthesystem.
Withthehistoryfeatureyoucanrecallpreviouslyexecutedcommandsandre-executethem,withchangesifdesired.
Analiasallowsyoutousethespecifiedaliasnameinsteadofthefullcommand.Inthe"ls"exampleabove,typing"ls"willresultin"/usr/bin/ls-sbF"beingexecuted.Youcantellwhich"ls"commandisinyourpathwiththebuilt-inwhichcommand,i.e.:
whichlsls:aliasedto/usr/bin/ls-sbFAsimple.logincouldbe:#.loginsttyerase^H#setControl-Htobetheerasekey
setnoglob#preventwildcardpatternmatchingevaltset-Q-s-m:?xterm#promptfortheterminaltype,assume"xterm"unsetnoglob#re-enablewildcardpatternmatching
Settingandunsettingnoglobaroundtsetpreventsitfrombeingconfusedbyanycshfilenamewildcard
patternmatchingorexpansion.Shouldyoumakeanychangestoyourstartupfilesyoucaninitiatethechangebysourcingthechangedfile.Forcshyoudothiswiththebuilt-insourcecommand,i.e.:
source.cshrcForfurtherinformationaboutcshtype"mancsh"attheshellprompt.
5.5JobControlWiththeCshell,csh,andmanynewershellsincludingsomenewerBourneshells,youcanputjobsintothebackgroundatanytimebyappending"&"tothecommand,aswithsh.Aftersubmittingacommandyoucanalsodothisbytyping^Z(Control-Z)tosuspendthejobandthen"bg"toputitintothebackground.Tobringitbacktotheforegroundtype"fg".
Youcanhavemanyjobsrunninginthebackground.Whentheyareinthebackgroun
dtheyarenolongerconnectedtothekeyboardforinput,buttheymaystilldisplayoutputtotheterminal,interspersingwithwhateverelseistypedordisplayedbyyourcurrentjob.YoumaywanttoredirectI/Otoorfromfilesforthejobyouintendtobackground.Yourkeyboardisconnectedonlytothecurrent,foreground,job.
Thebuilt-injobscommandallowsyoutolistyourbackgroundjobs.Youcanuset
-
7/31/2019 Unix Beginers
69/173
-
7/31/2019 Unix Beginers
70/173
-
7/31/2019 Unix Beginers
71/173
-
7/31/2019 Unix Beginers
72/173
Shells
5.7ChangingyourShellTochangeyourshellyoucanusuallyusethe"chsh"or"passwd-e"commands.Theoptionflag,here-e,mayvaryfromsystemtosystem(-sonBSDbasedsystems),socheckthemanpageonyoursystemforproperusage.Sometimesthisfeatureisdisabled.IfyoucantchangeyourshellcheckwithyourSystemAdministrator.
Thenewshellmustbethefullpathnameforavalidshellonthesystem.Whichshellsareavailabletoyouwillvaryfromsystemtosystem.Thefullpathnameofashellmayalsovary.Normally,though,theBourneandCshellsarestandard,andavailableas:
/bin/sh
/bin/cshSomesystemswillalsohavetheKornshellstandard,normallyas:
/bin/ksh
Someshellsthatarequitepopular,butnotnormallydistributedbytheOSvendorsarebashandtcsh.Thesemightbeplacedin/binoralocallydefineddirectory,e.g./usr/local/binor/opt/local/bin.ShouldyouchooseashellnotstandardtotheOSmakesurethatthisshell,andallloginshellsavailableonthesystem,arelistedinthefile/etc/shells.Ifthisfileexistsandyourshellisnotlistedinthisfilethefiletransferprotocoldaemon,ftpd,willnotletyouconnecttothismachine.Ifthisfiledoesnotexistonlyaccountswith"standard"shellsareallowedtoconnectviaftp.
Youcanalwaystryoutashellbeforeyousetitasyourdefaultshell.Todoth
isjusttypeintheshellnameasyouwouldanyothercommand.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
73/173
-
7/31/2019 Unix Beginers
74/173
-
7/31/2019 Unix Beginers
75/173
-
7/31/2019 Unix Beginers
76/173
FileRedirection
6.2.2Sh2>filedirectstderrtofile>file2>&1directbothstdoutandstderrtofile>>file2>&1appendbothstdoutandstderrtofile2>&1|commandpipestdoutandstderrtocommandToredirectstdoutandstderrtotwoseparatefilesyoucando:
$command1>out_file2>err_file
or,sincetheredirectiondefaultstostdout:
$command>out_file2>err_file
WiththeBourneshellyoucanspecifyotherfiledescriptors(3through9)andredirectoutputthroughthem.Thisisdonewiththeform:
n>&mredirectfiledescriptorntofiledescriptorm
Weusedtheabovetosendstderr(2)tothesameplaceasstdout(1),2>&1,whenwewantedtohave
errormessagesandnormalmessagestogotofileinsteadoftheterminal.Ifwewantedonlytheerrormessagestogotothefilewecoulddothisbyusingaplaceholderfiledescriptor,3.Wellfirstredirect3to2,thenredirect2to1,andfinally,wellredirect1to3:
$(command3>&22>&11>&3)>file
Thissendsstderrto3thento1,andstdoutto3,whichisredirectedto2.So,ineffect,wevereversedfiledescriptors1and2fromtheirnormalmeaning.Wemightusethisinthefollowingexample:
$(catfile3>&22>&11>&3)>errfile
Soiffileisreadtheinformationisdiscardedfromthecommandoutput,butiffilecantbereadtheerrormessageisputinerrfileforyourlateruse.
Youcanclosefiledescriptorswhenyouredonewiththem:
m&-closesstdout
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
77/173
SpecialUnixFeatures
6.3OtherSpecialCommandSymbolsInadditiontofileredirectionsymbolsthereareanumberofotherspecialsymbolsyoucanuseonacommandline.Theseinclude:
;commandseparator&runthecommandinthebackground&&runthecommandfollowingthisonlyifthepreviouscommandcompletessuccessfully,e.g.:grepstringfile&&catfile||runthecommandfollowingonlyifthepreviouscommanddidnotcompletesuccessfully,e.g.:grepstringfile||echo"Stringnotfound."()thecommandswithintheparenthesesareexecutedinasubshell.Theoutputofthesubshellcanbemanipulatedasabove.literalquotationmarks.Dontallowanyspecialmeaningtoanycharacterswithinthesequotations.\escapethefollowingcharacter(takeitliterally)""regularquotationmarks.Allowvariableandcommandsubstitutionwiththesesquotations(doesnotdisable$and\withinthestring).commandtaketheoutputofthiscommandandsubstituteitasanargument(s)onthe
commandline#everythingfollowinguntilisacomment
The\charactercanalsobeusedtoescapethecharactersothatyoucancontinuealongcommandonmorethanonephysicallineoftext.
6.4WildCardsTheshellandsometextprocessingprogramswillallowmeta-characters,orwildcards,andreplacethemwithpatternmatches.Forfilenamesthesemeta-charactersandtheirusesare:
?matchanysinglecharacterattheindicatedposition*matchanystringofzeroormorecharacters[abc...]matchanyoftheenclosedcharacters[a-e]matchanycharactersintherangea,b,c,d,e[!def]matchanycharactersnotoneoftheenclosedcharacters,shonly{abc,bcd,cde}matchanysetofcharactersseparatedbycomma(,)(nospaces),cshonly~homedirectoryofthecurrentuser,cshonly~userhomedirectoryofthespecifieduser,cshonly
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
78/173
-
7/31/2019 Unix Beginers
79/173
-
7/31/2019 Unix Beginers
80/173
-
7/31/2019 Unix Beginers
81/173
-
7/31/2019 Unix Beginers
82/173
-
7/31/2019 Unix Beginers
83/173
-
7/31/2019 Unix Beginers
84/173
TextProcessing
Thisexamplewillsearchforanyinstancesoftfollowedbyzeroormoreoccurrencesofe:{unixprompt13}grep'te*'num.list115fifteen214fourteen313thirteen412twelve610ten88eight133three142two
Thisexamplewillsearchforanyinstancesoftfollowedbyoneormoreoccurrencesofe:
{unixprompt14}grep'tee*'num.list
115fifteen
214fourteen
313thirteen610ten
Wecanalsotakeourinputfromaprogram,ratherthanafile.Herewereportonanylinesoutputbythewhoprogramthatbeginwiththeletterl.{unixprompt15}who|grep'^l'lcondronttyp0Dec102:41(lcondron-pc.acs.)
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
85/173
-
7/31/2019 Unix Beginers
86/173
cialmeaning.
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
87/173
-
7/31/2019 Unix Beginers
88/173
TextProcessingCommands
7.2.3awk,nawk,gawkawkisapatternscanningandprocessinglanguage.Itsnamecomesfromthelastinitialsofthethreeauthors:Alfred.V.Aho,Brian.W.Kernighan,andPeter.J.Weinberger.nawkisnewawk,anewerversionoftheprogram,andgawkisgnuawk,fromtheFreeSoftwareFoundation.Eachversionisalittledifferent.Herewellconfineourselvestosimpleexampleswhichshouldbethesameforallversions.OnsomeOSsawkisreallynawk.
awksearchesitsinputforpatternsandperformsthespecifiedoperationoneachline,orfieldsoftheline,thatcontainthosepatterns.Youcanspecifythepatternmatchingstatementsforawkeitheronthecommandline,orbyputtingtheminafileandusingthe-fprogram_fileoption.
Syntax
awkprogram[file]
whereprogramiscomposedofoneormore:
pattern{action}
fields.Eachinputlineischeckedforapatternmatchwiththeindicatedactionbeingtakenonamatch.Thiscontinuesthroughthefullsequenceofpatterns,thenthenextlineofinputischecked.
Inputisdividedintorecordsandfields.Thedefaultrecordseparatoris,andthevariableNRkeepstherecordcount.Thedefaultfieldseparatoriswhitespace,spacesand
tabs,andthevariableNFkeepsthefieldcount.Inputfield,FS,andrecord,RS,separatorscanbesetatanytimetomatchanysinglecharacter.Outputfield,OFS,andrecord,ORS,separatorscanalsobechangedtoanysinglecharacter,asdesired.$n,wherenisaninteger,isusedtorepresentthenthfieldoftheinputrecord,while$0representstheentireinputrecord.
BEGINandENDarespecialpatternsmatchingthebeginningofinput,beforethefirstfieldisread,andtheendofinput,afterthelastfieldisread,respectively.
Printingisallowedthroughtheprint,andformattedprint,printf,statements.
Patternsmayberegularexpressions,arithmeticrelationalexpressions,string-valuedexpressions,andbooleancombinationsofanyofthese.Forthelatterthepatternscanbecombinedwiththebooleanoperatorsbelow,usingparenthesestodefinethecombination:
||or&&and
-
7/31/2019 Unix Beginers
89/173
!not
Commaseparatedpatternsdefinetherangeforwhichthepatternisapplicable,e.g.:/first/,/last/
selectsalllinesstartingwiththeonecontainingfirst,andcontinuinginclusively,throughtheonecontaininglast.
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
90/173
TextProcessing
Toselectlines15through20usethepatternrange:NR==15,NR==20Regularexpressionsmustbeenclosedwithslashes(/)andmeta-characterscanbeescapedwiththebackslash(\).Regularexpressionscanbegroupedwiththeoperators:
|or,toseparatealternatives+oneormore?zeroorone
Aregularexpressionmatchcanbeeitherof:~containstheexpression!~doesnotcontaintheexpression
Sotheprogram:$1~/[Ff]rank/
istrueifthefirstfield,$1,contains"Frank"or"frank"anywherewithinthefield.Tomatchafieldidenticalto"Frank"or"frank"use:
$1~/^[Ff]rank$/Relationalexpressionsareallowedusingtherelationaloperators:greaterthan
Offhandyoudontknowifvariablesarestringsornumbers.Ifneitheroperandisknowntobenumeric,thanstringcomparisonsareperformed.Otherwise,anumericcomparison
isdone.Intheabsenceofanyinformationtothecontrary,astringcomparisonisdone,sothat:
$1>$2
willcomparethestringvalues.Toensureanumericalcomparisondosomethingsimilarto:($1+0)>$2
Themathematicalfunctions:exp,logandsqrtarebuilt-in.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoU
nix
-
7/31/2019 Unix Beginers
91/173
TextProcessingCommands
Someotherbuilt-infunctionsinclude:
index(s,t)returnsthepositionofstringswheretfirstoccurs,or0ifitdoesntlength(s)returnsthelengthofstringssubstr(s,m,n)returnsthen-charactersubstringofs,beginningatpositionm
Arraysaredeclaredautomaticallywhentheyareused,e.g.:arr[i]=$1
assignsthefirstfieldofthecurrentinputrecordtotheithelementofthearray.
Flowcontrolstatementsusingif-else,while,andforareallowedwithCtypesyntax:
for(i=1;i
-
7/31/2019 Unix Beginers
92/173
-
7/31/2019 Unix Beginers
93/173
OtherUsefulCommands
CHAPTER8OtherUsefulCommands
8.1WorkingWithFilesThissectionwilldescribeanumberofcommandsthatyoumightfindusefulinexaminingandmanipulatingthecontentsofyourfiles.
TABLE8.1Fileutilities
Command/SyntaxWhatitwilldocmp[options]file1file2comparetwofilesandlistwheredifferencesoccur(textorbinaryfiles)cut[options][file(s)]cutspecifiedfield(s)/character(s)fromlinesinfile(s)diff[options]file1file2comparethetwofilesanddisplaythedifferences(textfilesonly)file[options]fileclassifythefiletypefinddirectory[options][actions]findfilesmatchingatypeorpatternln[options]source_filetargetlinkthesource_filetothetargetpaste[options]filepastefield(s)ontothelinesinfile
sort[options]filesortthelinesofthefileaccordingtotheoptionschosenstrings[options]filereportanysequenceof4ormoreprintablecharactersendinginor.UsuallyusedtosearchbinaryfilesforASCIIstrings.tee[options]filecopystdouttooneormorefilestouch[options][date]filecreateanemptyfile,orupdatetheaccesstimeofanexistingfiletr[options]string1string2translatethecharactersinstring1fromstdinintothoseinstring2instdoutuniq[options]fileremoverepeatedlinesinafilewc[options][file(s)]displayword(orcharacterorline)countforfile(s)
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoU
nix
-
7/31/2019 Unix Beginers
94/173
WorkingWithFiles
8.1.1cmp-comparefilecontentsThecmpcommandcomparestwofiles,and(withoutoptions)reportsthelocationofthefirstdifferencebetweenthem.ItcandealwithbothbinaryandASCIIfilecomparisons.Itdoesabyte-by-bytecomparison.
Syntax
cmp[options]file1file2[skip1][skip2]Theskipnumbersarethenumberofbytestoskipineachfilebeforestartingthecomparison.
CommonOptions-lreportoneachdifference-sreportexitstatusonly,notbytedifferences
Examples
Giventhefilesmon.logins:andtues.logins:
ageorgeageorgebsmithcbettscbettsjchenjchenjdoejmarschjmarschlkereslkeresmschmidtproysphillipsphillipwyeppwyepp
Thecomparisonofthetwofilesyields:
%cmpmon.loginstues.logins
mon.loginstues.loginsdiffer:char9,line2
Thedefaultittoreportonlythefirstdifferencefound.
Thiscommandisusefulindeterminingwhichversionofafileshouldbekeptwhenthereismorethanoneversion.
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
95/173
-
7/31/2019 Unix Beginers
96/173
-
7/31/2019 Unix Beginers
97/173
-
7/31/2019 Unix Beginers
98/173
WorkingWithFiles
Examples
Giventhefileusers:
jdoeJohnDoe4/15/96
lsmithLauraSmith3/12/96
pchenPaulChen1/5/96
jhsuJakeHsu4/17/96
sphilipSuePhillip4/2/96
andthefilephone:
JohnDoe555-6634
LauraSmith555-3382
PaulChen555-0987
JakeHsu555-1235
SuePhillip555-7623
thepastecommandcanbeusedinconjunctionwiththecutcommandtocreateanewfile,listing,thatincludestheusername,realname,lastlogin,andphonenumberofalltheusers.First,extractthephonenumbersintoatemporaryfile,temp.file:%cut-f2phone>temp.file555-6634555-3382
555-0987555-1235555-7623
Theresultcanthenbepastedtotheendofeachlineinusersanddirectedtothenewfile,listing:%pasteuserstemp.file>listingjdoeJohnDoe4/15/96237-6634lsmithLauraSmith3/12/96878-3382pchenPaulChen1/5/96888-0987jhsuJakeHsu4/17/96545-1235sphilipSuePhillip4/2/96656-7623
Thiscouldalsohavebeendoneononelinewithoutthetemporaryfileas:%cut-f2phone|pasteusers->listing
withthesameresults.Inthiscasethehyphen(-)isactingasaplaceholderforaninputfield(namely,theoutputofthecutcommand).
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
99/173
-
7/31/2019 Unix Beginers
100/173
-
7/31/2019 Unix Beginers
101/173
-
7/31/2019 Unix Beginers
102/173
OtherUsefulCommands
8.1.7ln-linktoanotherfileThelncommandcreatesa"link"oranadditionalwaytoaccess(orgivesanadditionalnameto)anotherfile.
Syntax
ln[options]source[target]Ifnotspecifiedtargetdefaultstoafileofthesamenameinthepresentworkingdirectory.
CommonOptions-fforcealinkregardlessoftargetpermissions;dontreporterrors(SVR4only)-smakeasymboliclink
Examples
Asymboliclinkisusedtocreateanewpathtoanotherfileordirectory.Ifagroupofusers,forexample,isaccustomedtousingacommandcalledchkmag,butthecommandhasbeenrewrittenand
isnowcalledchkit,creatingasymboliclinksotheuserswillautomaticallyexecutechkitwhentheyenterthecommandchkmagwilleasetransitiontothenewcommand.
Asymboliclinkwouldbedoneinthefollowingway:%ln-schkitchkmagThelonglistingforthesetwofilesisnowasfollows:
16-rwxr-x---1lindadbacs15927Apr2304:10chkit1lrwxrwxrwx1lindadbacs5Apr2304:11chkmag->chkit
Notethatwhilethepermissionsforchkmagareopentoall,sinceitislinkedt
ochkit,thepermissions,groupandownercharacteristicsforchkitwillbeenforcedwhenchkmagisrun.
Withasymboliclink,thelinkcanexistwithoutthefileordirectoryitislinkedtoexistingfirst.Ahardlinkcanonlybedonetoanotherfileonthesamefilesystem,butnottoadirectory(exceptbythesuperuser).Ahardlinkcreatesanewdirectoryentrypointingtothesameinodeastheoriginalfile.Thefilelinkedtomustexistbeforethehardlinkcanbecreated.Thefilewillnotbedeleteduntilallthehardlinkstoitareremoved.Tolinkthetwofilesabovewithahardlinktoeachotherdo:
%lnchkitchkmagThenalonglistingshowsthattheinodenumber(742)isthesameforeach:%ls-ilchkitchkmag
742-rwxr-x---2lindadbacs15927Apr2304:10chkit742-rwxr-x---2lindadbacs15927Apr2304:10chkmag
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoU
-
7/31/2019 Unix Beginers
103/173
nix
-
7/31/2019 Unix Beginers
104/173
WorkingWithFiles
8.1.8sort-sortfilecontentsThesortcommandisusedtoorderthelinesofafile.Variousoptionscanbeusedtochoosetheorderaswellasthefieldonwhichafileissorted.Withoutanyoptions,thesortcomparesentirelinesinthefileandoutputstheminASCIIorder(numbersfirst,uppercaseletters,thenlowercaseletters).
Syntax
sort[options][+pos1[-pos2]]file
CommonOptions-bignoreleadingblanks(&)whendeterminingstartingandendingcharactersforthesortkey-ddictionaryorder,onlyletters,digits,andaresignificant-ffolduppercasetolowercase-kkeydefsortonthedefinedkeys(notavailableonallsystems)-iignorenon-printablecharacters-nnumericsort-ooutfileoutputfile
-rreversethesort-tcharusecharasthefieldseparatorcharacter-uunique;omitmultiplecopiesofthesameline(afterthesort)+pos1[-pos2](oldstyle)providesfunctionalitysimilartothe"-kkeydef"option.
Forthe+/-positionentriespos1isthestartingwordnumber,beginningwith0andpos2istheendingwordnumber.When-pos2isomittedthesortfieldcontinuesthroughtheendoftheline.Bothpos1andpos2canbewrittenintheformw.c,wherewisthewordnumberandcisthecharacterwithintheword.Forc0specifiesthedelimiterprecedingthefirstcharacter,and1isthe
firstcharacteroftheword.Theseentriescanbefollowedbytypemodifiers,e.g.nfornumeric,btoskipblanks,etc.
Thekeydeffieldofthe"-k"optionhasthesyntax:
start_field[type][,end_field[type]]
where:
start_field,end_fielddefinethekeystorestrictthesorttoaportionofthelinetypemodifiesthesort,validmodifiersaregiventhesinglecharacters(bdfiMnr
)fromthesimilarsortoptions,e.g.atypebisequivalentto"-b",butappliesonlytothespecifiedfield
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
105/173
OtherUsefulCommands
Examples
Inthefileusers:
jdoeJohnDoe4/15/96
lsmithLauraSmith3/12/96
pchenPaulChen1/5/96
jhsuJakeHsu4/17/96
sphilipSuePhillip4/2/96
sortusersyieldsthefollowing:
jdoeJohnDoe4/15/96
jhsuJakeHsu4/17/96
lsmithLauraSmith3/12/96
pchenPaulChen1/5/96
sphilipSuePhillip4/2/96
If,however,alistingsortedbylastnameisdesired,usetheoptiontospecifywhichfieldtosorton(fieldsarenumberedstartingat0):%sort+2users:pchenPaulChen1/5/96jdoeJohnDoe4/15/96jhsuJakeHsu4/17/96sphilipSuePhillip4/2/96
lsmithLauraSmith3/12/96
Tosortinreverseorder:%sort-rusers:sphilipSuePhillip4/2/96pchenPaulChen1/5/96lsmithLauraSmith3/12/96jhsuJakeHsu4/17/96jdoeJohnDoe4/15/96
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
106/173
-
7/31/2019 Unix Beginers
107/173
OtherUsefulCommands
8.1.9tee-copycommandoutputteesendsstandardintospecifiedfilesandalsotostandardout.Itsoftenusedincommandpipelines.
Syntax
tee[options][file[s]]
CommonOptions-aappendtheoutputtothefiles-iignoreinterruptsExamplesInthisfirstexampletheoutputofwhoisdisplayedonthescreenandstoredinthefileusers.file:
brigadier:condron[55]>who|teeusers.file
condronttyp0Apr2214:10(lcondron-pc.acs.)frankttyp1Apr2216:19(nyssa)condronttyp9Apr2215:52(lcondron-mac.acs)
brigadier:condron[56]>catusers.filecondronttyp0Apr2214:10(lcondron-pc.acs.)frankttyp1Apr2216:19(nyssa)condronttyp9Apr2215:52(lcondron-mac.acs)
Inthisnextexampletheoutputofwhoissenttothefilesusers.aandusers.b.Itisalsopipedtothewccommand,whichreportsthelinecount.
brigadier:condron[57]>who|teeusers.ausers.b|wc-l3
brigadier:condron[58]>catusers.acondronttyp0Apr2214:10(lcondron-pc.acs.)frankttyp1Apr2216:19(nyssa)condronttyp9Apr2215:52(lcondron-mac.acs)
brigadier:condron[59]>catusers.bcondronttyp0Apr2214:10(lcondron-pc.acs.)frankttyp1Apr2216:19(nyssa)condronttyp9Apr2215:52(lcondron-mac.acs)
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
108/173
WorkingWithFiles
Inthefollowingexamplealongdirectorylistingissenttothefilefiles.long.ItisalsopipedtothegrepcommandwhichreportswhichfileswerelastmodifiedinAugust.
brigadier:condron[60]>ls-l|teefiles.long|grepAug
1drwxr-sr-x2condron512Aug81995News/2-rw-r--r--1condron1076Aug81995magnus.cshrc2-rw-r--r--1condron1252Aug81995magnus.loginbrigadier:condron[63]>catfiles.longtotal342-rw-r--r--1condron1253Oct101995#.login#1drwx------2condron512Oct171995Mail/1drwxr-sr-x2condron512Aug81995News/
5-rw-r--r--1condron4299Apr2100:18editors.txt2-rw-r--r--1condron1076Aug81995magnus.cshrc2-rw-r--r--1condron1252Aug81995magnus.login7-rw-r--r--1condron6436Apr2123:50resources.txt4-rw-r--r--1condron3094Apr1818:24telnet.ftp
1drwxr-sr-x2condron512Apr2123:56uc/1-rw-r--r--1condron1002Apr2200:14uniq.tee.txt1-rw-r--r--1condron1001Apr2015:05uniq.tee.txt~7-rw-r--r--1condron6194Apr1520:18unixgrep.txt
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
109/173
OtherUsefulCommands
8.1.10uniq-removeduplicatelinesuniqfiltersduplicateadjacentlinesfromafile.
Syntax
uniq[options][+|-n]file[file.new]
CommonOptions-donecopyofonlytherepeatedlines-uselectonlythelinesnotrepeated+nignorethefirstncharacters-snsameasabove(SVR4only)-nskipthefirstnfields,includinganyblanks(&)-ffieldssameasabove(SVR4only)
Examples
Considerthefollowingfileandexample,inwhichuniqremovesthe4thlinefromfileandplacestheresultinafilecalledfile.new.
{unixprompt1}catfile1236453678907890
{unixprompt2}uniqfilefile.new
{unixprompt3}catfile.new123645367890
Below,the-noptionoftheuniqcommandisusedtoskipthefirst2fieldsinfile,andfilteroutlineswhichareduplicatesfromthe3rdfieldonward.
{unixprompt4}uniq-2file12367890
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
110/173
WorkingWithFiles
8.1.11strings-findASCIIstringsTosearchabinaryfileforprintable,ASCII,stringsusethestringscommand.Itsearchesforanysequenceof4ormoreASCIIcharactersterminatedbyaornullcharacter.IfindthiscommandusefulforsearchingforfilenamesandpossibleerrormessageswithincompiledprogramsthatIdonthavesourcecodefor.
Syntaxstrings[options]fileCommonOptions-nnumber-number-tformat-ousenumberastheminimumstringlength,ratherthan4(SVR4only)sameasaboveprecedethestringwiththebyteoffsetfromthestartofthefile,whereformatisoneof:d=decimal,o=octal,x=hexadecimal(SVR4only)
precedethestringwiththebyteoffsetindecimal(BSDonly)Examples%strings/bin/cut
SUNW_OST_OSCMDnodelimiterspecifiedinvaliddelimiterb:c:d:f:nscut:-nmayonlybeusedwith-bcut:-dmayonlybeusedwith-fcut:-smayonlybeusedwith-fnolistspecifiedcut:cannotopen%s
invalidrangespecifiertoomanyrangesspecifiedrangesmustbeincreasinginvalidcharacterinrangeInternalerrorprocessinginputinvalidmultibytecharacterunabletoallocateenoughmemoryunabletoallocateenoughmemorycut:usage:cut-blist[-n][filename...]
cut-clist[filename...]cut-flist[-ddelim][-s][filename]
IntroductiontoUnix1998UniversityTechnologyServices,TheOhioStateUniversity
-
7/31/2019 Unix Beginers
111/173
OtherUsefulCommands
8.1.12file-filetypeThisprogram,file,examinestheselectedfileandtriestodeterminewhattypeoffileitis.Itdoesthisbyreadingthefirstfewbytesofthefileandcomparingthemwiththetablein/etc/magic.ItcandetermineASCIItextfiles,tarformattedfiles,compressedfiles,etc.
Syntax
file[options][-mmagic_file][-ffile_list]file
CommonOptions-ccheckthemagicfileforerrorsinformat-ffile_listfile_listcontainsalistoffilestoexamine-hdontfollowsymboliclinks(SVR4only)-Lfollowsymboliclinks(BSDonly)-mmagic_fileusemagic_fileasthemagicfileinsteadof/etc/magic
Examples
Belowwelisttheoutputfromthecommand"filefilename"forsomerepresentativ
efiles./etc/magic:asciitext/usr/local/bin/gzip:SundemandpagedSPARCexecutabledynamicallylinked/usr/bin/cut:ELF32-bitMSBexecutableSPARCVersion1,dynamicallylinked,strippedsource.tar:USTARtararchivesource.tar.Z:compresseddatablockcompressed16bits
8.1.13tr-translatecharactersThetrcommandtranslatescharactersfromstdintostdout.
Syntax
tr[options]string1[string2]
Withnooptionsthecharactersinstring1aretranslatedintothecharactersinstring2,characterbycharacterinthestringarrays.Thefirstcharacterinstring1istranslatedintothefirstcharacterinstring2,etc.
Arangeofcharactersinastringisspecifiedwithahyphenbetweentheupperandlowercharactersoftherange,e.g.tospecifyalllowercasealphabeticcharactersuse[a-z].
Repeatedcharactersinstring2canberepresentedwiththe[x*n]notation,wherec
haracterxisrepeatedntimes.Ifnis0orabsentitisassumedtobeaslargeasneededtomatchstring1.
1998UniversityTechnologyServices,TheOhioStateUniversityIntroductiontoUnix
-
7/31/2019 Unix Beginers
112/173
WorkingWithFiles
Characterscaninclude\octal(BSDandSVR4)and\character(SVR4only)notation.Here"octal"isreplacedbytheone,two,orthreeoctalintegersequenceencodingtheASCIIcharacterand
"character"canbeoneof:bbackspacefformfeednnewlinercarriagereturnttabvverticaltab
TheSVR4versionoftrallowstheoperand":class:"inthestringfieldwhereclasscantakeoncharacterclassificationvalues,including:
alphaalphabeticcharacterslowerlowercasealphabeticcharactersupperuppercasealphabeticcharacters
CommonOptions-ccomplementthecharactersetinstring1-ddeletethecharactersinstring1-ssqueezeastringofrepeatedcharactersinstring1toasinglecharacter
Examples
Thefollowingexampleswilluseasinputthefile,alistofP.G.WodehouseJeeves&Woosterbooks.
TheInimitableJeev