You are on page 1of 221
Peete ackaetastomancu ae Unix Shell Programming Yashavant P, Kanetkar [bpb |BPB PUBLICATIONS ele! 5:4, commucir Pac, New OeLH= 1000 FRSTEDIION 1096 REPROTED 89 wCROUEDA Dore senor otra - faust as eee ie on er ora aroucrioe Ease FSM crac poner SaereenCearat | moTsen BEMBEETTNT ae STM aarg neni, Momouoreaaseias wees bcanesronnovainen Sepesttsunhe ot con tresoocceme soccer an imocnosoamerearom.eas OSUETIENERYCNE 2877 pine FURLICATIONS Dedicated al nase canara Fay ea = Semen, = Scene SS cee Som ema se enc) a ‘About the Author ‘Yashavan Prabbakr Kanetar bined Erm VITI Bombay dis M. Teh. ros IT Kanpur, Sine 1987 he has ben Director SCICTT a Tening nd Softwane Develop fim which he se up {Nagy Me Kanes shor of several book olding Let Us .Esplorin C: Working With CC Project, Undocumented DOS Through Writing TSRs Though and Understanding Pointers la Cpubiseaby rs Publications and Teck PubliaionsSingopore ‘These days bei wing afew more books on Cr and Windows itis teamatICF. Mr. Ranekarals tes repularenumn tied TheC Column and Objes Ces fra leading computer maga. Acknowledgments ‘Unie 1 was ods ifcult er,o0 found itt be so However, have resi that wring about ts more dificl. More so because itsneceny decide what lnlae and what to leave cut NirarjanBakre and SangetaKarandikrHlped me to make these ‘hoses In that enti book theirs ach sine thoagh F ‘ean the resposblity of any inadequacies or mistakes hat have Ima. have worker eniatetiemisakes YOu woul) beter wheter {worked ard enough. Sangeeta aso belped in boning the at fe chapters, whereas Niranjan exceed and in proved te sel ip ‘Thanks o Manish in f BP for asking might be ierested in vents ook sand you now boi it and I hope that may Telps make Unix as lesa fr yout tas ben forme Most ofthe figs in this book have Bees prepared by Shilpa ‘Apart. Her remarkable thoroaghness fs greatly Improved this tek. Hemant Kethar designed the book cover and I hope yu too would spree i ee for deta nd precien ‘TnkatoSeemsand Ady for puting up with ny bizarescheules sad isang to my rears. Contents Inaraaction PARTI Getting Started A Unix Biography "adware Requirement fr Unix Salon Fetes of Uns ‘Muliser Capability Mutiasking Capability Comminication Security Porability Unix System Organisation “Types Salle ‘ourne Shel Stet orn Shall ‘The Fist Faerng Steps Unix Commands ‘What'sinThe Name? Baers Gating Contdence ‘The Unix Fle System resting Files Indlging in File Pay ‘Ustng Fes and Dietries ‘Masking Fle Permissions Directory Permisions ‘tll Bete Directory Permissions Removing A File Forcibly ‘Other Use de Variations n " 2 15 16 0 “Te crontab command ersee Communication - Unie Style ‘The wall Command ‘What's Th News Today mois for Message of The Day Mall The asi of Unix Communication Sending mal apeingTneomiag Mall Catontng ral’ PARTIE ‘Set Programm Before We Sat When to Use Shel Seri ‘The Fit Shall Serpe Inveractive Sell Seip Stell Variables Sell Keywords “Another Way of Assigning Values o Vasables ‘Unin-defined or Systm Vaabes Userdsine Varables Tipsand Taps Unchanging Variables Wiping Out Variables Postiona parame Pasing Command Line Argument ‘Seting Values of PostnalPasmeters Displaying Date in Desired Format ‘Using Sif on Poston Parmeter Anthmeticin Shell Serpe, ad nd echo Revisited “he Caiae Renin The Fist Step a 208 210 22 212 nie ais as 27 219 Fat ms 26 Ey w " ‘The Tab and The Backspace Postoning Te Crsr| Beep, Beep. Bold and Beal “The put Comma Cont! nstracionsin Shell rere ‘Taking Decisions “The then i Staement “The then le Stent ‘The tet Cormand FileTess ‘Sting Tests Nested felis Foms off Une of Logis Opens icrchy of Logical Operates tse + fas lif ‘The Case Conirol Strate The Tips and Traps Bere ‘The Loop Contra Structure Loops ‘Thewhie Loop ‘Tips and Taps ried, Where are You ‘ThelFS Thing Reading From A Fle ‘The wl Loop The for Loop, ‘Ung for with Comma Lie Arguments ‘Creating Nested Dietories| (Generating Vales or afr Loop ‘Nesting af Loeps “The brea Statement ns 2s 29 us x0 233 2s 28 331 253, 236 a7 258 261 261 267 m 21 282 2s 2 oe 20 a 25 a 31 1B 1s ] = ‘Te comme Statement rercse ‘Shell Metacharace FRenameSabtiaton Metschasctrs UO Redirection Metacharaers Process Exeaton Metacharaters ‘Conditional Execton Using andi ‘Quoting Meacareters PoshlonalPararters a Special Parameters ‘Ont Forge Debugging a Seige S*AndSe ercive ‘Tricks af The Trade (Conoling Terminal Input Tackling Mutple Command Line Options sean Signals Factions Executing Malle Scripts Brerie Shell Miscellany Faction of & Shell, ‘Variables Revised ‘Exporting Variables CContoling Variable Assignments ‘The eval Command Exec System Administration ‘Adding nd Removing Uses Some More Daily Admiistaton ‘Stating Up Te Sytem Shating The System Down Disk Management 08 310 a9 m0 mi ma ms a a a3 330 a x ar me ma ass 350 x0 378 Ms 36 a6 ao a 385 356 ao Formatig A Disk ‘Making Ate Systm ‘Mounting A File Systm Unmountng 4 Sle System Using A Raw Disk Montariag System Usage Enauring Sytem Seewity Providing Arstance to Users Bicreue Stott Progeammning Project Pyoll Proceting System ats Organisation Mens Report Formats Cateltons Working of The System Progam ‘Where Do You Go fram Here. Improve This Progam Indes 02 aa 410 au 44 ‘20 a a a 2 0 31 432 436 8 a6 179 Introduction ‘Welcome o Unix Shel Programming! Ther arts of books bos ‘Unis bt mst of tem ssume tat you are computer wizard and ‘woulevetlearnevety single comand Unix as offer: Oa bose ‘Sores at eat you wold ind tis bookrefeshingly diferent 1 doesnt expect tht you have worked with Unix ear. Begins try desepin of wt you can realy do with Unix, how 1 gt Tred what commands you shoud realy xno, before brziuning vith th real stu he sel programing How This Book is Organized | This ook has two part. These pats stand on thr own depending ‘on whether yu are a povice Unix user or you have aed worked ‘hth Uni you ae already fant with Unix commangs you can ‘aighaway begin with Part I However, iss your ist st with Unix you would be Beer off Ifyou start with Pat I. Part ‘Comprises Chapters | hough wheres Ful consns of Chapes ‘trough 16. Contes ofeach parc are mentines bow i bit Part: ‘Caper 1 ios you o fandaental Unix cones, the major feats of Uni OS tndths equipment you ned trunk Chaer 2 _vexyou ep by-stepsigotons fr creating renaming ane Ing les and vectors, It also describes te le and etary ‘erissons andthe los behind fe Chaps 8 discuss he ‘Tn ile syste, is xganization andthe command elated to it CChaper 4 discuses commonly ured Uni commands with their Import vations. Cape $s devoted to oe ofthe ngrtant ‘caput of he Ualx shell -npaontpat edirection and piping. ‘Cpe i el contained goie to te ede which helps you ‘rene, mow sd nincain fet fe. Chapter 7 talks abou he © grocetes launched bythe stem and by th use ad there Fnvour, Chap 8 hlps you communicate with other wes through ‘he powerful communion fades offered Uni Part Assuming tht you ar thorough with he philosophy andthe com mand intodaced nthe earl pat, Parl proceeds ach you the nese of shell progranming. Chapter invoduces fundamen ‘al concepts of shel programming with discussion abut shell vai tes, pononal parame and wing interactive dr tive shel serps. Chap 10 covers the decision con instracton, ‘he fle and seng es and hel wily. Chapter 11 case the ‘aroes laoping ates valable with he hell nd che practic ‘he, Shell metacharacirs are VIPsOf Unita yoo eam bout hem ‘in dtl a Chapter 12, Every programmer keeps ew aces ip his sleeves Some ofthese ae shown ie Caper 13. Fates which oe fy fom mainswea sel proganuning bu re quite andy fn particular stations athe topo Caper 4. Tisbook would oe As charm it oct discuss system diiron ade rated serps, Hence asepuate chapter hs bee voto t= Chapter IS. To pt roger ll thesis acquired ei ino one big pact program nahing abort ofa ul hedged projet would. With hat Ineniona Paya rceingSyembarben develpedin Cer ‘is hs book les yx om th sip ue of sige Unk ‘commands trough complex commands to stl pt programs ‘net hel programing projet Throughout the book theresastrong emphasis on examples, that you an ses how various programming mechani work ad your and at nkerng wit hem. All tapers alo have on exercise ‘Mthoend so that you can tt your understanding of he concepts a youprogress Thismakes he eaming proces easier, Dont foget ah te exes. Afra aig sha ess 0 ef ‘wing thom If you we a reative novice, | hoe this Book woul! make & Unix programmer you. Andi youaeseady programmer, hope this book weld make yous good Unix pogrammer Goo ack ‘Yashavan Kant ee 1 Getting Started 2g 196 AUnix Biography Hardware Regiments for Unix Salient Features of Unix Malser Capability Multasking Cspaiiy ‘Commenicston Security Porabity Unix Sytem Organisation "Types of Shells "Bourne Stell Snel Kom Shel “The Fr Fltering Steps Unix Coyamands ‘What's in The Name? Exercise 7 Ta (Wane Peg 1 are now embarking on very spell Journey that of ‘unveiling anexplringte ualinied expanse uti Uni By the end of tis ourey, we plat have you risks ‘eoiaive, if ot confident vertores othe Unix Operating stm. Battie os doavay with fe eves, What wa the org Unix? How dit reach the stats it enjoys todsy? Rea on A Unix Biography Unix, the world knows it oda, ig the happy cutcome ofthe proverbial rageto-ices story. What i no headed the mas powerful and poplar muliser Operating System (0S) bd avery hnumble beginning in the astere premises of AT & T's Bell Inbortces, de fee spewing ound of many Tanda In compute iso ‘The orgn of Unix can be trace back wo 1965, when jot vente ‘wasundertkenby Hell Telephone Labocatovies. the General Blectc Company and Massachsets Inst of Technology. The si Was te develop am operating syst tht could serve a ge community tf ers and alow them to share dats feed he This neverso-be eure wa aed Multis for Malis Infcaton and Co ping Service. Even aermach tims resources nd efor ad boen Sevtedo he poet te sonvenieny erative computing service 1s quoted by Ritchie fled to materialise. Thin ed Dens Ritchie tnd Ken Thompson, bath of AT&T to stash on what tel mind's ee had so ilusiusl envisioned. Thus 196, th wo ong wha few odors evolved what was to be the fist version of c ing 3) he muluser sym Uni. Armed with maseum pee ofa com per called PDP. a rudimentary file ryssem was develope, Toush his was not ppd te Flesh al he rapping: of ly poten nlasr operating system. This emer cited "Unis" by Bran Kernighan, at 2 very reminder of the ilfated Mules. Later in 971 Unis was pated oa PDP-1 computer wit 2512 KB ask, Uni thon was a 16 KB set ith 8 KB for ose [rorams and a ype init of 4 KB per Me Al Ws assembly cose Feingmachine dependent theversonwaenntporabe ake ree ment ora suse OS “To rma this, Ken Thompson created anew language Band et tout he Herculean tak of writing the whole Unis code this ugh evel language “Bloke in sveral spect nessa forest Me programing. Richieste he nadegnces of Band msi {cto anew Language which be named ay "C= the langage wich finaly enabled Uni to stnd al onary machine, ‘Thus, by 1973, Una had come long way fom ts PDP-7 dys, nd sas soon ceed gute ruber of Unvestes, Companies nd tier compe isto. Wid ts uncomplissedeegance ‘ea charming following perhaps move effonesly than the ped Pipe of the tbls. The estentalyuecommating nate of the Fir encouraged many a developer to polish ant enhance > pads, wtih ep liveand wit the times, By the mid egos here were more than shundedthousind Uni insalatonsronaing on ating from + mio to'® mainframe compar and over numerous varying architects «remarkable ‘chleveent for at OS by any standard. Aosta decade ae Unik Sil ols the record for being the soul of me compute networks "han any her OS ae tase Param }), “srdware Requirements for Unix ‘om ihe Lipa System onthe PDP-11, Unis has emerged tobe ‘Tugsd stalwart today There ae some peseulsts fra system thaeanbot and ke est avantage of These ar an 8 MB hard tiskand east MB oF RAM Random Acces Memory) ona 16 Inicoprocesor (60386, peferbly SOSESD8H6). So you need 2 PINT er higher with the afrementoned cof gration to employ ‘Unit othe best of ably. Ad how do we conect he terminals lovke hom machine? Tough a6 port conor cd installed ‘nite expansion lt onthe mathe oar ofthe host machine. One hd ofthe cable i lagged to the porto the conor ca and ‘Goer crt th sei por (9 pin or 25 pia ofthe terial. Any 1508 bsed machine wih sel por can act sa terminal ‘to 0 NB dik space lost 0 MBs exten away by the ate {Unit 08 filer wheres apotber 10-20 MBs used swap space. The ‘ep spue wed whon Unit fal short of mermery. At sue mes ‘tenga stores in thisswapspace he contents memory which tue nt inmealy rege. Whenever thse contents are rogue they arerend hack om the Sap EE. Mr the mame of ina more shoul be te memory om the Rostimacine, Ava thmb le We ean say that per terminal tbe Sppred 075 | MB shou be present inthe host machine ‘esies the hare, Uni lo requires a coniderible amount of man support This comes inthe form of «Stem Administ In supers the working f Unix on any instalation Sutient Features of Unix | ‘he Unis 0 offers ever alent etre, th important of which 9 tsa belo — aig r= Multiuser Capability Among its salient features, what comes fist i its multvser ‘eb In smulaser system, he sare computer scutes ard tisk memory et -are socesbeto many wer OF course he wes thon Tock togeter the same compe, but riven difret terminal o operate from. A termina in ara keyboard a3 mono, which ae the input and output devices ft se All {erninls re comected fate main cmpater whose reoares at alledby ll ers So, auseratanyofteerminalsean se noonly the conpter, bot als ny peripherals that may be tached sy fo Fnstane apie One ean easly appreciate how economical ich 2 ‘Setup ethan having as many computers shee are usta ao how much more convenient when the same data so be shred by AIL The following figee shows sya Us sep. oO | — ‘Terminal C) el ae il Terminal Ravel thee f Unie tallaion she host machine, often known i a tever.or a console. The numberof feminale That cn te a connect tothe ost machine depends on the numberof ports ha ‘represent initeconrllr cand Forexapl, apt cone cad {ne host achine can support 4 trminus. Tete ate sever yes ‘tial hatch easter tothe st. These ae (@) Dumb Terminals: Tes terminal consist of akeyboard anda ‘pie ntithpomemeyordikofhcown Thesreannever atasindependet machines I hey are ob sed sey have tebe concede host machine (©) Terminal Emaltion: A PC has its own micropraceso, rmenary ae disk dives, By ataching this FC the Bos "hough sable and rain sofware rom this PC we can multe tt work adam erin. AI sch i, however, the meay and th dik are not nae nd the PC aot cary out any processing on HS own Like 2 dumb terminal tans is processing jobs wo the host machine ‘Thesotware that makes the PC work ikea mb emi is called Terminal Enolton Software, VTERM a XTALK. neo sock popularly ase softwares (©) Dian Terminale: These teins we telophone tines to connect withthe Rost machine. To comics over ‘clephone lines itis acer atch ni ealed maser 0 the terminal aswel sto he hos Figure 12 show typist Tajo of sch n communion withthe ont machine The modems egied to tansmit dats oer elepone lines Multitasking Capability Aer highligh of Uni is att i Malang, implying tat ‘scapbletcarryingoutmore thn ejabalthe amen allows youtotypeinaprogiminssedtor wile slultaneoulyexectet fom ote cemand you mgt have given cain, sy Yo ort and apy 3 ge le Te ate Jo performed in th background hein tb Yorepround you usetieedionortakea dete isting Tang aeD, or whatever else. Tiss managed by diving the CPU tne ine roy bevecn al procescs being cared oat. Depending onthe ofthe tsk, the operating system propriate alls all Aine sls (othe oder of miluceonds or microneconds) to ech forego snd backround as, e) =< |__| Host Machine | ie , Figue 2 ‘The very concep ofa muloser operating system execs he same tobe mitasiing to, We an sy ths beans even when aes xeating only onc command ata tine, the CPU isnot Sedat to Uhesolary user nal pobubiy, re are ten more eer wo alo tlesiand execution oftheir cormunds. Uni, therefore, has 10 Be on Uistoe lee ime, obliging all the ere come 1 Altnough crude, MS-DOS also provides a muliaskingcapbiliy The ype of muliasking povided by M-DOS is kaown av Sei Maluisking Inti type of multasking one progam i stopped tempor wile anothers lowed to execute. Atay given me only one ask sr. Youcanikenthistoasiuation awh human Working on acompuler stops his wor toanswer ringing phot ahd the, having finshed wth the ell switches ack to te comput, Se a

You might also like