You are on page 1of 31

1UNIXCONCEPTS

Tableofcontents

FeaturesofUNIX>2 UNIXCommands>3 ShellScripting>28

2UNIXCONCEPTS

Unixfeaturescontinued... Supportshierarchicalfilesystemtoholduserdataorganisedintheformof directoriesandfiles. Identifiesauserwithauseridandgroupidandallowsaccesspermissionsto resourcestobespecifiedusingtheseids. Supportsacommandlanguageselectableonaperuserbasis.(Example:csh,sh,and ksh) Supportsalargenumberoftools,librariesandutilitiestoaidsoftwaredevelopment.

BasicUnixCommands:

Manualcommand.
manmanThisishelpcommand,andwillexplainsyouaboutonlinemanualpagesyoucan alsousemaninconjunctionwithanycommandtolearnmoreaboutthatcommandfor example.

manlswillexplainaboutthelscommandandhowyoucanuseit. mankpatterncommandwillsearchforthepatterningivencommand.

Bannercommand.
bannerprintscharactersinasortofasciiartposter,forexampletoprintwaitinbigletters.I willtype bannerwaitatunixcommandlineorinmyscript.Thisishowitwilllook.

Calcommand

calcommandwillprintthecalanderoncurrentmonthbydefault.Ifyouwanttoprint calanderofaugustof1965.That'seighthtmonthof1965. cal81965willprintfollowingresults.

Clearcommand

clearcommandclearsthescreenandputscursoratbeginningoffirstline.

3UNIXCONCEPTS

Nohupcommand.
nohupcommandifaddedinfrontofanycommandwillcontinuerunningthecommandor processevenifyoushutdownyourterminalorcloseyoursessiontomachine.Forexmaple, ifIwanttorunajobthattakeslotoftimeandmustberunfromterminalandiscalled update_entries_tonight. nohupupdate_entries_tonightwillrunthejobevenifterminalisshutdowninmiddleofthis job.

Ttycommand

Ttycommandwilldisplayyourterminal.Syntaxis ttyoptions Options lwillprintthesynchronouslinenumber. swillreturnonlythecodes:0(aterminal),1(notaterminal),2(invalidoptions)(goodfor scripts)

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.

cdsandeepwillchangedirectoryfromcurrentdirectorytosandeepdirectory. Usepwdtocheckyourcurrentdirectoryandlstoseeifsandeepdirectoryisthereornot. Youcanthenusecdsandeeptochangethedirectorytothisnewdirectory.

4UNIXCONCEPTS Catcommand catcal.txtcatcommanddisplaysthecontentsofafileherecal.txtonscreen(orstandardout).

Headcommand.
headfilenamebydefaultwilldisplaythefirst10linesofafile. Ifyouwantfirst50linesyoucanusehead50filenameorfor37lineshead37filenameandso forth.

Tailcommand.
tailfilenamebydefaultwilldisplaythelast10linesofafile. Ifyouwantlast50linesthenyoucanusetail50filename.

Morecommand.morecommandwilldisplayapageatatimeandthenwaitforinputwhichis
morefilename

spacebar.Forexampleifyouhaveafilewhichis500linesandyouwanttoreaditall.Soyoucan use

Wccommand

wccommandcountsthecharacters,wordsorlinesinafiledependingupontheoption.

Options
wclfilenamewillprinttotalnumberoflinesinafile. wcwfilenamewillprinttotalnumberofwordsinafile. wccfilenamewillprinttotalnumberofcharactersinafile.

Filecommand.

Filecommanddisplaysaboutthecontentsofagivenfile,whetheritisatext(Ascii)orbinaryfile. Touseittype filefilename.ForexampleIhavecal.txtwhichhasasciicharactersaboutcalanderofcurrentmonth andIhaveresume1.docfilewhichisabinariyfileinmicrosoftword.Iwillget fileresume.doc


resume1.doc: data

filecal.txt
cal.txt: ascii text

Cpcommand.
cpcommandcopiesafile.IfIwanttocopyafilenamedoldfileinacurrentdirectorytoafile namednewfileinacurrentdirectory.

5UNIXCONCEPTS cpoldfilenewfile IfIwanttocopyoldfiletootherdirectoryforexample/tmpthen cpoldfile/tmp/newfile.Usefuloptionsavailablewithcparepandr.poptionspreservesthe modificationtimeandpermissions,rrecursivelycopyadirectoryanditsfiles,duplicatingthetree structure.

Rcpcommand.
rcpcommandwillcopyfilesbetweentwounixsystemsandworksjustlikecpcommand(pandi optionstoo). ForexampleyouareonaunixsystemthatiscalledCheetahandwanttocopyafilewhichisin currentdirectorytoasystemthatiscalledlionin/usr/john/directorythenyoucanusercp command rcpfilenamelion:/usr/john Youwillalsoneedpermissionsbetweenthetwomachines.Formoreinfortypemanrcpat commandline.

