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 Most of ws must have used Sidekick some other memory sient propsam, Once welosdthisintomemeryasimplekestokecantake {fom Silkk tanothrpeogram may beruningor vice-versa I forexample, welnvoke Siskick inthe mid ofsomecskuation ‘ing don, thnall wrk onthe cleulatons would be soppedas the “nny espns to Ski, Once you we dough wit ikl Sout hey to go out of Sidekick the calculations woul then te rosed. Would te far beter toe Sidekick enya pst of the compas tine? So that even whe we were in Sidekek the ‘clans would cary on being performed athe background thisisexaety what Unix des, Ung the met interop tschedales the CPU tine between programs. Tee time periods are known at Aoeaies, If there were 10 progr runing tone time he Inisoprocestor would Kep stching betweon these 10 programs ‘Ata given point time ony oe program wil be handed by the {CPU Bor because the etch happens vey fast we get the feling tha he mcrproessor is warking onal he programs simultaneous ¥ “Ths, mulaskng of Unis elifferen rom DOS which does mot ‘Eve mesos to running programe. And If thre ae 3 programs ‘nit nDOS andeven one goes haywire he entrerachine aN. In any genuine mulasking environment like Uni this does not pee. ‘oes iveeqal times alprograms runing in memory? No. There may be sone poms that re eltively mote impr. Fr example, howe hat wat for user responses af given a Higher rity. Program which hve the sme poly ar schedbled ona ound robin ass, Communication Unix hat exelent provision fr conumuniaing with fellow users “The vormmunsestion ray be within the network f single main i Tg Se, compute, oF tween two or more such computer networks. The her con easly exenange tal data, programs through soc ne Ss Distance poses no bua opssng information or messages ound fie. You may be two feet avay rato thousand miles your Anal ws arly ake anytime to each ts estiation, Security Unie allows sharing of dat but ot incriminate. Haditbeen Ht would be te delight of mischifvonges and useless fo any ‘trthtileenerpie aisha theinkerent provisions for peee- Ing dna, The fist promded by asiaing passwords and login nes to individual wars ensrng Tat ot ay body can come and fave acest your Work Ae ile eel, tht a ead, wee adeneut permissions each fle ich decide who can acess article who can ost) it {nd whocan execute You may owe read and wee permissions for youre andleave her onthe network ee toexecie it orany ‘ehoombinstion, Las theres ile encryption, This ity encodes your ile ito an ‘nreadaeforma, so steven f someone soceeds in opening i, oor scres re se, Of course shoul yom want sete cones, Sow ona ey the Be ° Portability ‘One othe min exon fo the iver pops of Unix is hat ‘team te ported to ulmos any computer ter, with only the Bare ‘nim of fuptions to ei the pven computes ae ECE. AS ti tady, there te omamerale computer anafctrers rod The le and ens of hundreds of tara conlgtations. More often Thun noe, Uni sunning song on each one of them. An est we Forge de ert for hs eat mst be given to the Dennis RN's prodigy, C hich granted Uni this ara transport fae almest entiely writen nC Unix System Organisation “The fanetoning of Uni ismanned in the ves On the outer rst ‘ese te plain ores ad er ules, wich pes ow language. Athehear.o Unis othe herhand the Kernel, whic ‘ner withthe atl rare in machine lngutge The stem Tinng ofthese two modes of communiation ede by the mide Jaye called he Shell Figur Sao the freclayers of Uns OS. Tels Appts Bgueis ‘Tho shll che command interpreters itis alle the medi, ‘whic incr th eorsmangs ae give and then conveys them ‘othe keel whichulumacy executes them, Youeanimagine kes! tetmonuch who en overall contol of everthing, wheres the Shella cmisay “The keine has various fonctions. Itmanages es, cas etal he ata ansfer betwen the ie system apd the hardware, and also Imanages memory. The onus of seheduling of varus pogars running inmemor oralloation of CPU imetoall ung progr eg Sed) soe with te kere. alo handles any inte sed, ats theca as Get dealings with he hardware, “The kernel program ic wually stored in file cle “on? whereas the shel program sina cllds reach ser working with Unie at any time diferent sell propane sre anning. Ts a3 portal poitincinethcremayleseveralshelsruminginmeinory itony one kere. This bees, at ary instance Uns opobe ti exeoving nly one program the other programs wit or their turn. Andsineisthe Kersl which okects the program one kerrel eicen However, cifren sessile eminals af ying tososk Keel sateton Andslace heuer tract withthe kerel Thr he abl differen shells are necessary ‘Types of Shells Difleren people plemented th interpreter anton ofthe shelin ‘ilrent ways. Ths gave rise to vais types of shells, the most Frominent of which ae ound below: Bourne Shell Among ll, Steve Boure'sereton known after mn ashe Borne Shel ete most popular, Probably thts why iis bundle i ‘very Unix yarn O pefaps it the aher ay round, Because it ters bundled with every syst it became popula. Whatever the ose the fc te fat resins that hi the sell wed ‘many Unis ser, This wil oso the sal we sale talking about ‘extensively trough he coarse of his book Shell “This sh is it with thse whoa seriously ito Unix program ‘ming. twas ret by Boy then posting his graduation tthe University of California at Berkey I has two advantages over the Bovine Sh, eS Fil, allows alisngofcomsrans. Tht, youcan decide what ‘um you want ocala command by. This roe very tefl wes Teng commands which ae used ne and again af enum by you Instead of typing the ene command you can simply one the Sor alas tthe commandline. Ir you want wo save even more on he ping Wok, C sel has 3 mand history feature. Tris the second ene that comes with Shel Previously ypedcarsmands can bere, ioe the shell -eepsirck fall command std th comune Ths ete Isso the one ride by the program DOSKEY in MS-DOS. Korn Shell 1 there was any doubt out the cause effet retioship ofthe popula of Bourne Shell andi’ inchson im every packages {0s fe toi The no so-viely-osed Kern Shells very power dis asuperset of Bourne Shel fle ot mor capitis isdecidealy more efficient than heather It was designed to Be 2 by David Keen of AT & T's Bel Lat, The First Faltering Steps Wiehiwedone enogh homework on Uni noo vente for oust Practical comaet with Given ht your terminal Is cere 1 the ostcomputer ands powereden sour pty prompts you for Jour login ame Esch ser is given unig login rae sada psd whch ar ke an ny pass to cones othe host machine os ase, ‘yeu havent ben given a login ame and pasword, you won't beable to gain aceesste Uni Mr you eter your login ame ou ane prompted to ent the pasar which hen heed in docs oat ‘snpear on the ispay. Obviously hes 0 cna that mo chance ot maybe premediated psserty ible o sec ne = fen you ry to access your system, Uni wil playa prompt that toc someting ike ns: legat Paseo hana Bet ring nn romp, yo enter our lon a (in fa above crap) eich youre the Pnver ro Bins rage eu mo ope frye provers een ots Gant) The vor of cee woul te spar on te tee {hc por you we sould bhp pre sth hod ae ty Unto preventnaathoed nay note ser Tesoro Shoal be changed equey. On many sytem fer spied oso of ine sour pasword expe (ge) an ie Pex ne You oer tn esos erp nin can cans yourpssord when! you Icon mo yes ising scommand oath pasword We wold css oto chang Sou pssvrd instr cher, Sometimes you may notype the login ame or password propery: ‘When you do this the sfstem will respond with the flowing mesg toate ast : Psat Nona Legh ess atom: ai Note thatthe stem des not! you wichonesincoet helen he ore prsword Again. ths saseculy mesure Even 304 1 3 gn mane gop, 04 wl let te pwd Fortin Settee Many stresses {hesysem administra eling Him ore a sve ussess tempts mere nade on yor og mae. Tarra ema 4 ‘Once the cme login name and pasword have been supplied, you Findsore welcome messages from he supplis of te Unix version fnsallodon tho host machine ellowed by 3 command pomp. The ‘Sand prompts (liu ae operating in Boor shel, ‘ra fin Gabe, What powers avait you here willbe unwound a5 se progress. For a ket frm me tha they do ‘You ae prompted forthe login andthe password every tine you put Snyour ermal purpose sto ey fewer and allo acess toihe sytem only ar vefying the deny of te user. You wll hot be Prompied forthe login if hee i ome problem in cables thraogwhich you termi is connected othe hot machine ‘Once at the $ prompt you can sue commands, Tere ae several hundred command aval n Uni, Lat begin withthe most slmenay oe Sntosni fat 30. Junto obs ‘A word of aston before we proceed. All Un comumanis reo be typed in small ave Teter. Onee you enter de above command and press the Ener hey the ill interprets your earumand and then spaches a menage fo keel lo ideity the usr. The keel ranevesth information sboutyouandasplasitonthe see. Tis Infomation coast of “aa” wich is ou login name, "y8a" sign te wenn] number othe stil port lin by which your terminaliconsced tothe ostmachine, Te date anime hich youlogged inareaso splayed. Infache who am commands apes ease ofthe who command ‘The who commands more power pd plays data abut ll he users who have logged inthe sytem cures. This i sown Cae) sto saat a Wun t0 amis a2 ye Jo 0925, Sey os D0 0622 iba 1 in 1 07:10, “Th fom f th ouput i sare that of who am Theft ni inagin hewerslogin ame alowed hetcrinalinee swing fondue and ines. “The cad of «Unix session i marked by a lout. This is dove by fihertypngesitathe§ pom or iting Cet Terminating you? Sesion his way indents that you have logged out of the system. Simply turing the power a your emia off doesnot resin ab Actual exit Anyone sutching onthe terial would then automat ely fndhinseiogedn bypassing teloginprocedre Needless hat wou mean goodbye to your Messy. Unix Commands Having covered ths mach ground lt now ett the tik of he things Mos of us woud be etering the Unit arena after ravering Tha of DOS. Sous so ato el at home, we il fist have ook ‘Msomecommandsis Unix hata parllothsesvalibein DOS.” That's the pin fom where we would bein the neat chapter. But before yout vertothe next chape were you ate oing to meet aplethrs of commands emer few things tht apply al Unik eran. (3) AIL Unix commands mas lvays be etre in small ease teers (6) Been the command mane aa he opions fat may be eran Wi i ced tease iis ova porcor tah For example, lv Here the command wheres is the oplon und the wo have Been separated bya space, The (=D a Prgrwing 7 options usally presided by a minus) sign. The options {alloc wih command are often own as switches. (6) Twoormaneopins aval with corsmandean sally be combined For example, the coma el -as same sl, (® Tryoumake a yping mistake, pot Bakapac to erate char sete, Don't fo back wing aro Res an hen ater. ‘eleing sing the Deh. (©) To cane the ene command before you pes Ener, ress heel ey. (9 Dont tum off he computer if you have made a misake and fis not ping well DOS wes re ed 0st taming the Compute i oma have strangely possibly lig in sn nin oop sme suc thing, Unix des respons trell tsa an apeoah Inset we need to sggest pit) {oUnintostpetecton of command whichis ereing 2 problem, One way doo by iting the De ey tl the nmnd fot sbendoned ty Cut d and you would be Fetumed te login pom. Aad iis ely bad dy for Sou even Ctl d may nthe abl tod the job. Ash ines Sou gto contac th system adminstatr who woud then Eto prces tom momay. How exacy he achive his tre would explore inane chapter. What's in The Name? A loti the rams happens to be the name of Unix command Un Commands hve sang names: UnikeDOS environment where You fave jay tunes for ech wlity there appears to be a lak of iapimation fre naming of i ules under Unias sensed, Under DOS youve Ceonpltsboarngrames like TurboC, Quick CzanechGrLatseC, Vitamin Cet whereas under Uni the © Sener simply mane astra DOS developer weiss ai -crching expression na leh kel tells “search or Tr” o pest or some such name. sna uiiy under Un x iecame erp’ standing tor global searcharegularenpreson PRlpnie! When’ Unideveloper developed auttywhicheous Shite le d's for toweeas 1 uperess) Wile copying fhedsidedronaettasee However ecwasaleadyteesancing fore Compiler Hence hs cose te next est option =a. What 8 {cof imsgiion! Wha we must underage same Uk Aomands have sich seatge names This because when Keo ‘Thompoon gave Unik sa case study to is stent, the stale poops stare bilding ties sound Ui Nebo eutsid hese (foopstelicved thal Unis would ever become popular ad success Tithe names vento ules weretserveasremindero penne who were developing ousng it You wold agree tha he names Aroid ave been diferent and beter had people gone aboot te evelopment of Unix more systematically. Exercise TAL Rekpte caress reco te lowing ge (9) Unix 0S was fin developed by (0) Deas Richie (2) Blame Stoatop 18) Ken Thompson (0) Bran Kerghan (0) Unix 08 wa ist developed at (0) Miro Comp, USA @) ATAT Bell Labs, USA @) IBN, USA {@) Brand neni. USA (©) UnixScanotrunon whichof he fllowing Misrprocesor (1 3086 a @ © 2) son86 (6) 0386, @ Peas ‘Uni is writen in () Clanguage (2) Ada language (G) Petanguage (@) Pec language Ina typical Unix stp the ost machine is tached 1 the \erminas troaph () Vocus (2) Sound baster ca (8) Diskeontoller card (apr cooler card Unis (A) Single wer, single asking OS (2) Single wer mutasking OS (G) Malser nuliasking OS (4) None othe above evry wer working on Unix setupisto us the pine, ten ‘he primer shoud be atached © () Thebostmachine © Ay of te terminal (G) The terminal rom where the fit login was made None of the stone For abi emia facity which ofthe following is aust () Mulimeda it (©) Modem (G) Finer (@) Terminal ewolaor ‘81 © © © @ © © © ” @ o o tcl Which of the following is «popular terminal emulation software (yvrerm @) vr (@) comtr (Pe Which fhe olin is command fr searching pater ina le (find ©) ep (6) lockup () None ofthe above ‘State mee the fllowing statements ae Tre or Fle: ‘Unix uses serial moliasking to suppor varios programs runing memery. ‘Uni soppors malitshng by svg tine slice 0 varius ropa unas i marry. In Unis we can communicate only between users comeiede ‘ne hosts ot withers connected sroer hos. very legal user ae to have login nd pase ‘Any tet having accesso Unix sstoraically gos av acess, {oallthe ies preset init Unixcan be pote new haw platform with ngs in the Unix coe ‘he Unix kernel 2 as an pent between the shel de are InatypicalUnixenvirnmenttore ate seve kere anone sal Bourne sel offer command sory etre who ia spec ease of who ami command. [Rcommandswichforany Unix command always begins with ait Aner flowing @ ® ° @ —_— ‘Whatdo you mean by password ageing? What you men by maliwser, mutating OS? What are the mina azdwarereguiements for instaling Unie? ‘Cin Unix be inal ona PCAXT wth mb hard ik sd Tem RAN? If aot why nt? Name any salient Features of Unix OS. ‘Wiiclare he ferent ways essing alga conn tin with th host machine? ‘Whats the asi iferenoebetweeo DOS, Windows 95 and Unix? Which tren ype of sels ae avaiable in Unix? ‘Wht are the long fons ofthe following Unix commands? fo gop une ‘Which diferent scary mechanisms arc avaiabein Uni? Gaining Con- fidence ‘The Unix File System Creating Files Indolging in Fite Pay Listing Files and Disectories ‘Masking le Persons Directory Persson Sill eter DirestoryPemisions Removing A File Frit Othe Usa fr Varin Directory Relsted Commands ‘nti mal at ABIL of Mathematics Miscellaneous Commands : Exercise —— (eel rogomg >) athelastchapter we swhow toexeeutthe whoconsmand which tives formation aboot he user who has ivoked this command fe ogg In. Remember that in mule ye ie Uns ‘ooing who you sre and where do you ands crucial. That why weed the who am fcommand it Wealso know tht whi ale ses that might have logged in Let ow find ut how ae ourlated it teseuser, Wehnow thatthe Systm Admin stator ‘sinovealcontolof the Una irsllaon.Infasthe the one who aso crate your acount with Uni oth you ca login, For thaimater unless he rates an secon ora parca user te wer is able wo login since Unie wont recognise wich a ae, Creation ‘fam acount involves the allowing soi a) Providing login mame tote usr (&) Providing inital pasword othe wer (©) Pain tb user in one ofthe groupe (@) Providing deta working sel othe wer (©) Providing a deta working scr tthe wer ‘A cpa Unison might hve 25 to 0 wes. this int ‘ations ina University then the users maybe categorised as second ea ster, third year students and s0 on. Acorn, while Stetng sch user the sysiem administer woud put all third ar Stent none group. second year student i abother group ce Sint, nan nds sep all user from Accounts purine ‘ny be kept in one group ll ser from Purchase departet ‘other grup and son By diving all sent grovps becomes easier forthe sytem dinar manage thane Ate same ie {kis more convenient for the users themes to sae thelr work, thse les and tet data. The way the system adinistaor gives, Gierenttogin names diferent ers he aso provides names tothe Ups to which the users belong. The following figure shows he rgnistion of the users and groups which woul give you an en Shout where do youstand mong the wer community. ‘Sm Alpiaaeior T Group! Geogp2——_Growp3 ro er) User? Used Waerd Users Urs Use Used Figue2t ‘The Unix File System : Before we ler any mire Unit commands it i xen ounde stad the Unix Fle ystem since Unix wets everthing iho and Understand, safle Al uti, pletion dats in Unix sored 1 files Even a deioy is teted a le which contains sever ber files. ‘The Unix filesystem resembles an upside dawa te. ‘Thus. the ie syste bepine with rectory called roo, The rat rectory i depaed 5 sash (). Branching om the tot there ae several edhe etre alo bin Ii, wa, ee, tmp an dev. The toot decor also contin fle clled unix which i Uni ketel lyf. These directories ae called sub-directories, tate Being the root dectary. Each hese soberectores contain sever let ‘nd directories called sub sb -ectres. igure 2.2showsthe base struct ofthe Unit ile sytem, ye (eae a Tsay awe =o ert er? seed ie Fig ‘Themain reason behind creation frets sto keep related files lopethr and separate them frm othe group of related files. For ximple, iti a good idea to keep all ser elat isin he use lst al deve rete ies the dev dro, ll emprary ‘es othe tmp decoy ands on. Let a lak tthe prpose ofeach of hese diester, ‘The bin dctory contains executable files for mato the Unix ‘ommanis. Unix commands can be ether © romans or sel ‘gras. Stell programs arenahingbutacoleconof several nix Sennen ‘The ib ieetry contains al he bray Functions provided by Unix forpogranmers The programs witenunder Unis melcuscot hee irr uncon nth it etry. ‘The dev diestory coma fies tha conv vais inpovouput eves ike terminals primer kien ee For each device tere ‘sa separate fi. In Unie each device implemented sy le. For example, everything tat isplayedon your trial iss ten toa fle sociated with your emia, and ths spree nthe dev dren. Canin Conte =25) a mr director thear sever dirctors ach sociated with Pei eens dvs ae ceed by the nc a Aun wher berets scout orien en Each seis lowed work withns decoy oe called hore dirty) and Ir trzanse his det by creating ater sub-dectones nto outs evo rel Fie. “nin thus rectory ter sanoterbincstory Which contains nina! Unix command ls, fies cety Uninorby “os imp decry contin temporary ut Sic he os peut seated fora temporary nn ea aferd 0 saperse wth them. Thee es pet {erGmaaly lac when the tein aldo and ested [ie aforementiona dreores ae present on almost all Unix fms. The floring gure captures the essence of these etre od ein pepo aoe Rawas Following are the allent Features ofthe Unie Fle System (Teal Pron (@)_thasaherchica fle ste. (8) Flescan grow émamicaly. (@)__lechave aces permissions. (o) Aleve re implemented sis “These fests would be cscussedin etl in the flowing paige. Creating Files Now tat we understand bow teil sytem s organise in Uni et ‘slr eclementary erated commande We wold is learn ow tocrete files Thre aretwocormndr to" fowch end ct And hiss how they are ob se, touch singe ‘Thiscrestesaflecaled "sample However theszeafe le would ‘zoo bytes singe touch deen low you to stor anything in 9 fle Then does touchserve any purpose? Yes, when we ant toca several empty les quel. Tis canbe done by sung, ‘Slouch snot sarod eal eps sis ‘You would gre that this refeshingly simple way of creating ery fle. But wht i we want ose fees a fe? st ‘ype the command, Seat» tt ‘Now pes the Enter key and you would find the cursor posioned in ‘bene ne, waiting for youtotype the mater hat you want sore ithe ees Type in wo lines ex" \Wlosaa, arava pas tte apts ‘Asia Asprlaceat heal bw ne —— ing Conte) ‘once yous tough wth hi pos the Keys Ctl In Unix the fps Cirdindcatethe EOF oendoflecharace. Therefore when te pes thee key the eat command recognises the EOF ehaacer {rc romply saves the mater you typed one skin the le tes Naturally. you weuldonceagun get tack th prompt onthe screen “ro siply the contents of «file under DOS, we wee the type own, In Un scooter seat, eve from neat, Sing eat resie atthe command prompt displays te contents of Filcreipe onthe sen, Thus, tose the cones ofthe Mle test hat trecrestodabove we shoulda. Seat tot Now we know two ses ofthe eat commaad. One io cea new files and aotherta display the content om exng ie eat as 3 fem more ass up seve can constr te coats of 0 fils and tre hem nthe hr le Seat sample sang > rowsancle ‘This would rete newsample which contains contents of sample followed by tat of sample. A woad of cain. IF newsample trendy contain someting it would be overiten If yom wat hat ‘shoud resin inc and content of samplel and samplez shuld etappendos tition you sould sete ‘append ouput redirection pert >>, as sbowa below: Scot earl samp >> nonsanple Indulging in File Play Now tht we know hs crea les nd splay ther ets inde ‘urselesinmore ile atdcommands Like ose forcopying files, enamine, deleting te isting them ec Here we Bo. Im DOS, wecapy fil, len Unix we epi For example, Sep lates etd This wil copy the conten of eter nto ile letter letier zea not ex twill rested However, ii doesent, Uni taken trenbeny to avenue st without wary You Look at the following ep command: Sep lees ird tors 1 sch eof pl les metoned ae cop to he indicated incor. Poviedthatthe etry letterscxiss both lester and eters would be copied 1 4st in DOS, sn Unix 00 you can copy Mls from rw itferat ‘dectreshy specifying ei namealong withthepath. Foexample Sep heraascopart Arn orantokeapt ere the ile chapter is copied trom the directory staal othe irc fasraal newbook When copie hidestary ld he the ne ep insted of ep, ‘Whileonenames, weighs wepointouthat ante DOS, Uni Mes donot have to follow astringent Schuster extension ie ‘Whatmore be dot nthe lemme iste a ny other charter constituting helenae, hsving no significance whatocter 8 Sepirater a ilenume and etemn Also ot that inte above exams we ave usedabsoluepatnmne torefertothellechaptrl Theabolte parame ied sche ro Sometines imal of abslve pam we may se else name This eles the pate tating rm the disso | — ene hich you are now. When you types fl pathname starting a tbe Footdietry.the athe sari ith Wen you type lative pane sang wth cunt working decor, the pathname fest start with Ta’ how Unix (and you ean igure ot which Kindo ph tis ‘Te counterpart ofthe del command in DOS i the m command ia ‘nie. removes the piven Mle o ies sped toi work iletenly Tor teen otons spied with. Thi leas to 2 Aligh digresion wherein we ned the mos pops ety in Unie “opins or switches. Unt commands have am ebondanc tons {omanipulite ter exccuone. For iance, saying Sm 4 te ‘wheres wich removes le neracivey ie you ae sk for ‘nimaton Weer deena the le, 4 DOS, to remove diet, you ae fst regu wo empy the Ancor and thea delete. Uni offer a singe conn fo the Sm en “This carmmand recursively (4 removes all coments of el and ase Atif. That pves ws wale ofthe power of Unis, daca? rm used withthe opin remove ils forcibly, iespeeve of heer you have write permision 10 them ono. This would Be tor lear inthe next seston were me del wi ile persons Forthecime being stemerber hat sochanopeoncxise wah Un Renaming o ies i DOS is interpreted in Uni ving tm, However, my is more capable than ren of DOS a we would se Suppose we want rename tele test sample we shold sy, Sr a sano (tama = ang Clee) The my command als has he power‘o roan drecteles Sv cle nar ‘olde wil be renamed to newdr, proved newdi is not akendy exis. ‘Bt why cll te operation moving” of es rather han renaming” to les, Becabse moving le ples removing it from ie cuent lection and copying it ata new locaton, However, moving ts ie than copying inthe source letras ron iil Tocaton and copied atthe specified destination. The see of mv ‘enmand is exemplified by the following command Sr fete nee ‘On exeetion of ts command lel sn file re no longer preset tier original lean, bt removed to the dretoy new, {Leas now ‘moe’ ono ote ile eluted commands Listing Files and Directories {sis to Un as DIR © DOS, I gives the asco tng, oists the coniens ofthe cunent or speciied decoy. As you mg bave fallen inthe babi of expecting, roo does more than what plain simple DIR ean do. No wonder, sonsdring the whole gang of sons awit) iba on side. Leal. Thee ae around to oven options ogo with (wha were they thinking otha isthe ‘ent in way uit eer fancy of ous Lets begin with he Plain and simple without ay pons si Corea oe ns pakio pees ‘panatls mus io, dont fll forthe filenames tat are present in te cent Girsctory. What you sould not unlike DIR of DOS Intl gemt eos toasla e Meas in alphabet ode, Lets now create file and then ce whether we canting Scat» ket Sontcerrt en sh Sosuescrt cae os Shay one Did you expect anerror because our lena ban witha"? Well, ‘names can bepin with «dot. Since no err has cecred While ‘reting this ile we soul be conden tarsi bound wo att Let tery tou sb cnbeans Iarganos ee de Fermi: Sper Ey Were has the fle erlcet gone? Well wel. Its therein the hector butts eiedas hiade le Fr htmter any ilename Dihich begins wit eee aside ie Andie wan 1 Tistese he hidden es we ned tous th soon of sha | | ‘che beat tangas us ae pannies ers Now tae i mooer pratt What arth i eatin. signifying? stands forthe eet dietary whereas stand forthe eat ofthe cunt deoy. Thee two ens automata pt fected inthe dco whenever ie des Ice, ‘iy te following command sip ee Feomes Letus tok era new entity called ‘metachaactes' No. thisisno Algresio. Ifyou alk of. you generally lk of meacharacters, and ‘se vers Metchaacte re chars tht th sl never ts face vale, They ae represetative of one oa group of charac and consitute Unit's way of indulging us users. Tse allow us 0 Tonmalstealsorn of retatobe ated bya sing. To unde em baer, we del wih them one By oe. ‘Takethemostperientonethegueston mark, When hsellcomes sows 7 understands tat the symbol signifies ny gle ‘Shrater, Conser the llowing crap Sie an one (rrr) “rs, assuming te four tt les tobe poset inthe cument Gety th shell sb sm’ p and" fn ars wo dlay tone es ening ina Te * fe trreted by the abel presence frames) of any Amber of caracters-Phs saying ese a saying wei the ies in he arent arectory are sted Infact whch we ssid Isp the bell smerpecte tas Iistall les whose ames bezin ith ence ponies andpakds” wore ited Tolisall es indrectry mye whichendin, sayz, we ould, Si yes seve a rye ‘Whateverbehe length ofthonans, theaters, guar forking “Ano very powesol means for sping itera for leseection ‘shy spplyng range. you want iat al les whose mame ar, witha vowel youcan say Sis eseur “This nse tha the ist charter ofthe name tobe sed mast be anyone ofthe ls given whi the squire rake athe ‘emaning canbe anything It your requirement soli those files whose nines do nt Sen ith vowel whntda yuo? List ol the other 21 apes? NO ‘nay. gain Uni indulges your whim. You spy el tos hose Fler whore names do ax bein with 3 vows). (Dae Progr a $1 so? ‘The symbol complemen the conton that follow i Hence the hove command woud list ll hose ls whose fist character ‘nyhing ter han a vowel ‘Remember thatthe salways subtited bya single character, We cseapecify' group of ehuracters within [3 i emjoxtsorn ‘This wil stall character filenames inthe current decor whose fist caratr in the ange stm, the second characteris ne ‘ings eto the thi chasse ent rang 41 9, wReeas the fourth an ith are ay valid characte. ‘Take deep beh before rating any farther Because whats ing ‘ofolon a longggg ising» theone obtained by the opin sed ‘ithe tes tera : five 1 et! up 2tunce 1:8 cabeans fines 1 ier! goup 23Jun060026 fargoae rwmioox 1 viet) ou 12n06 1254 Wis Gavan 1 wert geup 10.un08 1808 myst 1 1 1 1 ‘rocomee 2 vaer! goup 220un06 1406 pide rime 2 tae} gmp 16062225 penies fume 1 wae! eu OF NCE 3:6 erngbls fines 1 wet! goup O4un 061017 ma Intimidateg? Rela as we go along ll would low smoothly. Lets ‘enw aie he op Yt 2" Inetes tht the otal rambo of disk blocks thatthe ies in the eurentiecory have tecpied 22, Generally each block Ia Unis fof 1024 byes But the something which canbe changed ro some other mate of strats al ents les, restore, deve 8 Mls. Thos to igh between al of them uses pes. nf al be Med in top of he comand I-Ie etost character Maes hi ype Aedes ha the Me body i trea ineaes ht tira det Other posse file pes ven inthe flowing gue 1 F ‘rin le 4 Crater zc le ‘ Ble le 1 Sy ik Semaphore [ sioed mene fle Fiaue2 "The character sev fle andthe block speci les ae normaly scat inthe de detry, These ils ae used handle chaser ‘rcnted devices ike termina o lock eriemed deve ke ih. ‘Wen hese ies artiste filesize en fortes es stele 1 tajor and mine device mamters. Usa thee files tener found newer’ decay “The next ln churacters following he le type character athe le prmssions Each column sees gives terrier of Hinks, ener mime, rou nao, sie of en yes, date and ine when thee wa sted, a ally the Fl mame, “The concept ofan ‘owne' comes with he muluserO8.By defn, the peson who eras the fil the oer of that Hie, A "group a maybe formed ofa given numberof wes, whe maybe working on Sma data How many links he file has essenlly determines by how many iffeent ames he ee eserabe, When afisk ‘ot pyscally preset at wo paces but an be refered toby cher ‘ofthe ames. This very ef festa Ifyou aciderly delete ‘fl with single link or single ame teen angi ach, ‘Unix as ole undelete fay Bot fale has inks heey twomumes) your il sae even i one ofthe inks gts severed. A Tinks severed whe the ie deleted, So fa file is very important for you and you want to avoid its ‘cident deletion youshould exis ne non nk for sch ‘tle The commando dos i fy sgh forward ‘ho poom aypuem “This exablishes One mre nk forthe file poem in the frm fe "ame nempoem. Ifyou no take along listing you would find tet both she files ae sted each owing te presence o 2 inks, ‘Theconcept of having several nk ton ile offers anther advance ‘one ies obe shared between several uses sea ving ‘each wer separate copy of he se file we concrete ink of is ie m eich user's dietory. This avoids unecessary depistion of ‘hese file contents in dfretdectories, By fal any newfie that we seats mein whereas any ne etry we eet has two inks. Why 2 tink for a ditetoy? Becasne tat directory mame appears i wo asctory flee For cxumple fwecreateaditetoy de nadir al the rectory fle ant woold have an entry te, whereas the deioy fie di itstf wouldalso havean en il nthe Frm of which tans for

You might also like