Professional Documents
Culture Documents
Tableofcontents
2UNIXCONCEPTS
BasicUnixCommands:
Manualcommand.
manmanThisishelpcommand,andwillexplainsyouaboutonlinemanualpagesyoucan alsousemaninconjunctionwithanycommandtolearnmoreaboutthatcommandfor example.
manlswillexplainaboutthelscommandandhowyoucanuseit. mankpatterncommandwillsearchforthepatterningivencommand.
Bannercommand.
bannerprintscharactersinasortofasciiartposter,forexampletoprintwaitinbigletters.I willtype bannerwaitatunixcommandlineorinmyscript.Thisishowitwilllook.
Calcommand
Clearcommand
clearcommandclearsthescreenandputscursoratbeginningoffirstline.
3UNIXCONCEPTS
Nohupcommand.
nohupcommandifaddedinfrontofanycommandwillcontinuerunningthecommandor processevenifyoushutdownyourterminalorcloseyoursessiontomachine.Forexmaple, ifIwanttorunajobthattakeslotoftimeandmustberunfromterminalandiscalled update_entries_tonight. nohupupdate_entries_tonightwillrunthejobevenifterminalisshutdowninmiddleofthis job.
Ttycommand
Pwdcommand.
pwdcommandwillprintyourhomedirectoryonscreen,pwdmeansprintworkingdirectory.
/u0/ssb/sandeep is output for the command when I use pwd in /u0/ssb/sandeep directory.
Lscommand
lscommandismostwidelyusedcommandanditdisplaysthecontentsofdirectory.
options
lswilllistallthefilesinyourhomedirectory,thiscommandhasmanyoptions. lslwilllistallthefilenames,permissions,group,etcinlongformat. lsawilllistallthefilesincludinghiddenfilesthatstartwith.. lsltwilllistallfilesnamesbasedonthetimeofcreation,newerfilesbringfirst. lsFxwilllistfilesanddirectorynameswillbefollowedbyslash. lsRwilllistsallthefilesandfilesintheallthedirectories,recursively. lsR|morewilllistallthefilesandfilesinallthedirectories,onepageatatime.
command. mkdir sandeep will create new directory, i.e. here sandeep directory is created.
Mkdir
Cdcommand.
Headcommand.
headfilenamebydefaultwilldisplaythefirst10linesofafile. Ifyouwantfirst50linesyoucanusehead50filenameorfor37lineshead37filenameandso forth.
Tailcommand.
tailfilenamebydefaultwilldisplaythelast10linesofafile. Ifyouwantlast50linesthenyoucanusetail50filename.
Morecommand.morecommandwilldisplayapageatatimeandthenwaitforinputwhichis
morefilename
spacebar.Forexampleifyouhaveafilewhichis500linesandyouwanttoreaditall.Soyoucan use
Wccommand
wccommandcountsthecharacters,wordsorlinesinafiledependingupontheoption.
Options
wclfilenamewillprinttotalnumberoflinesinafile. wcwfilenamewillprinttotalnumberofwordsinafile. wccfilenamewillprinttotalnumberofcharactersinafile.
Filecommand.
filecal.txt
cal.txt: ascii text
Cpcommand.
cpcommandcopiesafile.IfIwanttocopyafilenamedoldfileinacurrentdirectorytoafile namednewfileinacurrentdirectory.
Rcpcommand.
rcpcommandwillcopyfilesbetweentwounixsystemsandworksjustlikecpcommand(pandi optionstoo). ForexampleyouareonaunixsystemthatiscalledCheetahandwanttocopyafilewhichisin currentdirectorytoasystemthatiscalledlionin/usr/john/directorythenyoucanusercp command rcpfilenamelion:/usr/john Youwillalsoneedpermissionsbetweenthetwomachines.Formoreinfortypemanrcpat commandline.
Lncommand.
Some examples:
lnsfileonefiletwowillcreateasymboliclinkandcanexistacrossmachines. lnnoptionwillnotoverwriteexistingfiles. lnfwillforcethelinktooccur.
Mvcommand.
mvcommandisusedtomoveafilefromonedirectorytoanotherdirectoryortorenameafile.
Some examples:
mvoldfilenewfilewillrenameoldfiletonewfile. mvioldfilenewfileforconfirmationprompt. mvfoldfilenewfilewillforcetherenameeveniftargetfileexists. mv*/usr/bajwa/willmoveallthefilesincurrentdirectoryto/usr/bajwadirectory.
Rmcommand.
Todeletefilesusermcommand.
6UNIXCONCEPTS
Options:
rmoldfilewilldeletefilenamedoldfile. rmfoptionwillremovewriteprotectedfileswithoutprompting. rmroptionwilldeletetheentiredirectoryaswellasallthesubdirectories,verydangerous command.
Rmdircommand.
Options:
Diffcommand.
diffcommandwillcomparethetwofilesandprintoutthedifferencesbetween. HereIhavetwoasciitextfiles.fileoneandfiletwo. Contentsoffileoneare
This this this this this is is is is is first file second line third line different as;lkdjf not different
filetwocontains
This this this this this is is is is is first file second line third line different xxxxxxxas;lkdjf not different
difffileonefiletwowillgivefollowingoutput
4c4 < this is different --> this is different as;lkdjf xxxxxxxas;lkdjf
Cmpcommand.
cmpcommandcomparesthetwofiles.ForexmapleIhavetwodifferentfilesfileoneandfiletwo. cmpfileonefiletwowillgiveme
7UNIXCONCEPTS
fileone filetwo differ: char 80, line 4
DircmpCommand.
dircmpcommandcomparestwodirectories.Ifihavetwodirectoriesinmyhomedirectorynamed dironeanddirtwoandeachhas510filesinit.Then dircmpdironedirtwowillreturnthis
Dec 9 16:06 1997 dirone only and dirtwo only Page 1 ./fourth.txt ./rmt.txt ./te.txt ./third.txt
GrepCommand
Options:
boptionwillprecedeeachlinewithitsblocknumber.
Findcommand.
Findcommandisaextremelyusefulcommand.youcansearchforanyfileanywhereusingthis commandprovidedthatfileanddirectoryyouaresearchinghasreadwriteattributessettoyou ,your,grouporall.Finddescendsdirectorytreebeginningateachpathnameandfindsthefilesthat meetthespecifiedconditions.Herearesomeexamples.
Some Examples:
conditions of find
atime+n|n|nwillfindfilesthatwerelastaccessedmorethannorlessthanndaysorn days. ctime+nornwillfindthatwerechanged+nnorndaysago. depthdescendthedirectorystructure,workingonactualfilesfirstandthendirectories.You canuseitwithcpiocommand. execcommad{}\;runtheUnixcommandoneachfilematchedbyfind.Veryuseful condition. printprintorlisttostandardoutput(screen). namepatternfindthepattern. permnnnfindfileswholepermissionflagsmatchoctalnumbernnn. sizenfindfilesthatcontainnblocks. typecFindfilewholetypeisc.Ccouldbeborblock,cCharacterspecialfile,ddirectory, pfifoornamedpipe,lsymboliclink,orfplainfile.
Cutcommand.
Examples: cutc1,4testfilewillprintthistostandardoutput(screen)
9UNIXCONCEPTS
ts ts ts
Itisprintingcolumns1and4ofthisfilewhichcontainstands(partofthis).
Options:
clistcutthecolumnpositionsidentifiedinlist. flistwillcutthefieldsidentifiedinlist. scouldbeusedwithftosuppresslineswithoutdelimiters.
PasteCommand.
pastecommandmergethelinesofoneormorefilesintoverticalcolumnsseparatedbyatab. forexampleifafilenamedtestfilecontains
this is firstline
andafilenamedtestfile2contains
this is testfile2
itcontainscontentsofbothfilesincolumns. who|pastewilllistusersintwocolumns.
Options:
d'char'separatecolumnswithcharinsteadofatab. smergesubsequentlinesfromonefile.
Sortcommand.
sortcommandsortthelinesofafileorfiles,inalphabeticalorder.forexampleifyouhaveafile namedtestfilewiththesecontents
zzz aaa 1234 yuer wer qww wwe
10UNIXCONCEPTS
aaa qww wer wwe yuer zzz
Options:
bignoresleadingspacesandtabs. ccheckswhetherfilesarealreadysorted. dignorespunctuation. iignoresnonprintingcharacters. nsortsinarithmeticorder. ofileputoutputinafile. +m[m]skipsnfieldsbeforesorting,andsortuptofieldpositionm. rreversetheorderofsort. uidenticallinesininputfileapearonlyonetimeinoutput.
Uniqcommand.
Examples
uniqcommandremovesduplicateadjacentlinesfromsortedfilewhilesendingonecopyofeach secondfile.
sortnames|uniqdwillshowwhichlinesappearmorethanonceinnamesfile.
Options:
cprinteachlineonce,countinginstancesofeach. dprintduplicatelinesonce,butnouniquelines. uprintonlyuniquelines.
AwkandNawkcommand.
awkismorelikeascriptinglanguagebuiltinonallunixsystems.Althoughmostlyusedfortext processing,etc. Herearesomeexampleswhichareconnectedwithothercommands.
Examples:
11UNIXCONCEPTS
Sedcommand.
sedcommandlaunchesastreamlineeditorwhichyoucanuseatcommandline. youcanenteryoursedcommandsinafileandthenusingfoptionedityourtextfile.Itworksas sed[options]files
options:
e'instruction'Applytheeditinginstructiontothefiles. fscriptApplythesetofinstructionsfromtheeditingscript. nsuppressdefaultoutput. formoreinformationaboutsed,entermansedatcommandlineinyoursystem.
Vieditor.
vicommandlaunchesavisualeditor.Toeditafiletype vifilename vieditorisadefaulteditorofallUnixsystems.Ithasseveralmodes.Inordertowritecharactersyou willneedtohititobeininsertmodeandthenstarttyping.Makesurethatyourterminalhascorrect settings,vt100emulationworksgoodifyouareloggedinusingpc. Onceyouaredonetypingthentobeincommandmodewhereyoucanwrite/search/youneedtohit :wfilenametowrite andincaseyouaredonewritingandwanttoexit :w!willwriteandexit.
options:
iforinsertmode. Iinsertstextatthecurson Aappendstextattheendoftheline. aappendstextaftercursor. Oopenanewlineoftextabovethecurson. oopenanewlineoftextbelowthecurson. :forcommandmode. <escape>toinvokecommandmodefrominsertmode. :!shtorununixcommands. xtodeleteasinglecharacter. ddtodeleteanentireline nddtodeletennumberoflines. d$todeletefromcursortoendofline. yytocopyalinetobuffer. Ptopastetextfrombuffer. nyycopynnumberoflinestobuffer. :%s/stringA/stringb/gtoreplacestringAwithstringBinwholefile. Gtogotolastlineinfile. 1Gtogotothefirstlineinfile. wtomoveforwardtonextword.
Shellprogrammingconceptsandcommands.
ShellprogrammingisintegralpartofUnixoperatingsystems.Shelliscommandlineuserinterface toUnixoperatingsystem,UserhaveanoptionofpickinganinterfaceonUnixsuchasksh,csh,or defaultsh.,thesearecalledshells(interface).Shellprogrammingisusedtoautomatemanytasks. Shellprogrammingisnotaprogramminglanguageinthetruestsenseofwordsinceitisnot compiledbutratheraninterpretedlanguage.UnixwaswritteninClanguageandthusclanguageis integralpartofunixandavailableonallversions.Shells,likekshandcsharepopularshellsonunix althoughthereare5or6differentshellsavailablebutIwillonlybediscussingkshandcshaswell assh.Commonfeaturesamongallshellsarejobcontrol,forexampleifIamrunningaprocesses whichissearchingthewholesystemfor.Zfilesandoutputisdirectedtoafilenamed compressedfiles.
example:
find/name*.Zprint>compressedfiles thenafterenteringthiscommandhitting <controlz> keywillsuspendthisjob,thenentering bg atcommandlinewillputthisjobinbackground,entering fg willputthisjobinforeground.Entering jobs atcommandlinewillshowmeallmyconcurrentjobsthatarerunning. Othercommonfeatures >willredirectoutputfromstandardout(screen)tofileorprinterorwhateveryou like. >>filenamewillappendattheendofafilecalledfilename. <willredirectinputtoaprocessorcommnand. |pipeoutput,orredirectoutput,goodforjoiningcommands,i.e.findcommandwith cpio,etc. &attheendofcommandwillruncommandinbackground. ;willseparatecommandsonsameline. *willmatchanycharactersinafileordirectories.junk*willmatchallfileswithfirst 4letters ?willmatchsinglecharactersinafile. []willmatchanycharactersenclosed. ()executeinsubshell. ``torunacommandinsideanothercommandanduseitsoutput. ""partialquoteforvariables. ''fullquoteforvariables.
13UNIXCONCEPTS #begincomment(if#/bin/kshorcshorshisenteredatfirstlineofscriptitruns scriptinthatshell) bgbackgroundexecution. breakbreakfromloopstatements. continueResumeaprogramloop. Killpidnumberwillterminaterunningjobs stopwillstopbackgroundjob. suspendwillsuspendforegroundjob. waitwillwaitforabackgroundjobtofinish.
BourneShell(shshell).
shorBourneshellisdefaultshellofUnixoperatingsystemsandisthemostsimplestshellinUnix systems. Examples: cd;lsexecuteoneafteranother. (date;who;pwd)>logifilewillredirectalltheoutputfromthreecommandstoafilenamed logfile. sortfile|lpwillfirstsortafileandthenprintit. alias[options][name[='command']]willletyoucreateyourowncommands.i.e. aliasll="lsla"willexecute`lsla`commandwheneverllisentered. letexpressionsissyntaxofletstatement. leti=i+1willworkasacounterwithiincrementingeachtimethisstatementis encountered. forx[inlist]docommandsdoneissyntaxforfordoloop. functionname {commands;}isthesyntaxofafunctionwhichcanbecalledfrom anywhereinprogram. ifcondition1thencommands1elifcondition2thencommands2.........elsecommands3fi
Kshshell(Korn). CshorCshell
KshorKornshelliswidelyusedshell.
cshissecondmostusedshell.
Echocommand
echocommandinshellprogramming.
14UNIXCONCEPTS
Linecommand.
linecommandinshellprogramming.
Sleepcommand.
sleepcommandinshellprogramming.
TestCommand.
testcommandinshellprogramming.
CCcompiler(cprogramminglanguagecompiler).
SinceUnixisitselfwritteninCprogramminglanguage,mostUnixoperatingsystemscomewithc compilercalledcc.
Cucommand.
cucommandisusedforcommunicationsoveramodemordirectlinewithanotherUnixsystem. Syntaxis cuoptionsdestination Options bnprocesslinesusingnbitcharacters(7or8). cnameSearchUUCP'sdevicefileandselectlocalareanetworkthatmatchesname. dPrintsdiagnostics. esendsevenparitydatatoremotesystem llinecommunicateonthisdevice(line=/dev/tty001,etc) npromptsforatelephonenumber. snsettransmissionrateton(e.g1200,2400,9600,BPS)
Ftpcommand(protocol).
ftpcommandisusedtoexecuteftpprotocolusingwhichfilesaretransferredovertwosystems. Syntaxis ftpoptionshostname options denabledebugging. gdisablefilenameglobbing. iturnoffinteractiveprompts.
Logincommand.
logincommandinvokesaloginsessiontoaUnixsystem,whichthenauthenticatesthelogintoa system.Systempromptsyoutoenteruseridandpassword.
Rlogincommand.
Talkcommand.
talkcommandisusedtoinvoketalkprogramavailableonallunixsystemwhichletstwousers exchangeinformationbackandforthinrealtime.Syntaxis talkuserid@hostname
Telnetcommand.
Telnetcommandinvokesatelnetprotocolwhichletsyoulogontodifferentunix,vmsorany machineconnectedoverTCP/IPprotocol,IPxprotocolorotherwise.Syntaxis telnethostname
Vacationcommand.
vacationcommandisusedwhenyouareoutofoffice.Itreturnsamailmessagetosender announcingthatyouareonvacation.todisablethisfeature,typemailF"". syntaxis vacationoptions Options dwillappendthedatetothelogfile. Fuserwillforwardmailtouserwhenunabletosendmailtomailfile. llogfilewillrecordinthelogfilethenamesofsenderswhoreceivedautomaticreply.
16UNIXCONCEPTS mmailfilewillsavereceivedmessagesinmailfile.
Writecommandwillinitiateaninteractiveconversationwithuser.Syntaxis
writeusertty
ompresscommand.
Compresscommandcompressesafileandreturnstheoriginalfilewith.zextension,touncompress thisfilename.Zfileuseuncompressfilenamecommand.syntaxforcompresscommandis compressoptionsfiles Options bnlimitthenumberofbitsincodington. cwritetostandardoutput(donotchangefiles). fcompressconditionally,donotpromptbeforeoverwritingfiles. vPrinttheresultingpercentageofreductionforfiles.
Uncompresscommand.
Uncompressfileuncompressesafileandreturnittoitsoriginalform. syntaxis uncompressfilename.Zthisuncompressesthecompressedfiletoitsoriginalname. Options cwritetostandardoutputwithoutchangingfiles
Cpiocommand.
cpiocommandisusefultobackupthefilesystems.Itcopyfilearchivesinfromorouttotapeor disk,ortoanotherlocationonthelocalmachine.Itssyntaxis cpioflags[options] Ithasthreeflags,i,o,p cpioi[options][patterns] cpioicopyinfileswhonamesmatchselectedpatterns. Ifnopatternisusedallfilesarecopiedin. Itisusedtowritetoatape. cpioo Copyoutalistoffileswhosenamearegivenonstandardoutput. cpiop copyfilestoanotherdirectoryonthesamesystem. Options aresetaccesstimesofinputfiles. Aappendfilestoanarchive(mustusewitho). bswapbytesandhalfwords.Wordsare4bytes.
17UNIXCONCEPTS Bblockinputoroutputusing5120bytesperrecord. cReadorwriteheaderinformationasAsciicharacter. dcreatedirectoriesasneeded. llinkfilesinsteadofcopying. ofiledirectoutputtoafile. rrenamefilesinteractively. RIDreassignfileownershipandgroupinformationtotheuser'sloginID. Vprintadotforeachfilereadorwritten. sswapbytes. Sswaphalfbytes. vprintalistoffilenames. Examples find.name"*.old"print|cpioocvB>/dev/rst8willbackupall*.oldfilestoatape in/dev/rst8 cpioicdv"save""</dev/rst8willrestoreallfileswhosenamecontain"save" find.depthprint|cpiopadm/mydirwillmoveadirectorytree.
Dumpcommandisusefultobackupthefilesystems.
dumpcommandcopiesallthefilesinfilesystemthathavebeenchangedafteracertaindate.Itis goodforincrementalbackups.Thisinformationaboutdateisderivedfrom/var/adm/dumpdates and/etc/fstab. syntaxforHPUXdumpis /usr/sbin/dump[option[argument...]filesystem] Options 09Thisnumberisdumplevel.0optioncausesentirefilesystemtobedumped. bblockingfactortakenintoargument. ddensityoftapedefaultvalueis1600. fplacethedumponnextargumentfileinsteadoftape. Thisexamplecausestheentirefilesystem(/mnt)tobedumpedon/dev/rmt/c0t0d0BEST andspecifiesthatthedensityofthetapeis6250BPI. /usr/sbin/dump0df6250/dev/rmt/c0t0d0BEST/mnt formoreinfotypemandumpatcommandline.
Packcommand.
packcommandcompactseachfileandcombinethemtogetherintoafilename.zfile.Theoriginal fileisreplaced.Pcatandunpackwillrestorepackedfilestotheiroriginalform. Syntaxis Packoptionsfiles Options Printnumberoftimeseachbyteisused,relativefrequencyandbytecode. fForcethepackevenwhendiskspaceisn'tsaved.
Tarcommand.
Examples:
tarcvf/dev/rmt/0/bin/usr/bincreatesanarchiveof/binand/usr/bin,andstoreonthetapein /dev/rmt0. tartvf/dev/rmt0willlistthetape'scontentina/dev/rmt0drive. tarcvf'find.print'>backup.tarwillcreatesanarchiveofcurrentdirectoryandstoreitinfile backup.tar.
Functions:
ccreatesanewtape. rappendfilestoatape. tprintthenamesoffilesiftheyarestoredonthetape. xextractfilesfromtape.
Options:
bnuseblockingfactorofn. lprinterrormessagesaboutlinksnotfound. Lfollowsymboliclinks. vprintfunctionletter(xforextractionoraforarchive)andnameoffiles.
Mtcommand
Mtcommandisusedfortapeandotherdevicefunctionslikerewinding,ejecting,etc.Itgive commandstotapedeviceratherthantapeitself.MtcommandisBSDcommandandisseldom foundinsystemVunixversions. syntaxis mt[ttapename]command[count] mtforHPUXacceptfollowingcommands eofwritecountEOFmarks. fsfForwardspacecountfiles. fsrForwardspacecountrecords. bsfBackwardspacecountfiles. bsrBackwardspacecountrecords. rewRewindtape. offlRewindtapeandgooffline.
Atcommand.
atcommandalongwithcrontabcommandisusedtoschedulejobs. atoptionstime[ddate][+increment]issyntaxofatcommand. forexampleifIhaveascriptnamedusersloggedinwhichcontains.
#!/bin/ksh who | wc -l echo "are total number of people logged in at this time."
Chmodcommand.
chmodcommandisusedtochangepermissionsonafile. forexampleifIhaveatextfilewithcalenderinitcalledcal.txt. initiallywhenthisfilewillbecreatedthepermissionsforthisfiledependsuponumasksetinyour profilefiles.Asyoucanseethisfilehas666orrwrwrwattributes. lslacal.txt
-rw-rw-rw1 ssb dxidev 135 Dec 3 16:14 cal.txt
Chgrpcommand.
Chowncommand.
Crontabcommand.
Minutes
crontabcommandisusedtoschedulejobs.Youmusthavepermissiontorunthiscommandbyunix Administrator.Jobsarescheduledinfivenumbers,asfollows.
0-59 Hour Day of month month Day of week 1-31 0-23 1-12 0-6 (0 is sunday)
21UNIXCONCEPTS
Datecommand.
Datedisplaystodaysdate,touseittypedateatprompt.
Sun Dec 7 14:23:08 EST 1997
issimilartowhatyoushouldseeonscreen.
Dfcommand.
dfcommanddisplaysinformationaboutmountedfilesystems.Itreportsthenumberoffreedisk blocks.TypicallyaDiskblockis512bytes(or1/2Kilobyte). syntaxis dfoptionsname Options bwillprintonlythenumberoffreeblocks. ewillprintonlythenumberoffreefiles. fwillreportfreeblocksbutnotfreeinodes. Ftypewillreportonanumountedfilesystemspecifiedbytype. kwillprintallocationinkilobytes. lwillreportonlyonlocalfilesystems. nwillprintonlythefilesystemnametype,withnoargumentsitliststypeofallfilesystems
Ducommand.
ducommanddisplaysdiskusage.
Envcommand.
envcommanddisplaysallthevariables.
Fingercommand.
fingercommand.
PScommand
22UNIXCONCEPTS
Ruptimecommand.
ruptimecommandtellsthestatusoflocalnetworkedmachines. ruptimeoptions options. aincludeuserevenifthey'vebeenidleformorethanonehour. lsortbyloadaverage. rreversethesortorder. tsortbyuptime. isortbynumberofusers.
Shutdowncommand.
Shutdowncommandcanonlybeexecutedbyroot.Togracefullybringdownasystem,shutdown commandisused. options. gnuseagraceperiodofnseconds(defaultis60). iktelltheinitcommandtoplacesysteminastatek. ssingleuserstate(default) 0shutdownforpoweroff. 1likes,butmountmultiuserfilesystems. 5stopsystem,gotofirmwaremode. 6stopsystemthenreboot. ysuppressthedefaultpromptforconfirmation.
Sttycommand
sttycommandsetsterminalinputoutputoptionsforthecurrentterminal.withoutoptionsstty reportsterminalsettings. sttyoptionsmodes<device options areportalloptions. greportcurrentsettings. Modes 0hangupphone. nsetterminalbaud. erasekeyname,willchangeyourkeynametobebackspacekey.
Whocommand
whocommanddisplaysinformationaboutthecurrentstatusofsystem. whooptionsfile
Command Cd cd ~ cd / cd /root
Function returnsyoutoyourlogindirectory alsoreturnsyoutoyourlogindirectory takesyoutotheentiresystem'srootdirectory takesyoutothehomedirectoryoftheroot,orsuperuser, accountcreatedatinstallation;youmustbetherootuser toaccessthisdirectory takesyoutothehomedirectory,whereuserlogin directoriesareusuallystored movesyouuponedirectory takesyoutootheruser'slogindirectory,ifotheruserhas grantedyoupermission regardlessofwhichdirectoryyouarein,thisabsolute pathwouldtakeyoustraighttosubdirfoo,a subdirectoryofdir1 thisrelativepathwouldtakeyouuptwodirectories,then todir3,thentothedir2directory.
cd ../../dir3/dir2
24UNIXCONCEPTS 4.morefilenameshowsthefirstpartofafile,justasmuchaswillfitononescreen.Justhitthe spacebartoseemoreorqtoquit.Youcanuse/patterntosearchforapattern. mvfilename1filename2movesafile(i.e.givesitadifferentname,ormovesitintoadifferent directory(seebelow) cpfilename1filename2copiesafile rmfilenameremovesafile.Itiswisetousetheoptionrmi,whichwillaskyoufor confirmationbeforeactuallydeletinganything.Youcanmakethisyourdefaultbymakingan aliasinyour.cshrcfile. difffilename1filename2comparesfiles,andshowswheretheydiffer wcfilenametellsyouhowmanylines,words,andcharactersthereareinafile chmodoptionsfilenameletsyouchangetheread,write,andexecutepermissionson yourfiles.Thedefaultisthatonlyyoucanlookatthemandchangethem,butyoumay sometimeswanttochangethesepermissions.Forexample,chmodo+rfilenamewillmake thefilereadableforeveryone,andchmodorfilenamewillmakeitunreadableforothers again.Notethatforsomeonetobeabletoactuallylookatthefilethedirectoriesitisinneed tobeatleastexecutable.Seehelpprotectionformoredetails. FileCompression gzipfilenamecompressesfiles,sothattheytakeupmuchlessspace.Usuallytextfiles compresstoabouthalftheiroriginalsize,butitdependsverymuchonthesizeofthefile andthenatureofthecontents.Thereareothertoolsforthispurpose,too(e.g.compress), butgzipusuallygivesthehighestcompressionrate.Gzipproducesfileswiththeending'.gz' appendedtotheoriginalfilename. gunzipfilenameuncompressesfilescompressedbygzip. gzcatfilenameletsyoulookatagzippedfilewithoutactuallyhavingtogunzipit(same asgunzipc).Youcanevenprintitdirectly,usinggzcatfilename|lpr printing lprfilenameprint.UsethePoptiontospecifytheprinternameifyouwanttousea printerotherthanyourdefaultprinter.Forexample,ifyouwanttoprintdoublesided,use 'lprPvalkyrd',orifyou'reatCSLI,youmaywanttouse'lprPcord115d'.See'help printers'formoreinformationaboutprintersandtheirlocations. lpqcheckouttheprinterqueue,e.g.togetthenumberneededforremoval,ortoseehow manyotherfileswillbeprintedbeforeyourswillcomeout lprmjobnumberremovesomethingfromtheprinterqueue.Youcanfindthejobnumber byusinglpq.Theoreticallyyoualsohavetospecifyaprintername,butthisisn'tnecessaryas longasyouuseyourdefaultprinterinthedepartment. genscriptconvertsplaintextfilesintopostscriptforprinting,andgivesyousomeoptions forformatting.Considermakinganaliaslikealiasecop'genscript2r\!*|lprh Pvalkyr'toprinttwopagesononepieceofpaper. dvipsfilenameprint.dvifiles(i.e.filesproducedbyLaTeX).Youcanusedviselectto printonlyselectedpages.SeetheLaTeXpageformoreinformationabouthowtosavepaper whenprintingdrafts. GREP grep[options]pattern[files]
Options
a,text Don'tsuppressoutputlineswithbinarydata;treatastext. b,byteoffset Printthebyteoffsetwithintheinputfilebeforeeachlineofoutput. c,count Printonlyacountofmatchedlines.Withvorrevertmatchoption,count nonmatchinglines. daction,directories=action Defineanactionforprocessingdirectories.Possibleactionsare: read Readdirectorieslikeordinaryfiles(default). skip Skipdirectories. recurse Recursivelyreadallfilesundereachdirectory.Sameasr. epattern,regexp=pattern Searchforpattern.Sameasspecifyingapatternasanargument,butusefulinprotecting patternsbeginningwith. ffile,file=file Takealistofpatternsfromfile,oneperline. h,nofilename Printmatchedlinesbutnotfilenames(inverseofl). i,ignorecase
26UNIXCONCEPTS Ignoreuppercaseandlowercasedistinctions. l,fileswithmatches Listthenamesoffileswithmatchesbutnotindividualmatchedlines;scanningperfile stopsonthefirstmatch. mmap Trytousememorymapping(mmap)toreadinputinordertosavetime. n,linenumber Printlinesandtheirlinenumbers. q,quiet,silent Suppressnormaloutputinfavorofquietmode;scanningstopsonthefirstmatch. r,recursive Recursivelyreadallfilesundereachdirectory.Sameasdrecurse. s,nomessages Suppresserrormessagesaboutnonexistentorunreadablefiles. v,invertmatch Printalllinesthatdon'tmatchpattern. w,wordregexp Matchonwholewordsonly.Wordsaredividedbycharactersthatarenotletters,digits, orunderscores. x,lineregexp Printlinesonlyifpatternmatchestheentireline. Anum,aftercontext=num Printnumlinesoftextthatoccurafterthematchingline. Bnum,beforecontext=num Printnumlinesoftextthatoccurbeforethematchingline. C[num],context[=num],num Printnumlinesofleadingandtrailingcontext.Defaultcontextis2lines. E,extendedregexp
27UNIXCONCEPTS Actlikeegrep,recognizingextendedregularexpressionssuchas(UN|POS)IXtofind UNIXandPOSIX. F,fixedstrings Actlikefgrep,recognizingonlyfixedstringsinsteadofregularexpressions.Useful whensearchingforcharactersthatgrepnormallyrecognizesasmetacharacters. G,basicregexp Expecttheregularexpressionstraditionallyrecognizedbygrep(thedefault). H,withfilename Display,beforeeachlinefound,thenameofthefilecontainingtheline.Thisisdoneby defaultifmultiplefilesaresubmittedtoasinglegrepcommand. V,version Printtheversionnumberandthenexit. Z,null Whendisplayingfilenames,followeachwithazerobyteinsteadofacolon.
Examples
Listthenumberofuserswhousetcsh: grepc/bin/tcsh/etc/passwd Listheaderfilesthathaveatleastone#includedirective: grepl'^#include'/usr/include/* Listfilesthatdon'tcontainpattern: grepcpatternfiles|grep:0 vmstatreportsinformationaboutprocesses,memory,paging,blockIO,traps,andcpuactivity. vmstat[n][delay[count]] vmstat[V]
28UNIXCONCEPTS
SHELLSCRIPTSINUNIX
Howtowriteshellscript
Followingstepsarerequiredtowriteshellscript: (1)Useanyeditorlikeviormcedittowriteshellscript. (2)Afterwritingshellscriptsetexecutepermissionforyourscriptasfollows syntax: chmodpermissionyourscriptname Examples: $ chmod +x your-script-name $ chmod 755 your-script-name Note:Thiswillsetreadwriteexecute(7)permissionforowner,forgroupandotherpermissionis readandexecuteonly(5). (3)Executeyourscriptas syntax: bashyourscriptname shyourscriptname ./yourscriptname Examples: $ bash bar $ sh bar $ ./bar NOTEInthelastsyntax./meanscurrentdirectory,Butonly.(dot)meansexecutegivencommand fileincurrentshellwithoutstartingthenewcopyofshell,Thesyntaxfor.(dot)commandisas follows
29UNIXCONCEPTS Syntax: .commandname Example: $ . foo Nowyouarereadytowritefirstshellscriptthatwillprint"KnowledgeisPower"onscreen.Seethe commonvicommandlist,ifyouarenewtovi. $ vi first # # My first shell script # clear echo "Knowledge is Power" Aftersavingtheabovescript,youcanrunthescriptasfollows: $ ./first Thiswillnotrunscriptsincewehavenotsetexecutepermissionforourscriptfirst;todothistype command $ chmod 755 first $ ./first Firstscreenwillbeclear,thenKnowledgeisPowerisprintedonscreen. DifferentShellScriptexamples 1.Howtowriteshellscriptthatwilladdtwonos,whicharesuppliedascommandlineargument,andifthistwonosare
notgivenshowerroranditsusage #!/bin/sh
2.
WriteScripttofindoutbiggestnumberfromgiventhreenos.Nosaresuppliesascommandlineargument. Printerrorifsufficientargumentsarenotsupplied.
30UNIXCONCEPTS
if[$n1gt$n2]&&[$n1gt$n3] then echo"$n1isBigestnumber" elif[$n2gt$n1]&&[$n2gt$n3] then echo"$n2isBigestnumber" elif[$n3gt$n1]&&[$n3gt$n2] then echo"$n3isBigestnumber" elif[$1eq$2]&&[$1eq$3]&&[$2eq$3] then echo"Allthethreenumbersareequal" else echo"Icannotfigureoutwhichnumberisbiger" fi 3.writeashellscripttoreadatablefromthedatabasefetchitandstoreitintextfile #!/bin/sh setheaderoff sqlplussarbor/arbor123@custdev<<! Spoolon spool/arbor/scripts/output.txt select*fromemp7; spooloff ! 4.WriteScripttoseecurrentdate,time,username,andcurrentdirectory #!/bin/sh echo"Hello,$LOGNAME" echo"Currentdateis`date`" echo"Useris`whoiam`" echo"Currentdirecotry`pwd`"
31UNIXCONCEPTS
fi n=$1 rev=0 sd=0 while[$ngt0] do sd=`expr$n%10` rev=`expr$rev\*10+$sd` n=`expr$n/10` done echo"Reversenumberis$rev"