Lncommand.

Insteadofcopyingyoucanalsomakelinkstoexistingfilesusinglncommand. Ifyouwanttocreatealinktoafilecalledcoolfilein/usr/local/bindirectorythenyoucanenterthis command. lnmycoolfile/usr/local/bin/coolfile

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:

rmdircommandwillremovedirectoryordirectoriesifadirectoryisempty. rmrdirectory_namewillremoveallfilesevenifdirectoryisnotempty. rmdirsandeepishowyouuseittoremovesandeepdirectory. rmdirpwillremovedirectoriesandanyparentdirectoriesthatareempty. rmdirswillsuppressstandarderrormessagescausedbyp.

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

ifIruncmpcommandonsimilarfilesnothingisreturned. scommandcanbeusedtoreturnexitcodes.i.e.return0iffilesareidentical,1iffilesaredifferent, 2iffilesareinaccessible. Thisfollowingcommandprintsamessage'nochanges'iffilesaresame cmpsfileonefile1&&echo'nochanges'.


no changes

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

./cal.txt ./dohazaar.txt ./four.txt ./junk.txt ./test.txt

GrepCommand

grepcommandisthemostusefulsearchcommand.Youcanuseittofindprocessesrunningon system,tofindapatterninafile,etc.Itcanbeusedtosearchoneormorefilestomatchan expression. Itcanalsobeusedinconjunctionwithothercommandsasinthisfollowingexample,outputofps commandispassedtogrepcommand,hereitmeanssearchallprocessesinsystemandfindthe patternsleep. psef|grepsleepwilldisplayallthesleepprocessesrunninginthesystemasfollows.


ops dxi ops ops ops dxi ops dxi ops ops ssb pjk 12964 12974 12941 12847 12894 13067 13046 12956 12965 12989 13069 27049 25853 15640 25688 25812 25834 27253 25761 13078 25737 25778 26758 3353 0 0 0 0 0 2 0 0 0 0 2 0 16:12:24 16:12:25 16:12:21 16:11:59 16:12:12 16:12:48 16:12:44 16:12:23 16:12:24 16:12:28 16:12:49 15:20:23 ttyAE/AAES ttyAH/AAHP ttyAE/AAEt ttyAH/AAH6 ttyAE/AAEX ttyAE/ABEY ttyAE/AAE0 ttyAG/AAG+ ttyAE/AAEp ttyAH/AAHv ttyAH/AAHs ? 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 0:00 sleep 60 sleep 60 sleep 60 sleep 60 sleep 60 sleep 1 sleep 60 sleep 60 sleep 60 sleep 60 grep sleep sleep 3600

Options:
boptionwillprecedeeachlinewithitsblocknumber.

8UNIXCONCEPTS coptionwillonlyprintthecountofmatchedlines. iignoresuppercaseandlowercasedistinctions. llistsfilenamesbutnotmatchedlines. otherassociatedcommandswithgrepareegrepandfgrep.egreptypicallyrunsfaster.formore informationtypemanegrepormanfgrepinyoursystem.

Findcommand.
Findcommandisaextremelyusefulcommand.youcansearchforanyfileanywhereusingthis commandprovidedthatfileanddirectoryyouaresearchinghasreadwriteattributessettoyou ,your,grouporall.Finddescendsdirectorytreebeginningateachpathnameandfindsthefilesthat meetthespecifiedconditions.Herearesomeexamples.

Some Examples:

find$HOMEprintwilllistsallfilesinyourhomedirectory. find/worknamechapter1printwilllistallfilesnamedchapter1in/workdirectory. find/typedname'man*'printwilllistallmanpagedirectories. find/size0okrm{}\;willremoveallemptyfilesonsystem.

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.

cutcommandselectsalistofcolumnsorfieldsfromoneormorefiles. Optioncisforcolumnsandfforfields.Itisenteredas cutoptions[files] forexampleifafilenamedtestfilecontains


this is firstline this is secondline this is thirdline

Examples: cutc1,4testfilewillprintthistostandardoutput(screen)

9UNIXCONCEPTS
ts ts ts

Itisprintingcolumns1and4ofthisfilewhichcontainstands(partofthis).

Options:
clistcutthecolumnpositionsidentifiedinlist. flistwillcutthefieldsidentifiedinlist. scouldbeusedwithftosuppresslineswithoutdelimiters.

PasteCommand.

pastecommandmergethelinesofoneormorefilesintoverticalcolumnsseparatedbyatab. forexampleifafilenamedtestfilecontains
this is firstline

andafilenamedtestfile2contains
this is testfile2

thenrunningthiscommand pastetestfiletestfile2>outputfile willputthisintooutputfile


this is firstline this is testfile2

itcontainscontentsofbothfilesincolumns. who|pastewilllistusersintwocolumns.

Options:
d'char'separatecolumnswithcharinsteadofatab. smergesubsequentlinesfromonefile.

Sortcommand.
sortcommandsortthelinesofafileorfiles,inalphabeticalorder.forexampleifyouhaveafile namedtestfilewiththesecontents
zzz aaa 1234 yuer wer qww wwe

Thenrunning sorttestfile willgiveusoutputof


1234

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:

dft|awk'BEGIN{tot=0}$2=="total"{tot=tot+$1}END{print(tot*512)/1000000}'Will givetotalspaceinyoursysteminmegabytes. Heretheoutputofcommanddftisbeingpassedintoawkwhichiscountingthefield1after pattern"total"appears.Samewayifyouchange$1to$4itwillaccumulateanddisplaytheaddition offield4 whichisusedspace. formoreinformationaboutawkandnawkcommandinyoursystementermanawkormannawk.

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.

12UNIXCONCEPTS btomovebackwardstonextword. $tomovetotheendofline. Jjoinalinewiththeonebelowit. /stringtosearchstringinfile. ntosearchfornextoccurenceofstring.

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)

Destination telnoisthetelephonenumberofthemodemtoconnectto. systemiscallthesystemknowntouucp. aadrisanaddressspecifictoLAN.

Ftpcommand(protocol).
ftpcommandisusedtoexecuteftpprotocolusingwhichfilesaretransferredovertwosystems. Syntaxis ftpoptionshostname options denabledebugging. gdisablefilenameglobbing. iturnoffinteractiveprompts.

15UNIXCONCEPTS vverboseon.showallresponsesfromremoteserver. ftphostnamebydefaultwillconnectyoutothesystem,youmusthavealoginidtobeableto transferthefiles.Twotypesoffilescanbetransferred,ASCIIorBinary.binatftp>promptwillset thetransfertobinary.PracticeFTPbyftpingtonic.funet.filoggininasanomymouswithpassword beingyouremailaddress.

Logincommand.
logincommandinvokesaloginsessiontoaUnixsystem,whichthenauthenticatesthelogintoa system.Systempromptsyoutoenteruseridandpassword.

Rlogincommand.

rlogincommandisusedtologontoremoteUnixsystems,usermusthavepermissionsonboth systemsaswellassameuserid,oraniddefinedin.rhostsfile.Syntaxis rloginoptionshost options 8willallow8bitdatatopass,insteadof7bitdata. ecwillletyouuseescapecharacterc. luserwillletyoutologinasusertoremotehost,insteadofsameaslocalhost.

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.

18UNIXCONCEPTS TodisplayPackedfilesinafileusepcatcommand pcatfilename.z Tounpackapackedfileuseunpackcommandasunpackfilename.z.

Tarcommand.

tarcommandcreatesanarchiveoffilesintoasinglefile. Tarcopiesandrestorefilestoatapeoranystoragemedia.Synopsisoftaris tar[options][file]

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.

19UNIXCONCEPTS eodSeektoendofdata(DDSandQICdrivesonly). smkWritecountsetmarks(DDSdrivesonly). fssForwardspacecountsetmarks(DDSdrivesonly). bssBackwardspacecountsetmarks(DDSdrivesonly). Examples mtt/dev/rmt/0mnbrewwillrewindthetapeinthisdevice. mtt/dev/rmt/0mnbofflwillejectthetapeinthisdevice.

Atcommand.
atcommandalongwithcrontabcommandisusedtoschedulejobs. atoptionstime[ddate][+increment]issyntaxofatcommand. forexampleifIhaveascriptnamedusersloggedinwhichcontains.
#!/bin/ksh who | wc -l echo "are total number of people logged in at this time."

andIwanttorunthisscriptat8:00AM.SoIwillfirsttypeat8:00%lt;enter> usersloggedin%lt;enter> Iwillgetfollowingoutputat8:00AM


30 are total number of people logged in at this time.

Options: ffilewillexecutecommandsinafile. mwillsendmailtouserafterjobiscompleted. lwillreportalljobsthatarescheduledandtheirjobnumbers. rjobnumberwillremovespecifiedjobsthatwerepreviouslyscheduled.

Chmodcommand.
chmodcommandisusedtochangepermissionsonafile. forexampleifIhaveatextfilewithcalenderinitcalledcal.txt. initiallywhenthisfilewillbecreatedthepermissionsforthisfiledependsuponumasksetinyour profilefiles.Asyoucanseethisfilehas666orrwrwrwattributes. lslacal.txt
-rw-rw-rw1 ssb dxidev 135 Dec 3 16:14 cal.txt

InthislineaboveIhaverwrwrwmeaningrespectivelythatownercanreadandwritefile, memberoftheowner'sgroupcanreadandwritethisfileandanyoneelseconnectedtothis systemcanreadandwritethisfile.,nextssbisownerofthisfiledxidevisthegroupofthisfile, thereare135bytesinthisfile,thisfilewascreatedonDecember3attime16:14andattheend thereisnameofthisfile.Learntoreadthesepermissionsinbinary,likethisforexampleDecimal 644whichis110100100inbinarymeandrwrrorusercanread,writethisfile,groupcanread only,everyoneelsecanreadonly.Similarly,ifpermissionsare755or111101101thatmeansrwxr

20UNIXCONCEPTS xrxorusercanread,writeandexecute,groupcanreadandexecute,everyoneelsecanreadand execute.Alldirectorieshavedinfrontofpermissions.Soifyoudon'twantanyonetoseeyourfiles ortodoanythingwithitusechmodcommandandmakepermissionssothatonlyyoucanreadand writetothatfile,i.e. chmod600filename.

Chgrpcommand.

chgrpcommandisusedtochangethegroupofafileordirectory. Youmustownthefileorbeasuperuser. chgrp[options]newgroupfilesissyntaxofchgrp. NewgroupiseitheragroupIdoragroupnamelocatedin/etc/group. Options: hwillchangethegrouponsymboliclinks. Rrecursivelydescendthroughdirectorychanginggroupofallfilesandsubdirectories.

Chowncommand.

chowncommandtochangeownershipofafileordirectorytooneormoreusers. Syntaxis chownoptionsnewownerfiles Options hwillchangetheowneronsymboliclinks. Rwillrecursivelydescendthroughthedirectory,includingsubdirectoriesandsymbolic links.

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)

soforexampleyouwanttoscheduleajobwhichrunsfromscriptnamedbackup_jobsin /usr/local/bindirectoryonsunday(day0)at11.25(22:25)on15thofmonth.Theentryincrontab filewillbe.*representsallvalues.


25 22 15 * 0 /usr/local/bin/backup_jobs

The*heretellssystemtorunthiseachmonth. Syntaxis crontabfileSoacreateafilewiththescheduledjobsasaboveandthentype crontabfilename.Thiswillscheduledthejobs.

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

pscommandisprobablythemostusefulcommandforsystemsadministrators.Itreportsinformation onactiveprocesses. psoptions options. aListsallprocessesinsystemexceptprocessesnotattachedtoterminals. eListsallprocessesinsystem. fListsafulllisting. jprintprocessgroupIDandsessionID.

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

23UNIXCONCEPTS Whoasdefaultprintsloginnamesofuserscurrentlyloggedin. Options ausealloptions. bReportinformationaboutlastreboot. dreportexpiredprocesses. Hprintheadings. preportpreviouslyspawnedprocesses. ureportterminalusage.

Putadvancecommandsutilities,redirection,etchere. cal>cal.txtTocreateanewfilecalledcal.txtthathascalendarforcurrentmonth.>signredirects outputfromstdout(screen)toafile.

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 /home cd .. cd ~otheruser cd /dir1/subdirfoo

cd ../../dir3/dir2

lslistsyourfiles 2.lsllistsyourfilesin'longformat',whichcontainslotsofusefulinformation,e.g.theexact sizeofthefile,whoownsthefileandwhohastherighttolookatit,andwhenitwaslastmodified. 3.lsalistsallfiles,includingtheoneswhosefilenamesbegininadot,whichyoudonotalways wanttosee.

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]

25UNIXCONCEPTS Searchoneormorefilesforlinesthatmatcharegularexpressionpattern.Regularexpressionsare describedinChapter7.Exitstatusis0ifanylinesmatch,1ifnonematch,and2forerrors.Seealso egrepandfgrep.

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

if[$#ne2] then echo"Usage$0xy" echo"WherexandyaretwonosforwhichIwillprintsum" exit1 fi echo"Sumof$1and$2is`expr$1+$2`"

2.

WriteScripttofindoutbiggestnumberfromgiventhreenos.Nosaresuppliesascommandlineargument. Printerrorifsufficientargumentsarenotsupplied.

#!/bin/sh if[$#ne3] then echo"$0:number1number2number3arenotgiven">&2 exit1 fi n1=$1 n2=$2 n3=$3

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`"

5.Writescripttoprintgivennumberinreverseorder #!/bin/sh if[$#ne1] then echo"Usage:$0number" echo"Iwillfindreverseofgivennumber" echo"Foreg.$0123,Iwillprint321" exit1

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"

You might also like