You are on page 1of 54

Source:http://www.freeos.com/guides/lsst/index.

html

Chapter1:IntroductiontoShellprogramming WhatisLinuxShell?
Computerunderstandthelanguageof0'sand1'scalledbinarylanguage. Inearlydaysofcomputing,instructionareprovidedusingbinarylanguage,whichisdifficultforallofus,to readandwrite.SoinOsthereisspecialprogramcalledShell.Shellacceptsyourinstructionorcommandsin English(mostly)andifitsavalidcommand,itispasstokernel. Shellisauserprogramorit'senvironmentprovidedforuserinteraction.Shellisancommandlanguage interpreterthatexecutescommandsreadfromthestandardinputdevice(keyboard)orfromafile. Shellisnotpartofsystemkernel,butusesthesystemkerneltoexecuteprograms,createfilesetc. SeveralshellavailablewithLinuxincluding:
ShellName Developedby Where FreeSoftwareFoundation Remark Mostcommonshellin Linux.It'sFreewareshell.

BASH(BourneAgainSHell BrianFoxandChet ) Ramey CSH(CSHell) BillJoy

UniversityofCalifornia(For TheCshell'ssyntaxand BSD) usageareverysimilarto theCprogramming language. AT&TBellLabs TCSHisanenhancedbut completelycompatible versionoftheBerkeley UNIXCshell(CSH).

KSH(KornSHell) TCSH

DavidKorn Seethemanpage. Type$mantcsh

Tip:Tofindallavailableshellsinyoursystemtypefollowingcommand: $cat/etc/shells Notethateachshelldoesthesamejob,buteachunderstandadifferentcommandsyntaxandprovides differentbuiltinfunctions. InMSDOS,ShellnameisCOMMAND.COMwhichisalsousedforsamepurpose,butit'snotaspowerful asourLinuxShellsare! Anyoftheaboveshellreadscommandfromuser(viaKeyboardorMouse)andtellsLinuxOswhatusers want.Ifwearegivingcommandsfromkeyboarditiscalledcommandlineinterface(Usuallyinfrontof$ prompt,ThispromptisdependuponyourshellandEnvironmentthatyousetorbyyourSystem Administrator,thereforeyoumaygetdifferentprompt). Tip:Tofindyourcurrentshelltypefollowingcommand $echo$SHELL

WhatisShellScript?
Normallyshellsareinteractive.Itmeansshellacceptcommandfromyou(viakeyboard)andexecutethem. Butifyouusecommandonebyone(sequenceof'n'numberofcommands),theyoucanstorethissequence ofcommandtotextfileandtelltheshelltoexecutethistextfileinsteadofenteringthecommands.Thisis knowasshellscript. Shellscriptdefinedas: "ShellScriptisseriesofcommandwritteninplaintextfile.ShellscriptisjustlikebatchfileisMSDOSbut havemorepowerthantheMSDOSbatchfile."

WhytoWriteShellScript?
Shellscriptcantakeinputfromuser,fileandoutputthemonscreen. Usefultocreateourowncommands. Savelotsoftime. Toautomatesometaskofdaytodaylife. SystemAdministrationpartcanbealsoautomated.

WhichShellWeareusingtowriteShellScript?
Inthistutorialweareusingbashshell.

ObjectiveofthisTutorial(LSSTv.1.5)
TrytounderstandLinuxOs TrytounderstandthebasicsofLinuxshell TrytolearntheLinuxshellprogramming

GettingstartedwithShellProgramming
Inthispartoftutorialyouareintroducetoshellprogramming,howtowritescript,executethemetc.Wewill gettingstartedwithwritingsmallshellscript,thatwillprint"KnowledgeisPower"onscreen.

Howtowriteshellscript
Followingstepsarerequiredtowriteshellscript: (1)Useanyeditorlikeviormcedittowriteshellscriptonttymode.InXwindowstrykateandgedit. (2)Afterwritingshellscriptsetexecutepermissionforyourscriptasfollows syntax: chmodpermissionyourscriptname

Examples: $ chmod +x your-script-name $ chmod 755 your-script-name Note:Thiswillsetreadwriteexecute(7)permissionforowner,forgroupandotherpermissionisreadand executeonly(5). (3)Executeyourscriptas syntax: bashyourscriptname shyourscriptname ./yourscriptname Examples: $ bash bar $ sh bar $ ./bar NOTEInthelastsyntax./meanscurrentdirectory,Butonly.(dot)meansexecutegivencommandfilein currentshellwithoutstartingthenewcopyofshell,Thesyntaxfor.(dot)commandisasfollows Syntax: .commandname Example: $ . foo Nowyouarereadytowritefirstshellscriptthatwillprint"KnowledgeisPower"onscreen. Openyourfavoritetexteditor. Andwritethefollowingcode: # # My first shell script # clear echo "Knowledge is Power" Aftersavingtheabovescript,youcanrunthescriptasfollows: $ ./first Thiswillnotrunscriptsincewehavenotsetexecutepermissionforourscriptfirst;todothistypecommand $ chmod 755 first $ ./first

Firstscreenwillbeclear,thenKnowledgeisPowerisprintedonscreen. ScriptCommand(s) Meaning #followedbyanytextisconsideredas comment.Commentgivesmoreinformation aboutscript,logicalexplanationaboutshell script. Syntax: #commenttext clearthescreen Toprintmessageorvalueofvariableson screen,weuseechocommand,generalform ofechocommandisasfollows syntax: echo"Message"

# #Myfirstshellscript #

clear

echo"KnowledgeisPower"

Tip:Forshellscriptfiletrytogivefileextensionsuchas.sh,whichcanbeeasilyidentifiedbyyouasshell script. Exercise: 1)Writefollowingshellscript,saveit,executeitandnotedowntheit'soutput. # # # Script to print user information who currently login , current date & time # clear echo "Hello $USER" echo "Today is \c ";date echo "Number of user login : \c" ; who | wc -l echo "Calendar" cal exit 0 FuturePoint:Attheendwhystatementexit0isused?(tip:manexit)

VariablesinShell
Toprocessourdata/information,datamustbekeptincomputersRAMmemory.RAMmemoryisdivided intosmalllocations,andeachlocationhaduniquenumbercalledmemorylocation/address,whichisusedto holdourdata.Programmercangiveauniquenametothismemorylocation/addresscalledmemoryvariable orvariable(Itsanamedstoragelocationthatmaytakedifferentvalues,butonlyoneatatime). InLinux(Shell),therearetwotypesofvariable: (1)SystemvariablesCreatedandmaintainedbyLinuxitself.ThistypeofvariabledefinedinCAPITAL LETTERS. (2)Userdefinedvariables(UDV)Createdandmaintainedbyuser.Thistypeofvariabledefinedinlower

letters. Youcanseesystemvariablesbygivingcommandlike$set,someoftheimportantSystemvariablesare: SystemVariable BASH=/bin/bash BASH_VERSION=1.14.7(1) COLUMNS=80 HOME=/home/vivek LINES=25 LOGNAME=students OSTYPE=Linux PATH=/usr/bin:/sbin:/bin:/usr/sbin PS1=[\u@\h\W]\$ PWD=/home/students/Common SHELL=/bin/bash USERNAME=vivek Ourshellname Ourshellversionname No.ofcolumnsforourscreen Ourhomedirectory No.ofcolumnsforourscreen studentsOurloggingname OurOstype Ourpathsettings Ourpromptsettings Ourcurrentworkingdirectory Ourshellname UsernamewhoiscurrentlylogintothisPC Meaning

NOTEthatSomeoftheabovesettingscanbedifferentinyourPC/Linuxenvironment.Youcanprintanyof theabovevariablescontainsasfollows: $ echo $USERNAME $ echo $HOME Exercise: 1)Ifyouwanttoprintyourhomedirectorylocationthenyougivecommand: a)$ echo $HOME OR (b)$ echo HOME Whichoftheabovecommandiscorrect&why?

Caution:DonotmodifySystemvariablethiscansometimecreateproblems.

HowtodefineUserdefinedvariables(UDV)
TodefineUDVusefollowingsyntax Syntax: variablename=value 'value'isassignedtogiven'variablename'andValuemustbeonrightside=sign. Example: $ no=10 #thisisok $ 10=no #Error,NOTOk,Valuemustbeonrightsideof=sign. Todefinevariablecalled'vech'havingvalueBus $ vech=Bus

Todefinevariablecallednhavingvalue10 $ n=10

RulesforNamingvariablename(BothUDVand SystemVariable)
(1)VariablenamemustbeginwithAlphanumericcharacterorunderscorecharacter(_),followedbyoneor moreAlphanumericcharacter.Fore.g.Validshellvariableareasfollows HOME SYSTEM_VERSION vech no (2)Don'tputspacesoneithersideoftheequalsignwhenassigningvaluetovariable.Fore.g.Infollowing variabledeclarationtherewillbenoerror $ no=10 Buttherewillbeproblemforanyofthefollowingvariabledeclaration: $ no =10 $ no= 10 $ no = 10 (3)Variablesarecasesensitive,justlikefilenameinLinux.Fore.g. $ no=10 $ No=11 $ NO=20 $ nO=2 Aboveallaredifferentvariablename,sotoprintvalue20wehavetouse$echo$NOandnotanyofthe following $ echo $no#willprint10butnot20 $ echo $No#willprint11butnot20 $ echo $nO#willprint2butnot20 (4)YoucandefineNULLvariableasfollows(NULLvariableisvariablewhichhasnovalueatthetimeof definition)Fore.g. $vech= $vech="" Trytoprintit'svaluebyissuingfollowingcommand $ echo $vech Nothingwillbeshownbecausevariablehasnovaluei.e.NULLvariable. (5)Donotuse?,*etc,tonameyourvariablenames.

HowtoprintoraccessvalueofUDV(Userdefined variables)
ToprintoraccessUDVusefollowingsyntax Syntax: $variablename Definevariablevechandnasfollows: $ vech=Bus $ n=10 Toprintcontainsofvariable'vech'type $ echo $vech Itwillprint'Bus',Toprintcontainsofvariable'n'typecommandasfollows $ echo $n Exercise Q.1.HowtoDefinevariablexwithvalue10andprintitonscreen. Q.2.HowtoDefinevariablexnwithvalueRaniandprintitonscreen Q.3.Howtoprintsumoftwonumbers,let'ssay6and3? Q.4.Howtodefinetwovariablex=20,y=5andthentoprintdivisionofxandy(i.e.x/y) Q.5.Modifyaboveandstoredivisionofxandytovariablecalledz Q.6.Pointouterrorifanyinfollowingscript # # # Script to test MY knowledge about variables! # myname=Vivek myos = TroubleOS myno=5 echo "My name is $myname" echo "My os is $myos" echo "My number is myno, can you see this number"

echoCommand
Useechocommandtodisplaytextorvalueofvariable. echo[options][string,variables...] Displaystextorvariablesvalueonscreen. Options nDonotoutputthetrailingnewline. eEnableinterpretationofthefollowingbackslashescapedcharactersinthestrings: \aalert(bell) \bbackspace \csuppresstrailingnewline \nnewline

\rcarriagereturn \thorizontaltab \\backslash Fore.g.$echoe"Anappleadaykeepsaway\a\t\tdoctor\n"

ShellArithmetic
Usetoperformarithmeticoperations. Syntax: exprop1mathoperatorop2 Examples: $ expr 1 + 3 $ expr 2 - 1 $ expr 10 / 2 $ expr 20 % 3 $ expr 10 \* 3 $ echo `expr 6 + 3` Note: expr20%3Remainderreadas20mod3andremainderis2. expr10\*3Multiplicationuse\*andnot*sinceitswildcard. Forthelaststatementnotthefollowingpoints (1)First,beforeexprkeywordweused`(backquote)signnotthe(singlequotei.e.')sign.Backquoteis generallyfoundonthekeyundertilde(~)onPCkeyboardORtotheaboveofTABkey. (2)Second,exprisalsoendwith`i.e.backquote. (3)Hereexpr6+3isevaluatedto9,thenechocommandprints9assum (4)Hereifyouusedoublequoteorsinglequote,itwillNOTwork Fore.g. $echo"expr6+3"#Itwillprintexpr6+3 $echo'expr6+3'#Itwillprintexpr6+3

MoreaboutQuotes
Therearethreetypesofquotes Quotes " ' ` Name Double Quotes Meaning "DoubleQuotes"Anythingencloseindoublequotesremovedmeaningofthat characters(except\and$).

Singlequotes 'Singlequotes'Enclosedinsinglequotesremainsunchanged. Backquote `Backquote`Toexecutecommand

Example: $echo"Todayisdate" Can'tprintmessagewithtoday'sdate. $echo"Todayis`date`". Itwillprinttoday'sdateas,TodayisTueJan....,Canyouseethatthe`date`statementusesbackquote?

ExitStatus
BydefaultinLinuxifparticularcommand/shellscriptisexecuted,itreturntwotypeofvalueswhichisused toseewhethercommandorshellscriptexecutedissuccessfulornot. (1)Ifreturnvalueiszero(0),commandissuccessful. (2)Ifreturnvalueisnonzero,commandisnotsuccessfulorsomesortoferrorexecutingcommand/shell script. ThisvalueisknowasExitStatus. Buthowtofindoutexitstatusofcommandorshellscript? Simple,todeterminethisexitStatusyoucanuse$?specialvariableofshell. Fore.g.(Thisexampleassumesthatunknow1filedoestnotexistonyourharddrive) $rmunknow1file Itwillshowerrorasfollows rm:cannotremove`unkowm1file':Nosuchfileordirectory andafterthatifyougivecommand $echo$? itwillprintnonzerovaluetoindicateerror.Nowgivecommand $ls $echo$? Itwillprint0toindicatecommandissuccessful. Exercise Trythefollowingcommandsandnotdowntheexitstatus: $ expr 1 + 3 $ echo $? $echoWelcome $echo$? $wildwestcanwork? $echo$? $date $echo$? $echon$? $echo$?

ThereadStatement
Usetogetinput(datafromuser)fromkeyboardandstore(data)tovariable. Syntax: readvariable1,variable2,...variableN Followingscriptfirstaskuser,nameandthenwaitstoenternamefromtheuserviakeyboard.Thenuser entersnamefromkeyboard(aftergivingnameyouhavetopressENTERkey)andenterednamethrough keyboardisstored(assigned)tovariablefname. # #Script to read your name from key-board # echo "Your first name please:" read fname echo "Hello $fname, Lets be friend!" Runitasfollows: $ chmod 755 sayH $ ./sayH Yourfirstnameplease:vivek Hellovivek,Letsbefriend!

Wildcards(FilenameShorthandormeta Characters)
Wildcard /Shorthand Meaning $ls* $lsa* * Matchesanystringorgroupof characters. $ls*.c $lsut*.c $ls? ? Matchesanysinglecharacter. $lsfo? [...] Matchesanyoneoftheenclosed characters $ls[abc]* Examples willshowallfiles willshowallfileswhose firstnameisstartingwith letter'a' willshowallfileshaving extension.c willshowallfileshaving extension.cbutfilename mustbeginwith'ut'. willshowallfileswhose namesare1characterlong willshowallfileswhose namesare3characterlong andfilenamebeginwithfo willshowallfilesbeginning withlettersa,b,c

Note: [....]Apairofcharactersseparatedbyaminussigndenotesarange. Example: $ls/bin/[ac]* Willshowallfilesnamebeginningwithlettera,borclike 1. /bin/arch /bin/awk /bin/bsh /bin/chmod /bin/cp /bin/ash /bin/basename/bin/cat /bin/chown /bin/cpio /bin/ash.static /bin/bash /bin/chgrp/bin/consolechars/bin/csh But $ls/bin/[!ao] $ls/bin/[^ao] Ifthefirstcharacterfollowingthe[isa!ora^,thenanycharacternotenclosedismatchedi.e.donotshow usfilenamethatbeginningwitha,b,c,e...o,like /bin/ps /bin/rv /bin/pwd /bin/rview /bin/red /bin/sayHello /bin/remadmin/bin/sed /bin/rm /bin/setserial /bin/rmdir /bin/sfxload /bin/rpm /bin/sh /bin/sleep/bin/touch/bin/view /bin/sort/bin/true/bin/wcomp /bin/stty/bin/umount/bin/xconf /bin/su/bin/uname/bin/ypdomainname /bin/sync/bin/userconf/bin/zcat /bin/tar/bin/usleep /bin/tcsh/bin/vi

Morecommandononecommandline
Syntax: command1;command2 Toruntwocommandwithonecommandline. Examples: $date;who Willprinttoday'sdatefollowedbyuserswhoarecurrentlylogin.NotethatYoucan'tuse $datewho forsamepurpose,youmustputsemicoloninbetweendateandwhocommand.

CommandLineProcessing
Trythefollowingcommand(assumesthatthefile"grate_stories_of"isnotexistonyoursystem) $lsgrate_stories_of Itwillprintmessagesomethinglikegrate_stories_of:Nosuchfileordirectory. lsisthenameofanactualcommandandshellexecutedthiscommandwhenyoutypecommandatshell prompt.NowitcreatesonemorequestionWhatarecommands?Whathappenedwhenyoutype$ls grate_stories_of?

Thefirstwordoncommandlineis,lsisnameofthecommandtobeexecuted. Everythingelseoncommandlineistakenasargumentstothiscommand.Fore.g. $tail+10myf Nameofcommandistail,andtheargumentsare+10andmyf. Exercise Trytodeterminecommandandargumentsfromfollowingcommands $ ls foo $ cp y y.bak $ mv y.bak y.okay $ tail -10 myf $ mail raj $ sort -r -n myf $ date $ clear NOTE: $#holdsnumberofargumentsspecifiedoncommandline.And$*or$@refertoallargumentspassedto script.

WhyCommandLineargumentsrequired
1. Tellingthecommand/utilitywhichoptiontouse. 2. Informingtheutility/commandwhichfileorgroupoffilestoprocess(reading/writingoffiles). Let'stakermcommand,whichisusedtoremovefile,butwhichfileyouwanttoremoveandhowyouwill tailthistormcommand(evenrmcommanddon'taskyounameoffilethatyouwouldliketoremove).So whatwedoiswewritecommandasfollows: $rm{filename} Herermiscommandandfilenameisfilewhichyouwouldliketoremove.Thiswayyoutailrmcommand whichfileyouwouldliketoremove.Sowearedoingonewaycommunicationwithourcommandby specifyingfilenameAlsoyoucanpasscommandlineargumentstoyourscripttomakeitmoreusers friendly.Buthowweaccesscommandlineargumentinourscript. Letstakelscommand $Lsa/* Thiscommandhas2commandlineargumentaand/*isanother.Forshellscript, $myshellfoobar

ShellScriptnamei.e.myshell Firstcommandlineargumentpassedtomyshelli.e.foo Secondcommandlineargumentpassedtomyshelli.e.bar

Inshellifwewishtoreferthiscommandlineargumentwereferaboveasfollows myshellitis$0 fooitis$1 baritis$2 Here$#(builtinshellvariable)willbe2(SincefooandbaronlytwoArguments),Pleasenoteatatime such9argumentscanbeusedfrom$1..$9,Youcanalsoreferallofthembyusing$*(whichexpandto `$1,$2...$9`).Notethat$1..$9i.ecommandlineargumentstoshellscriptisknowas"positionalparameters". Exercise Trytowritefollowingforcommands ShellScriptName($0), No.ofArguments(i.e.$#), Andactualargument(i.e.$1,$2etc) $ sum 11 20 $ math 4 - 7 $ d $ bp -5 myf +20 $ Ls * $ cal $ findBS 4 8 24 BIG Followingscriptisusedtoprintcommandlingargumentandwillshowyouhowtoaccessthem: #!/bin/sh # # Script that demos, command line args # echo "Total number of command line argument are $#" echo "$0 is script name" echo "$1 is first argument" echo "$2 is second argument" echo "All of them are :- $* or $@" Runitasfollows Setexecutepermissionasfollows: $chmod755demo Runit&testitasfollows: $./demoHelloWorld Iftestsuccessful,copyscripttoyourownbindirectory(Installscriptforprivateuse) $cpdemo~/bin Checkwhetheritisworkingornot(?) $demo $demoHelloWorld NOTE:Afterthis,foranyscriptyouhavetousedabovecommand,insequence,Iamnotgoingtoshowyou alloftheabovecommand(s)forrestofTutorial.

Alsonotethatyoucan'tassignethenewvaluetocommandlineargumentsi.epositionalparameters.So followingallstatementsinshellscriptareinvalid: $1=5 $2="MyName"

RedirectionofStandardoutput/inputi.e.Input Outputredirection
Mostlyallcommandgivesoutputonscreenortakeinputfromkeyboard,butinLinux(andinotherOSs also)it'spossibletosendoutputtofileortoreadinputfromfile. Fore.g. $lscommandgivesoutputtoscreen;tosendoutputtofileoflscommandgivecommand $ls>filename Itmeansputoutputoflscommandtofilename. Therearethreemainredirectionsymbols>,>>,< (1)>RedirectorSymbol Syntax: Linuxcommand>filename TooutputLinuxcommandsresult(outputofcommandorshellscript)tofile.Notethatiffilealreadyexist, itwillbeoverwrittenelsenewfileiscreated.Fore.g.Tosendoutputoflscommandgive $ls>myfiles Nowif'myfiles'fileexistinyourcurrentdirectoryitwillbeoverwrittenwithoutanytypeofwarning. (2)>>RedirectorSymbol Syntax: Linuxcommand>>filename TooutputLinuxcommandsresult(outputofcommandorshellscript)toENDoffile.Notethatiffileexist, itwillbeopenedandnewinformation/datawillbewrittentoENDoffile,withoutlosingprevious information/data,Andiffileisnotexist,thennewfileiscreated.Fore.g.Tosendoutputofdatecommandto alreadyexistfilegivecommand $date>>myfiles (3)<RedirectorSymbol Syntax: Linuxcommand<filename TotakeinputtoLinuxcommandfromfileinsteadofkeyboard.Fore.g.Totakeinputforcatcommandgive $cat<myfiles Youcanalsouseaboveredirectorssimultaneouslyasfollows Createtextfilesnameasfollows $cat>sname vivek ashish

zebra babu PressCTRL+Dtosave. Nowissuefollowingcommand. $sort<sname>sorted_names $catsorted_names ashish babu vivek zebra Inaboveexamplesort($sort<sname>sorted_names)commandtakesinputfromsnamefileandoutput ofsortcommand(i.e.sortednames)isredirectedtosorted_namesfile. Tryonemoreexampletoclearyouridea: $tr"[az]""[AZ]"<sname>cap_names $catcap_names VIVEK ASHISH ZEBRA BABU trcommandisusedtotranslatealllowercasecharacterstouppercaseletters.Ittakeinputfromsnamefile, andtr'soutputisredirectedtocap_namesfile. FuturePoint:Tryfollowingcommandandfindoutmostimportantpoint: $sort>new_sorted_names<sname $catnew_sorted_names

Pipes
Apipeisawaytoconnecttheoutputofoneprogramtotheinputofanotherprogramwithoutanytemporary file.

PipeDefinedas: "Apipeisnothingbutatemporarystorageplacewheretheoutputofonecommandisstoredandthen passedastheinputforsecondcommand.Pipesareusedtorunmorethantwocommands(Multiple commands)fromsamecommandline." Syntax: command1|command2

Examles: CommandusingPipes $ls|more $who|sort $who|sort>user_list $who|wcl MeaningorUseofPipes Outputoflscommandisgivenasinputtomore commandSothatoutputisprintedonescreenfull pageatatime. Outputofwhocommandisgivenasinputtosort commandSothatitwillprintsortedlistofusers Sameasaboveexceptoutputofsortissendto (redirected)user_listfile Outputofwhocommandisgivenasinputtowc commandSothatitwillnumberofuserwhologonto system Outputoflscommandisgivenasinputtowc commandSothatitwillprintnumberoffilesin currentdirectory. Outputofwhocommandisgivenasinputtogrep commandSothatitwillprintifparticularusername ifheislogonornothingisprinted(Toseeparticular userislogonornot)

$lsl|wcl

$who|grepraju

Filter
IfaLinuxcommandacceptsitsinputfromthestandardinputandproducesitsoutputonstandardoutputis knowasafilter.Afilterperformssomekindofprocessontheinputandgivesoutput.Fore.g..Supposeyou havefilecalled'hotel.txt'with100linesdata,Andfrom'hotel.txt'youwouldliketoprintcontainsfromline number20tolinenumber30andstorethisresulttofilecalled'hlist'thengivecommand: $tail+20<hotel.txt|headn30>hlist Hereheadcommandisfilterwhichtakesitsinputfromtailcommand(tailcommandstartselectingfrom linenumber20ofgivenfilei.e.hotel.txt)andpassesthislinesasinputtohead,whoseoutputisredirectedto 'hlist'file. Consideronemorefollowingexample $sort<sname|uniq>u_sname Example:Removingduplicatelinesusinguniqutility Createtextfilepersonameasfollows: HelloIamvivek 12333 12333 welcome to

saicomputeracademy,a'bad. whatstillIremeberthatname. oaky!howareuluser? whatstillIremeberthatname. Aftercreatingfile,issuefollowingcommandatshellprompt $uniqpersoname HelloIamvivek 12333 welcome to saicomputeracademy,a'bad. whatstillIremeberthatname. oaky!howareuluser? whatstillIremeberthatname. Abovecommandprintsthoselineswhichareunique.Fore.g.ouroriginalfilecontains12333twice,so additionalcopiesof12333aredeleted.Butifyouexamineoutputofuniq,youwillnoticethat12333isgone (Duplicate),and"whatstillIremeberthatname"remainsasits.Becausetheuniqutilitycompareonly adjacentlines,duplicatelinesmustbenexttoeachotherinthefile.Tosolvethisproblemyoucanuse commandasfollows $sortpersoname|uniq GeneralSyntaxofuniqutility: Syntax: uniq{filename}

WhatisProcesses
ProcessiskindofprogramortaskcarriedoutbyyourPC.Fore.g. $lslR lscommandorarequesttolistfilesinadirectoryandallsubdirectoryinyourcurrentdirectoryItisa process. Processdefinedas: "Aprocessisprogram(commandgivenbyuser)toperformspecificJob.InLinuxwhenyoustartprocess,it givesanumbertoprocess(calledPIDorprocessid),PIDstartsfrom0to65535."

WhyProcessrequired
AsYouknowLinuxismultiuser,multitaskingOs.Itmeansyoucanrunmorethantwoprocess simultaneouslyifyouwish.Fore.g.Tofindhowmanyfilesdoyouhaveonyoursystemyoumaygive commandlike: $ls/R|wcl Thiscommandwilltakelotoftimetosearchallfilesonyoursystem.Soyoucanrunsuchcommandin Backgroundorsimultaneouslybygivingcommandlike

$ls/R|wcl& Theampersand(&)attheendofcommandtellsshellsstartprocess(ls/R|wcl)andrunitin backgroundtakesnextcommandimmediately. Process&PIDdefinedas: "Aninstanceofrunningcommandiscalledprocessandthenumberprintedbyshelliscalledprocessid (PID),thisPIDcanbeusetoreferspecificrunningprocess."

LinuxCommandRelatedwithProcess
Followingtablesmostcommonlyusedcommand(s)withprocess: Forthispurpose Toseecurrentlyrunningprocess ps UsethisCommand $ps $kill1012 $killallhttpd $psag $kill0 $ls/R|wcl& $psaux Fore.g.youwanttosee whetherApachewebserver processisrunningornotthen givecommand $psax|grephttpd Examples*

TostopanyprocessbyPIDi.e.tokill kill{PID} process Tostopprocessesbynamei.e.tokill process Togetinformationaboutallrunning process Tostopallprocessexceptyourshell Forbackgroundprocessing(With&, usetoputparticularcommandand programinbackground) killall{Processname} psag kill0 linuxcommand&

Todisplaytheowneroftheprocesses psaux alongwiththeprocesses Toseeifaparticularprocessisrunning ornot.Forthispurposeyouhavetousepsax|grepprocessUwanttosee pscommandincombinationwiththe grepcommand

Toseecurrentlyrunningprocessesand top otherinformationlikememoryand Seetheoutputoftopcommand. CPUusagewithrealtimeupdates. Todisplayatreeofprocesses pstree

$top
Notethattoexitfromtopcommand pressq.

$pstree

*Torunsomeofthiscommandyouneedtoberootorequivalntuser. NOTEthatyoucanonlykillprocesswhicharecreatedbyyourself.AAdministratorcanalmostkill9598% process.Butsomeprocesscannotbekilled,suchasVDUProcess.

Chapter2:Shells(bash)structuredLanguage Constructs Introduction


MakingdecisionisimportantpartinONCElifeaswellasincomputerslogicaldrivenprogram.Infactlogic isnotLOGICuntilyouusedecisionmaking.Thischapterintroducestothebashsstructuredlanguage constrictssuchas: Decisionmaking Loops IsthereanydifferencemakingdecisioninReallifeandwithComputers?Wellreallifedecisionarequit complicatedtoallofusandcomputersevendon'thavethatmuchpowertounderstandourreallifedecisions. Whatcomputerknowis0(zero)and1thatisYesorNo.Tomakethisideaclear,letsplaysomegame (WOW!)withbcLinuxcalculatorprogram. $bc Afterthiscommandbcisstartedandwaitingforyourcommands,i.e.giveitsomecalculationasfollows type5+2as: 5+2 7 7isresponseofbci.e.additionof5+2youcaneventry 52 5/2 Seewhathappenedifyoutype5>2asfollows 5>2 1 1(One?)isresponseofbc,How?bccompare5with2as,Is5isgreaterthen2,(IfIasksamequestionto you,youranswerwillbeYES),bcgivesthis'YES'answerbyshowing1value.Nowtry 5<2 0 0(Zero)indicatesthefalsei.e.Is5islessthan2?,Youranswerwillbenowhichisindicatedbybcby showing0(Zero).Rememberinbc,relationalexpressionalwaysreturnstrue(1)orfalse(0zero). TryfollowinginbctoclearyourIdeaandnotdownbc'sresponse 5>12 5==10 5!=2 5==5 12<2

Expression 5>12 5==10 5!=2 5==5 1<2

Meaningtous Is5greaterthan12 Is5isequalto10 Is5isNOTequalto2 Is5isequalto5 Is1islessthan2

YourAnswer NO NO YES YES Yes

BC'sResponse 0 0 1 1 1

ItmeanswheneverthereisanytypeofcomparisoninLinuxShellItgivesonlytwoansweroneisYESand NOisother. InLinuxShellValue ZeroValue(0) Meaning Yes/True Example 0 1,32,55 anything butnot zero

NONZEROValue

No/False

RememberbothbcandLinuxShellusesdifferentwaystoshowTrue/Falsevalues Value True/Yes False/No 1 0 Showninbcas 0 Nonzerovalue ShowninLinuxShellas

ifcondition
ifconditionwhichisusedfordecisionmakinginshellscript,Ifgivenconditionistruethencommand1is executed. Syntax:
if condition then command1 if condition is true or if exit status of condition is 0 (zero) ... ... fi

Conditionisdefinedas: "Conditionisnothingbutcomparisonbetweentwovalues." Forcompressionyoucanusetestor[expr]statementsorevenexiststatuscanbealsoused. Expreessionisdefinedas: "Anexpressionisnothingbutcombinationofvalues,relationaloperator(suchas>,<,<>etc)and mathematicaloperators(suchas+,,/etc)."

Followingareallexamplesofexpression: 5>2 3+6 3*65 a<b c>5 c>5+301 Typefollowingcommands(assumesyouhavefilecalledfoo) $catfoo $echo$? Thecatcommandreturnzero(0)i.e.exitstatus,onsuccessful,thiscanbeused,inifconditionasfollows, Writeshellscriptas $ cat > showfile #!/bin/sh # #Script to print file # if cat $1 then echo -e "\n\nFile $1, found and successfully echoed" fi Runabovescriptas: $chmod755showfile $./showfilefoo Shellscriptnameisshowfile($0)andfooisargument(whichis$1).Thenshellcompareitasfollows: ifcat$1whichisexpandedtoifcatfoo. Detailedexplanation ifcatcommandfindsfoofileandifitssuccessfullyshownonscreen,itmeansourcatcommandis successfulanditsexiststatusis0(indicatessuccess),Soourifconditionisalsotrueandhencestatement echoe"\n\nFile$1,foundandsuccessfullyechoed"isproceedbyshell.Nowifcatcommandisnot successfulthenitreturnsnonzerovalue(indicatessomesortoffailure)andthisstatementechoe"\n\nFile $1,foundandsuccessfullyechoed"isskippedbyourshell. Exercise Writeshellscriptasfollows: cat > trmif # # Script to test rm command and exist status # if rm $1 then echo "$1 file deleted" fi PressCtrl+dtosave $chmod755trmif

Answerthefollowingquestioninreferancetoabovescript: (A)foofileexistsonyourdiskandyougivecommand,$./trmfifoowhatwillbeoutput? (B)Ifbarfilenotpresentonyourdiskandyougivecommand,$./trmfibarwhatwillbeoutput? (C)Andifyoutype$./trmfiWhatwillbeoutput?

testcommandor[expr]
testcommandor[expr]isusedtoseeifanexpressionistrue,andifitistrueitreturnzero(0),otherwise returnsnonzeroforfalse. Syntax: testexpressionOR[expression] Example: Followingscriptdeterminewhethergivenargumentnumberispositive. $ cat > ispostive #!/bin/sh # # Script to see whether argument is positive # if test $1 -gt 0 then echo "$1 number is positive" fi Runitasfollows $chmod755ispostive $ispostive5 5numberispositive $ispostive45 Nothingisprinted $ispostive ./ispostive:test:gt:unaryoperatorexpected Detailedexplanation Theline,iftest$1gt0,testtoseeiffirstcommandlineargument($1)isgreaterthan0.Ifitistrue(0)then testwillreturn0andoutputwillprintedas5numberispositivebutfor45argumentthereisnooutput becauseourconditionisnottrue(0)(no45isnotgreaterthan0)henceechostatementisskipped.Andfor laststatementwehavenotsuppliedanyargumenthenceerror./ispostive:test:gt:unaryoperatorexpected, isgeneratedbyshell,toavoidsucherrorwecantestwhethercommandlineargumentissuppliedornot. testor[expr]workswith 1.Integer(Numberwithoutdecimalpoint) 2.Filetypes 3.Characterstrings

ForMathematics,usefollowingoperatorinShellScript Mathematical OperatorinShell Script eq ne lt le gt ge isequalto islessthan Meaning NormalArithmetical/ Mathematical Statements 5==6 5<6 ButinShell For[expr] Forteststatement statementwithif withifcommand command iftest5eq6 iftest5ne6 iftest5lt6 iftest5le6 iftest5gt6 iftest5ge6 if[5eq6] if[5ne6] if[5lt6] if[5le6] if[5gt6] if[5ge6]

isnotequalto 5!=6 islessthanor 5<=6 equalto isgreaterthan 5>6 isgreaterthan 5>=6 orequalto

NOTE:==isequal,!=isnotequal. ForstringComparisonsuse Operator Meaning

string1=string2 string1isequaltostring2 string1!=string2 string1isNOTequaltostring2 string1 nstring1 zstring1 string1isNOTNULLornotdefined string1isNOTNULLanddoesexist string1isNULLanddoesexist Shellalsotestforfileanddirectorytypes Test sfile ffile ddir wfile rfile xfile Nonemptyfile IsFileexistornormalfileandnotadirectory IsDirectoryexistandnotafile Iswriteablefile Isreadonlyfile Isfileisexecutable Meaning

LogicalOperators Logicaloperatorsareusedtocombinetwoormoreconditionatatime Operator !expression expression1aexpression2 expression1oexpression2 LogicalNOT LogicalAND LogicalOR Meaning

if...else...fi
Ifgivenconditionistruethencommand1isexecutedotherwisecommand2isexecuted. Syntax:
if condition then

condition is zero (true - 0) execute all commands up to else statement if condition is not true then execute all commands up to fi

else fi

Fore.g.WriteScriptasfollows: #!/bin/sh # # Script to see whether argument is positive or negative # if [ $# -eq 0 ] then echo "$0 : You must give/supply one integers" exit 1 fi

if test $1 -gt 0 then echo "$1 number is positive" else echo "$1 number is negative" fi Tryitasfollows: $chmod755isnump_n $isnump_n5 5numberispositive

$isnump_n45 45numberisnegative $isnump_n ./ispos_n:Youmustgive/supplyoneintegers $isnump_n0 0numberisnegative Detailedexplanation Firstscriptcheckswhethercommandlineargumentisgivenornot,ifnotgiventhenitprinterrormessage as"./ispos_n:Youmustgive/supplyoneintegers".ifstatementcheckswhethernumberofargument($#) passedtoscriptisnotequal(eq)to0,ifwepassedanyargumenttoscriptthenthisifstatementisfalseand ifnocommandlineargumentisgiventhenthisifstatementistrue.Theechocommandi.e. echo"$0:Youmustgive/supplyoneintegers" || || 12 1willprintNameofscript 2willprintthiserrormessage Andfinallystatementexit1causesnormalprogramterminationwithexitstatus1(nonzeromeansscriptis notsuccessfullyrun). Thelastsamplerun$isnump_n0,givesoutputas"0numberisnegative",becausegivenargumentisnot> 0,henceconditionisfalseandit'stakenasnegativenumber.Toavoidthisreplacesecondifstatementwithif test$1ge0.

Nestedifelsefi
Youcanwritetheentireifelseconstructwithineitherthebodyoftheifstatementofthebodyofanelse statement.Thisiscalledthenestingofifs. osch=0 echo echo echo read "1. Unix (Sun Os)" "2. Linux (Red Hat)" -n "Select your os choice [1 or 2]? " osch

if [ $osch -eq 1 ] ; then echo "You Pick up Unix (Sun Os)" else #### nested if i.e. if within if ###### if [ $osch -eq 2 ] ; then echo "You Pick up Linux (Red Hat)"

else fi fi Runtheaboveshellscriptasfollows: $chmod+xnestedif.sh $./nestedif.sh 1.Unix(SunOs) 2.Linux(RedHat) Selectyouoschoice[1or2]?1 YouPickupUnix(SunOs) $./nestedif.sh 1.Unix(SunOs) 2.Linux(RedHat) Selectyouoschoice[1or2]?2 YouPickupLinux(RedHat) $./nestedif.sh 1.Unix(SunOs) 2.Linux(RedHat) Selectyouoschoice[1or2]?3 Whatyoudon'tlikeUnix/LinuxOS. NotethatSecondifelseconstuctisnestedinthefirstelsestatement.Iftheconditioninthefirstifstatement isfalsethetheconditioninthesecondifstatementischecked.Ifitisfalseaswellthefinalelsestatementis executed. Youcanusethenestedifsasfollowsalso: Syntax:
if condition then if condition then ..... .. do this else .... .. do this fi else ... ..... do this fi

echo "What you don't like Unix/Linux OS."

Multilevelifthenelse
Syntax: if condition then condition is zero (true - 0) execute all commands up to elif statement elif condition1 then condition1 is zero (true - 0) execute all commands up to elif statement elif condition2 then condition2 is zero (true - 0) execute all commands up to elif statement else None of the above condtion,condtion1,condtion2 are true (i.e. all of the above nonzero or false) execute all commands up to fi fi Formultilevelifthenelsestatementtrythefollowingscript: $ cat > elf # #!/bin/sh # Script to test if..elif...else # if [ $1 -gt 0 ]; then echo "$1 is positive" elif [ $1 -lt 0 ] then echo "$1 is negative" elif [ $1 -eq 0 ] then echo "$1 is zero" else echo "Opps! $1 is not number, give number" fi Tryabovescriptasfollows: $chmod755elf $./elf1 $./elf2 $./elf0 $./elfa Hereo/pforlastsamplerun: ./elf:[:gt:unaryoperatorexpected ./elf:[:lt:unaryoperatorexpected ./elf:[:eq:unaryoperatorexpected

Opps!aisnotnumber,givenumber Aboveprogramgiveserrorforlastrun,hereintegercomparisonisexpectedthereforeerrorlike"./elf:[:gt: unaryoperatorexpected"occurs,butstillourprogramnotifythiserrortouserbyprovidingmessage"Opps! aisnotnumber,givenumber".

LoopsinShellScripts
Loopdefinedas: "Computercanrepeatparticularinstructionagainandagain,untilparticularconditionsatisfies.Agroupof instructionthatisexecutedrepeatedlyiscalledaloop." Bashsupports: forloop whileloop Notethatineachandeveryloop, (a)First,thevariableusedinloopconditionmustbeinitialized,thenexecutionoftheloopbegins. (b)Atest(condition)ismadeatthebeginningofeachiteration. (c)Thebodyofloopendswithastatementthatmodifiesthevalueofthetest(condition)variable.

forLoop
Syntax: for { variable name } in { list } do execute one for each item in the list until the list is and done) done not finished (And repeat all statement between do

Beforetrytounderstandabovesyntaxtrythefollowingscript: $ cat > testfor for i in 1 2 3 4 5 do echo "Welcome $i times" done Runitabovescriptasfollows: $chmod+xtestfor $./testfor Theforloopfirstcreatesivariableandassignedanumbertoifromthelistofnumberfrom1to5,Theshell executeechostatementforeachassignmentofi.(Thisisusuallyknowasiteration)Thisprocesswill continueuntilalltheitemsinthelistwerenotfinished,becauseofthisitwillrepeat5echostatements.To makeyouideamorecleartryfollowingscript:

$ cat > mtable #!/bin/sh # #Script to test for loop # # if [ $# -eq 0 ] then echo "Error - Number missing form command line argument" echo "Syntax : $0 number" echo "Use to print multiplication table for given number" exit 1 fi n=$1 for i in 1 2 3 4 5 6 7 8 9 10 do echo "$n * $i = `expr $i \* $n`" done Saveabovescriptandrunitas: $chmod755mtable $./mtable7 $./mtable Forfirstrun,abovescriptprintmultiplicationtableofgivennumberwherei=1,2...10ismultiplybygiven n(herecommandlineargument7)inordertoproducemultiplicationtableas 7*1=7 7*2=14 ... .. 7*10=70 Andforsecondtestrun,itwillprintmessage ErrorNumbermissingformcommandlineargument Syntax:./mtablenumber Usetoprintmultiplicationtableforgivennumber Thishappenedbecausewehavenotsuppliedgivennumberforwhichwewantmultiplicationtable,Hence scriptisshowingErrormessage,Syntaxandusageofourscript.Thisisgoodideaifourprogramtakessome argument,lettheuserknowwhatisuseofthescriptandhowtousedthescript. Notethattoterminateourscriptweused'exit1'commandwhichtakes1asargument(1indicateserrorand thereforescriptisterminated) Evenyoucanusefollowingsyntax: Syntax: for (( expr1; expr2; expr3 )) do ..... ... repeat all statements between do and done until expr2 is TRUE Done

InabovesyntaxBEFOREthefirstiteration,expr1isevaluated.Thisisusuallyusedtoinitializevariablesfor theloop. AllthestatementsbetweendoanddoneisexecutedrepeatedlyUNTILthevalueofexpr2isTRUE. AFTEReachiterationoftheloop,expr3isevaluated.Thisisusuallyusetoincrementaloopcounter. $ cat > for2 for (( i = 0 ; i <= 5; i++ do echo "Welcome $i times" done Runtheabovescriptasfollows: $chmod+xfor2 $./for2 Welcome0times Welcome1times Welcome2times Welcome3times Welcome4times Welcome5times ))

Inaboveexample,firstexpression(i=0),isusedtosetthevaluevariableitozero. Secondexpressionisconditioni.e.allstatementsbetweendoanddoneexecutedaslongasexpression2(i.e continueaslongasthevalueofvariableiislessthanorequelto5)isTRUE. Lastexpressioni++incrementsthevalueofiby1i.e.it'sequivalenttoi=i+1statement.

NestingofforLoop
Asyouseetheifstatementcannested,similarlyloopstatementcanbenested.Youcannesttheforloop.To understandthenestingofforloopseethefollowingshellscript. for (( i = 1; i <= 5; i++ )) do ### Outer for loop ###

for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ### do echo -n "$i " done echo "" #### print the new line ### done Runtheabovescriptasfollows: $chmod+xnestedfor.sh $./nestefor.sh 11111 22222 33333

44444 55555 Here,foreachvalueofitheinnerloopiscycledthrough5times,withthevariblejtakingvaluesfrom1to 5.Theinnerforloopterminateswhenthevalueofjexceeds5,andtheouterloopterminetswhenthevalue ofiexceeds5. Followingscriptisquiteintresting,itprintsthechessboardonscreen. for (( i = 1; i <= 9; i++ )) ### Outer for loop ### do for (( j = 1 ; j <= 9; j++ )) ### Inner for loop ### do tot=`expr $i + $j` tmp=`expr $tot % 2` if [ $tmp -eq 0 ]; then echo -e -n "\033[47m " else echo -e -n "\033[40m " fi done echo -e -n "\033[40m" #### set back background colour to black echo "" #### print the new line ### done Runtheabovescriptasfollows: $chmod+xchessboard $./chessboard Onmyterminalabovescriptproduectheoutputasfollows:

Aboveshellscriptcabbeexplainedasfollows: Command(s)/Statements for((i=1;i<=9;i++)) do Explanation Begintheouterloopwhichruns9times.,andtheouterloop terminetswhenthevalueofiexceeds9 Beginstheinnerloop,foreachvalueofitheinnerloopis cycledthrough9times,withthevariblejtakingvaluesfrom1 to9.Theinnerforloopterminateswhenthevalueofjexceeds 9. Seeforevenandoddnumberpositionsusingthesestatements. Ifevennumberposiotionprintthewhitecolourblock(using echoen"\033[47m"statement);otherwiseforoddpostion printtheblackcolourbox(usingechoen"\033[40m" statement).Thisstatementsareresponsibletoprintentier chessboardonscreenwithalternetcolours. Endofinnerloop Makesureitsblackbackgroundaswealwayshaveonour terminals. Printtheblankline Endofouterloopandshellscriptsgettermintedbyprinting thechessboard.

for((j=1;j<=9;j++)) do

tot=`expr$i+$j` tmp=`expr$tot%2` if[$tmpeq0];then echoen"\033[47m" else echoen"\033[40m" fi done echoen"\033[40m" echo"" done

whileloop
Syntax: while [ condition ] do command1 command2 command3 .. .... done Loopisexecutedaslongasgivenconditionistrue.Fore.g..Aboveforloopprogram(showninlastsection offorloop)canbewrittenusingwhileloopas: $cat > nt1 #!/bin/sh # #Script to test while statement

# # if [ $# -eq 0 ] then echo "Error - Number missing form command line argument" echo "Syntax : $0 number" echo " Use to print multiplication table for given number" exit 1 fi n=$1 i=1 while [ $i -le 10 ] do echo "$n * $i = `expr $i \* $n`" i=`expr $i + 1` done Saveitandtryas $chmod755nt1 $./nt17 Aboveloopcanbeexplainedasfollows:
n=$1 i=1 while[$ile10] do Setthevalueofcommandlineargumenttovariable n.(Hereit'ssetto7) Setvariableito1 Thisisourloopcondition,hereifvalueofiisless than10then,shellexecuteallstatementsbetween doanddone Startloop Printmultiplicationtableas 7*1=7 7*2=14 .... 7*10=70,Hereeachtimevalueofvariablenis multiplybei. Incrementiby1andstoreresulttoi.(i.e.i=i+1) Caution:Ifyouignore(remove)thisstatement thanourloopbecomeinfiniteloopbecausevalue ofvariableialwaysremainlessthan10and programwillonlyoutput 7*1=7 ... ... E(infinitetimes) Loopstopshereifiisnotlessthan10i.e.condition ofloopisnottrue.Hence loopisterminated.

echo"$n*$i=`expr$i\*$n`"

i=`expr$i+1`

done

ThecaseStatement
ThecasestatementisgoodalternativetoMultilevelifthenelsefistatement.Itenableyoutomatchseveral valuesagainstonevariable.Itseasiertoreadandwrite. Syntax: case $variable-name in pattern1) command ... .. command;; pattern2) command ... .. command;; patternN) command ... .. command;; *) command ... .. command;;

esac The$variablenameiscomparedagainstthepatternsuntilamatchisfound.Theshellthenexecutesallthe statementsuptothetwosemicolonsthatarenexttoeachother.Thedefaultis*)anditsexecutedifnomatch isfound.Fore.g.writescriptasfollows: $ # # # # # cat > car if no vehicle name is given i.e. -z $1 is defined and it is NULL if no command line arg

if [ -z $1 ] then rental="*** Unknown vehicle ***" elif [ -n $1 ] then # otherwise make first arg as rental rental=$1 fi case $rental in "car") echo "For $rental Rs.20 per k/m";; "van") echo "For $rental Rs.10 per k/m";; "jeep") echo "For $rental Rs.5 per k/m";; "bicycle") echo "For $rental 20 paisa per k/m";; *) echo "Sorry, I can not gat a $rental for you";;

esac SaveitbypressingCTRL+Dandrunitasfollows: $chmod+xcar $carvan $carcar $carMaruti800 Firstscriptwillcheck,thatif$1(firstcommandlineargument)isgivenornot,ifNOTgivensetvalueof rentalvariableto"***Unknownvehicle***",ifcommandlineargissupplied/givensetvalueofrental variabletogivenvalue(commandlinearg).The$rentaliscomparedagainstthepatternsuntilamatchis found. Forfirsttestrunitsmatchwithvananditwillshowoutput"ForvanRs.10perk/m." Forsecondtestrunitprint,"ForcarRs.20perk/m". Andforlastrun,thereisnomatchforMaruti800,hencedefaulti.e.*)isexecutedanditprints,"Sorry,I cannotgataMaruti800foryou". Notethatesacisalwaysrequiredtoindicateendofcasestatement.

Howtodebugtheshellscript?
Whileprogrammingshellsometimesyouneedtofindtheerrors(bugs)inshellscriptandcorrecttheerrors (removeerrorsdebug).Forthispurposeyoucanusevandxoptionwithshorbashcommandtodebug theshellscript.Generalsyntaxisasfollows: Syntax: shoption{shellscriptname} OR bashoption{shellscriptname} Optioncanbe vPrintshellinputlinesastheyareread. xAfterexpandingeachsimplecommand,bashdisplaystheexpandedvalueofPS4systemvariable, followedbythecommandanditsexpandedarguments. Example: $cat>dsh1.sh # #Scripttoshowdebugofshell # tot=`expr$1+$2` echo$tot Pressctrl+dtosave,andrunitas $chmod755dsh1.sh $./dsh1.sh45 9 $shxdsh1.sh45 #

#Scripttoshowdebugofshell # tot=`expr$1+$2` expr$1+$2 ++expr4+5 +tot=9 echo$tot +echo9 9 Seetheaboveoutput,xshowstheexactvaluesofvariables(orstatementsareshownonscreenwithvalues). $shvdsh1.sh45 Usevoptiontodebugcomplexshellscript.

Chapter4:AdvancedShellScriptingCommands Introduction
Afterlearningbasisofshellscripting,itstimetolearnmoreadvancefeaturesofshellscripting/command suchas: Functions Userinterface Conditionalexecution FileDescriptors traps Multiplecommandlineargshandlingetc

/dev/nullUsetosendunwantedoutputof program
ThisisspecialLinuxfilewhichisusedtosendanyunwantedoutputfromprogram/command. Syntax: command>/dev/null Example: $ls>/dev/null Outputofabovecommandisnotshownonscreenitssendtothisspecialfile.The/devdirectorycontains otherdevicefiles.Thefilesinthisdirectorymostlyrepresentperipheraldevicessuchdiskslikefloppydisk, soundcard,lineprintersetc.SeethefilesystemtutorialformoreinformationonLinuxdisk,partitionand filesystem. FuturePoint: Runthefollowingtwocommands $ls>/dev/null $rm>/dev/null 1) Whytheoutputoflastcommandisnotredirectedto/dev/nulldevice?

LocalandGlobalShellvariable(exportcommand)
Normallyallourvariablesarelocal.Localvariablecanbeusedinsameshell,ifyouloadanothercopyof shell(bytypingthe/bin/bashatthe$prompt)thennewshellignoredalloldshell'svariable.Fore.g. Considerfollowingexample $vech=Bus $echo$vech Bus $/bin/bash $echo$vech NOTE:Emptylineprinted $vech=Car $echo$vech Car $exit $echo$vech Bus Command $vech=Bus $echo$vech $/bin/bash $echo$vech $vech=Car $echo$vech $exit $echo$vech Meaning Createnewlocalvariable'vech'withBusasvalueinfirstshell Printthecontainsofvariablevech Nowloadsecondshellinmemory(Whichignoresalloldshell'svariable) Printthecontainsofvariablevech Createnewlocalvariable'vech'withCarasvalueinsecondshell Printthecontainsofvariablevech Exitfromsecondshellreturntofirstshell Printthecontainsofvariablevech(Nowyoucanseefirstshellsvariableand itsvalue)

Globalshelldefinedas: "Youcancopyoldshell'svariabletonewshell(i.e.firstshellsvariabletosecondsshell),suchvariableis knowasGlobalShellvariable." Tosetglobalvaribleyouhavetouseexportcommand. Syntax: exportvariable1,variable2,.....variableN Examples: $vech=Bus $echo$vech Bus $exportvech

$/bin/bash $echo$vech Bus $exit $echo$vech Bus Command $vech=Bus $echo$vech Printthecontainsofvariablevech $exportvech Exportfirstshellsvariabletosecondshelli.e.globalvarible $/bin/bash Nowloadsecondshellinmemory(Oldshell'svariableisaccessedfromsecondshell,if theyareexported) Exitfromsecondshellreturntofirstshell Meaning Createnewlocalvariable'vech'withBusasvalueinfirstshell

$echo$vech Printthecontainsofvariablevech $exit $echo$vech Printthecontainsofvariablevech

Conditionalexecutioni.e.&&and||
Thecontroloperatorsare&&(readasAND)and||(readasOR).ThesyntaxforANDlistisasfollows Syntax: command1&&command2 command2isexecutedif,andonlyif,command1returnsanexitstatusofzero. ThesyntaxforORlistasfollows Syntax: command1||command2 command2isexecutedifandonlyifcommand1returnsanonzeroexitstatus. Youcanusebothasfollows Syntax: command1&&comamnd2ifexiststatusiszero||command3ifexitstatusisnonzero ifcommand1isexecutedsuccessfullythenshellwillruncommand2andifcommand1isnotsuccessfulthen command3isexecuted. Example: $rmmyf&&echo"Fileisremovedsuccessfully"||echo"Fileisnotremoved" Iffile(myf)isremovedsuccessful(existstatusiszero)then"echoFileisremovedsuccessfully"statementis executed,otherwise"echoFileisnotremoved"statementisexecuted(sinceexiststatusisnonzero)

I/ORedirectionandfiledescriptors
AsyouknowI/Oredirectorsareusedtosendoutputofcommandtofileortoreadinputfromfile.Consider followingexample $cat>myf Thisismyfile ^D(pressCTRL+Dtosavefile) Abovecommandsendoutputofcatcommandtomyffile $cal Abovecommandprintscalendaronscreen,butifyouwishtostorethiscalendartofilethengivecommand $cal>mycal Thecalcommandsendoutputtomycalfile.Thisiscalledoutputredirection. $sort 10 20 11 2 ^D 20 2 10 11 sortcommandtakesinputfromkeyboardandthensortsthenumberandprints(send)outputtoscreenitself. Ifyouwishtotakeinputfromfile(forsortcommand)givecommandasfollows: $cat>nos 10 20 11 2 ^D $sort<nos 20 2 10 11 Firstyoucreatedthefilenosusingcatcommand,thennosfilegivenasinputtosortcommandwhichprints sortednumbers.Thisiscalledinputredirection. InLinux(AndinCprogrammingLanguage)yourkeyboard,screenetcarealltreatedasfiles.Followingare nameofsuchfiles

StandardFile FileDescriptorsnumber stdin stdout stderr 0 1 2

Use asStandard output

Example

asStandardinput Keyboard Screen

asStandarderror Screen

BydefaultinLinuxeveryprogramhasthreefilesassociatedwithit,(whenwestartourprogramthesethree filesareautomaticallyopenedbyyourshell).Theuseoffirsttwofiles(i.e.stdinandstdout),arealready seenbyus.Thelastfilestderr(numberedas2)isusedbyourprogramtoprinterroronscreen.Youcan redirecttheoutputfromafiledescriptordirectlytofilewithfollowingsyntax Syntax: filedescriptornumber>filename Examples:(Assemumsthefilebad_file_name111doesnotexists) $rmbad_file_name111 rm:cannotremove`bad_file_name111':Nosuchfileordirectory Abovecommandgiveserrorasoutput,sinceyoudon'thavefile.Nowifwetrytoredirectthiserroroutputto file,itcannotbesend(redirect)tofile,tryasfollows: $rmbad_file_name111>er Stillitprintsoutputonstderrasrm:cannotremove`bad_file_name111':Nosuchfileordirectory,Andif youseeerfileas$cater,thisfileisempty,sinceoutputissendtoerrordeviceandyoucannotredirectit tocopythiserroroutputtoyourfile'er'.Toovercomethisproblemyouhavetousefollowingcommand: $rmbad_file_name1112>er Notethatnospaceareallowedbetween2and>,The2>erdirectsthestandarderroroutputtofile.2number isdefaultnumber(filedescriptorsnumber)ofstderrfile.Toclearyourideaonsideranotherexampleby writingshellscriptasfollows: $ cat > demoscr if [ $# -ne 2 ] then echo "Error : Number are not supplied" echo "Usage : $0 number1 number2" exit 1 fi ans=`expr $1 + $2` echo "Sum is $ans" Runitasfollows: $chmod755demoscr $./demoscr Error:Numberarenotsupplied Usage:./demoscrnumber1number2 $./demoscr>er1 $./demoscr57 Sumis12 Forfirstsamplerun,ourscriptprintserrormessageindicatingthatyouhavenotgiventwonumber. Forsecondsamplerun,youhaveredirectoutputofscripttofileer1,sinceit'serrorwehavetoshowitto

user,Itmeanswehavetoprintourerrormessageonstderrnotonstdout.Toovercomethisproblemreplace aboveechostatementsasfollows echo"Error:Numberarenotsupplied"1>&2 echo"Usage:$0number1number2"1>&2 Nowifyourunitasfollows: $./demoscr>er1 Error:Numberarenotsupplied Usage:./demoscrnumber1number2 Itwillprinterrormessageonstderrandnotonstdout.The1>&2attheendofechostatement,directsthe standardoutput(stdout)tostandarderror(stderr)device. Syntax: from>&destination

Functions
Humansareintelligentanimals.Theyworktogethertoperformalloflife'stask,infactmostofusdepend uponeachother.Fore.g.yourelyonmilkmantosupplymilk,orteachertolearnnewtechnology(if computerteacher).Whatallthismeanisyoucan'tperformalloflife'staskalone.Youneedsomebodyto helpyoutosolvespecifictask/problem. Theabovelogicalsoappliestocomputerprogram(shellscript).Whenprogramgetscomplexweneedtouse divideandconquertechnique.Itmeanswheneverprogramsgetscomplicated,wedivideitintosmall chunks/entitieswhichisknowasfunction. Functionisseriesofinstruction/commands.Functionperformsparticularactivityinshelli.e.ithadspecific worktodoorsimplysaytask.Todefinefunctionusefollowingsyntax: Syntax: function-name ( ) { command1 command2 ..... ... commandN return } Wherefunctionnameisnameofyoufunction,thatexecutesseriesofcommands.Areturnstatementwill terminatethefunction.Example: TypeSayHello()at$promptasfollows $SayHello() { echo"Hello$LOGNAME,Havenicecomputing" return }

ToexecutethisSayHello()functionjusttypeitnameasfollows: $SayHello Hellovivek,Havenicecomputing.

Whytowritefunction?
Saveslotoftime. Avoidsrewritingofsamecodeagainandagain Programiseasiertowrite. Programmaintainsisveryeasy.

UserInterfaceanddialogutilityPartI
Goodprogram/shellscriptmustinteractwithusers.Youcanaccomplishthisasfollows: (1)Usecommandlinearguments(args)toscriptwhenyouwantinteractioni.e.passcommandlineargsto scriptas:$./sutil.shfoo4,wherefoo&4arecommandlineargspassedtoshellscriptsutil.sh. (2)Usestatementlikeechoandreadtoreadinputintovariablefromtheprompt.Fore.g.Writescriptas: $ cat > userinte # # Script to demo echo and read command for user interaction # echo "Your good name please :" read na echo "Your age please :" read age neyr=`expr $age + 1` echo "Hello $na, next year you will be $neyr yrs old." Saveitandrunas $chmod755userinte $./userinte Yourgoodnameplease: Vivek Yourageplease: 25 HelloVivek,nextyearyouwillbe26yrsold. Evenyoucancreatemenustointeractwithuser,firstshowmenuoption,thenaskusertochoosemenuitem, andtakeappropriateactionaccordingtoselectedmenuitem,thistechniqueisshowinfollowingscript: $ cat > menuui # # Script to create simple menus and take action according to that selected # menu item # while : do clear

echo echo echo echo echo echo echo echo echo echo read case 1) 2) read ;; 3) 4) 5) *)

"-------------------------------------" " Main Menu " "-------------------------------------" "[1] Show Todays date/time" "[2] Show files in current directory" "[3] Show calendar" "[4] Start editor to write letters" "[5] Exit/Stop" "=======================" -n "Enter your menu choice [1-5]: " yourch $yourch in echo "Today is `date` , press a key. . ." ; read ;; echo "Files in `pwd`" ; ls -l ; echo "Press a key. . ." ; cal ; echo "Press a key. . ." ; read ;; gedit ;; exit 0 ;; echo "Opps!!! Please select choice 1,2,3,4, or 5"; echo "Press a key. . ." ; read ;;

esac done Aboveallstatementexplainedinfollowingtable: Statement while: do clear echo"" echo"MainMenu" echo"" echo"[1]ShowTodaysdate/time" echo"[2]Showfilesincurrentdirectory" echo"[3]Showcalendar" echo"[4]Starteditortowriteletters" echo"[5]Exit/Stop" echo"=======================" echon"Enteryourmenuchoice[15]:"

Explanation Startinfiniteloop,thisloop willonlybreakifyouselect5 (i.e.Exit/Stopmenuitem)as yourmenuchoice Startloop Clearthescreen,eachand everytime

Showmenuonscreenwith menuitems

Askusertoentermenuitem number

Statement readyourch case$yourchin 1)echo"Todayis`date`,pressakey...";read;; 2)echo"Filesin`pwd`";lsl; echo"Pressakey...";read;; 3)cal;echo"Pressakey...";read;; 4)gedit;; 5)exit0;; *)echo"Opps!!!Pleaseselectchoice1,2,3,4,or5"; echo"Pressakey...";read;; esac done

Explanation Readmenuitemnumberfrom user

Takeappropriateaction accordingtoselectedmenu item,Ifmenuitemisnot between15,thenshowerror andaskusertoinputnumber between15again

Stoploop,ifmenuitem numberis5(i.e.Exit/Stop)

Userinterfaceusuallyincludes,menus,differenttypeofboxeslikeinfobox,messagebox,Inputboxetc.In Linuxshell(i.e.bash)thereisnobuiltinfacilityavailabletocreatesuchuserinterface,Butthereisone utilitysuppliedwithRedHatLinuxversion6.0calleddialog,whichisusedtocreatedifferenttypeofboxes likeinfobox,messagebox,menubox,Inputboxetc.Nextsectionshowsyouhowtousedialogutility.

UserInterfaceanddialogutilityPartII
Beforeprogrammingusingdialogutilityyouneedtoinstallthedialogutility,sincedialogutilityinnot installedbydefault. ForRedHatLinux6.2userinstallthedialogutilityasfollows(FirstinsertRedHatLinux6.2CDinto CDROMdrive) #mount/mnt/cdrom #cd/mnt/cdrom/RedHat/RPMS #rpmivhdialog0.616.i386.rpm ForRedHatLinux7.2userinstallthedialogutilityasfollows(FirstinsertRedHatLinux7.2#1CDinto CDROMdrive) #mount/mnt/cdrom #cd/mnt/cdrom/RedHat/RPMS #rpmivhdialog0.9a5.i386.rpm Afterinstallationyoucanstarttousedialogutility.Beforeunderstandingthesyntaxofdialogutilitytrythe followingscript: $ cat > dia1 dialog --title "Linux Dialog Utility Infobox" --backtitle "Linux Shell Script\ Tutorial" --infobox "This is dialog box called infobox, which is used \

to show some information on screen, Thanks to Savio Lam and\ Stuart Herbert to give us this utility. Press any key. . . " 7 50 ; read Savetheshellscriptandrunitas: $chmod+xdia1 $./dia1

Afterexecutingthisdialogstatementyouwillseeboxonscreenwithtitledas"WelcometoLinuxDialog Utility"andmessage"Thisisdialog....Pressanykey..."insidethisbox.Thetitleofboxisspecifiedby titleoptionandinfoboxwithinfobox"Message"withthisoption.Here7and50areheightofboxand widthofboxrespectively."LinuxShellScriptTutorial"isthebacktitleofdialogshowonupperleftsideof screenandbelowthatlineisdrawn.UsedialogutilitytoDisplaydialogboxesfromshellscripts. Syntax:


dialog --title {title} --backtitle {backtitle} {Box options} where Box options can be any one of following --yesno {text} {height} {width} --msgbox {text} {height} {width} --infobox {text} {height} {width} --inputbox {text} {height} {width} [{init}] --textbox {file} {height} {width} --menu {text} {height} {width} {menu} {height} {tag1} item1}...

Messagebox(msgbox)usingdialogutility
$cat > dia2 dialog --title "Linux Dialog Utility Msgbox" --backtitle "Linux Shell Script\ Tutorial" --msgbox "This is dialog box called msgbox, which is used\ to show some information on screen which has also Ok button, Thanks to Savio Lam\ and Stuart Herbert to give us this utility. Press any key. . . " 9 50 Saveitandrunas $chmod+xdia2 $./dia2

yesnoboxusingdialogutility
$cat>dia3 dialogtitle"Alert:DeleteFile"backtitle"LinuxShellScript\ Tutorial"yesno"\nDoyouwanttodelete'/usr/letters/jobapplication'\ file"760 sel=$? case$selin 0)echo"Userselecttodeletefile";; 1)echo"Userselectnottodeletefile";; 255)echo"Canceledbyuserbypressing[ESC]key";; esac Savethescriptandrunitas:

$chmod+xdia3 $./dia3

Abovescriptcreatesyesnotypedialogbox,whichisusedtoasksomequestionstotheuser,andanswerto thosequestioneitheryesorno.Afteraskingquestionhowdoweknow,whetheruserhaspressyesorno button?Theanswerisexitstatus,ifuserpressyesbuttonexitstatuswillbezero,ifuserpressnobuttonexit statuswillbeoneandifuserpressEscapekeytocanceldialogboxexitstatuswillbeone255.Thatiswhat wehavetestedinouraboveshellscriptas Statement sel=$? case$selin 0)echo"Youselecttodeletefile";; 1)echo"Youselectnottodeletefile";; 255)echo"Canceledbyyoubypressing[Escape]key";; esac Meaning Getexitstatusofdialogutility Nowtakeactionaccordingtoexitstatusof dialogutility,ifexitstatusis0,deletefile, ifexitstatusis1donotdeletefileandif exitstatusis255,meansEscapekeyis pressed.

InputBox(inputbox)usingdialogutility
$ cat > dia4 dialog --title "Inputbox - To take input from you" --backtitle "Linux Shell\ Script Tutorial" --inputbox "Enter your name please" 8 60 2>/tmp/input.$ $ sel=$?

na=`cat /tmp/input.$$` case $sel in 0) echo "Hello $na" ;; 1) echo "Cancel is Press" ;; 255) echo "[ESCAPE] key pressed" ;; esac rm -f /tmp/input.$$ Runitasfollows: $chmod+xdia4 $./dia4

Inputboxisusedtotakeinputfromuser,InthisexamplewearetakingNameofuserasinput.Butwherewe aregoingtostoreinputtedname,theansweristoredirectinputtednametofileviastatement2>/tmp/input.$ $attheendofdialogcommand,whichmeanssendscreenoutputtofilecalled/tmp/input.$$,letterwecan retrievethisinputtednameandstoretovariableasfollows na=`cat/tmp/input.$$`. Forinputbox'sexitstatusreferthefollowingtable: ExitStatusforInput box 0 1 255 Meaning Commandissuccessful Cancelbuttonispressedbyuser Escapekeyispressedbyuser

UserInterfaceusingdialogUtilityPuttingitall together
Itstimetowritescripttocreatemenususingdialogutility,followingaremenuitems Date/time Calendar Editor andactionforeachmenuitemisfollows: MENUITEM Date/time Calendar Editor ACTION Showcurrent date/time Showcalendar StartgeditEditor

$ cat > smenu # #How to create small menu using dialog # dialog --backtitle "Linux Shell Script Tutorial " --title "Main\ Menu" --menu "Move using [UP] [DOWN],[Enter] to\ Select" 15 50 3\ Date/time "Shows Date and Time"\ Calendar "To see calendar "\ Editor "To start vi editor " 2>/tmp/menuitem.$$ menuitem=`cat /tmp/menuitem.$$` opt=$? case $menuitem in Date/time) date;; Calendar) cal;; Editor) gedit;; esac Saveitandrunas: $rmf/tmp/menuitem.$$ $chmod+xsmenu $./smenu

menuoptionisusedofdialogutilitytocreatemenus,menuoptiontake menuoptions "Moveusing[UP][DOWN],[Enter]to Select" 15 50 3 Date/time"ShowsDateandTime" Meaning Thisistextshowbeforemenu Heightofbox Widthofbox Heightofmenu Firstmenuitemcalledastag1(i.e.Date/time)and descriptionformenuitemcalledasitem1(i.e."Shows DateandTime") Firstmenuitemcalledastag2(i.e.Calendar)and descriptionformenuitemcalledasitem2(i.e."Tosee calendar") Firstmenuitemcalledastag3(i.e.Editor)anddescription formenuitemcalledasitem3(i.e."Tostartgediteditor") Sendselectedmenuitem(tag)tothistemporaryfile

Calendar"Toseecalendar" Editor"Tostartgediteditor" 2>/tmp/menuitem.$$

Aftercreatingmenus,userselectsmenuitembypressingtheENTERkey,selectedchoiceisredirectedto temporaryfile,Nextthismenuitemisretrievedfromtemporaryfileandfollowingcasestatementcompare themenuitemandtakesappropriatestepaccordingtoselectedmenuitem.Asyousee,dialogutilityallows morepowerfuluserinteractionthentheolderreadandechostatement.Theonlyproblemwithdialogutility isitworkslowly.

Theseexercisesaretotestyourgeneralunderstandingoftheshellscripting.Myadviseisfirsttrytowrite thisshellscriptyourselfsothatyouunderstandhowtoputtheconceptstoworkinreallifescripts.For sampleanswertoexerciseyoucanrefertheshellscriptfilesuppliedwiththistutorial.Ifyouwanttobecome thegoodprogrammerthenyourfirsthabitmustbetoseethegoodcode/samplesofprogramminglanguage thenpracticelotandfinallyimplementtheyourowncode(andbecomethegoodprogrammer!!!). Q.1.Howtowriteshellscriptthatwilladdtwonos,whicharesuppliedascommandlineargument,andif thistwonosarenotgivenshowerroranditsusage Q.2.WriteScripttofindoutbiggestnumberfromgiventhreenos.Nosaresuppliesascommandline argument.Printerrorifsufficientargumentsarenotsupplied. Q.3.Writescripttoprintnosas5,4,3,2,1usingwhileloop. Q.4.WriteScript,usingcasestatementtoperformbasicmathoperationas follows +addition subtraction xmultiplication /division Thenameofscriptmustbe'q4'whichworksasfollows $./q420/3,Alsocheckforsufficientcommandlinearguments Q.5.WriteScripttoseecurrentdate,time,username,andcurrentdirectory Q.6.Writescripttoprintgivennumberinreverseorder,foreg.Ifnois123itmustprintas321. Q.7.Writescripttoprintgivennumberssumofalldigit,Foreg.Ifnois123it'ssumofalldigitwillbe 1+2+3=6. Q.8.Howtoperformrealnumber(numberwithdecimalpoint)calculationinLinux(TIP:manbc) Q.9.Howtocalculate5.12+2.5realnumbercalculationat$promptinShell? Q.10.Howtoperformrealnumbercalculationinshellscriptandstoreresultto thirdvariable,letssaya=5.66,b=8.67,c=a+b? Q.11.Writescripttodeterminewhethergivenfileexistornot,filenameissuppliedascommandline argument,alsocheckforsufficientnumberofcommandlineargument Q.12.Writescripttodeterminewhethergivencommandlineargument($1)contains"*"symbolornot,if$1 doesnotcontains"*"symboladditto$1,otherwiseshowmessage"Symbolisnotrequired".Fore.g.Ifwe calledthisscriptQ12thenaftergiving, $Q12/bin Here$1is/bin,itshouldcheckwhether"*"symbolispresentornotifnotitshouldprintRequiredi.e. /bin/*,andifsymbolpresentthenSymbolisnotrequiredmustbeprinted.Testyourscriptas $Q12/bin $Q12/bin/* Q.13.Writescripttoprintcontainsoffilefromgivenlinenumbertonextgivennumberoflines.Fore.g.If wecalledthisscriptasQ13andrunas $Q1355myf,Hereprintcontainsof'myf'filefromlinenumber5tonext5lineofthatfile. Q.14.Writescripttoimplementgetoptsstatement,yourscriptshouldunderstandfollowingcommandline argumentcalledthisscriptQ14,

Q14cdme Whereoptionsworkas cclearthescreen dshowlistoffilesincurrentworkingdirectory mstartmc(midnightcommandershell),ifinstalled e{editor}startthis{editor}ifinstalled Q.15.WritescriptcalledsayHello,putthisscriptintoyourstartupfilecalled.bash_profile,thescriptshould runassoonasyoulogontosystem,anditprintanyoneofthefollowingmessageininfoboxusingdialog utility,ifinstalledinyoursystem,Ifdialogutilityisnotinstalledthenuseechostatementtoprintmessage: GoodMorning GoodAfternoon GoodEvening,accordingtosystemtime. Q.16.Howtowritescript,thatwillprint,Message"HelloWorld",inBoldandBlinkeffect,andindifferent colorslikered,brownetcusingechocommand. Q.17.Writescripttoimplementbackgroundprocessthatwillcontinuallyprintcurrenttimeinupperright cornerofthescreen,whileusercandohis/hernormaljobat$prompt. Q.18.Writeshellscripttoimplementmenususingdialogutility.Menuitemsandactionaccordingtoselect menuitemisasfollows: MenuItem Date/time Calendar Purpose Toseecurrentdatetime Toseecurrentcalendar ActionforMenuItem Dateandtimemustbeshownusinginfoboxofdialogutility Calendarmustbeshownusinginfoboxofdialogutility Firstaskusernameofdirectorywhereallfilesarepresent,if nonameofdirectorygivenassumescurrentdirectory,then showallfilesonlyofthatdirectory,Filesmustbeshownon screenusingmenusofdialogutility,lettheuserselectthefile, thenasktheconfirmationtouserwhetherhe/shewantsto deleteselectedfile,ifanswerisyesthendeletethefile,report errorsifanywhiledeletingfiletouser. Exit/Stopsthemenudrivenprogrami.e.thisscript

Delete

Todeleteselectedfile

Exit

ToExitthisshellscript

Note:Createfunctionforallactionfore.g.Toshowdate/timeonscreencreatefunctionshow_datetime(). Q.19.Writeshellscripttoshowvarioussystemconfigurationlike 1)Currentlyloggeduserandhislogname 2)Yourcurrentshell 3)Yourhomedirectory 4)Youroperatingsystemtype 5)Yourcurrentpathsetting 6)Yourcurrentworkingdirectory 7)ShowCurrentlyloggednumberofusers 8)Aboutyourosandversion,releasenumber,kernelversion 9)Showallavailableshells 10)Showmousesettings 11)Showcomputercpuinformationlikeprocessortype,speedetc

12)Showmemoryinformation 13)Showharddiskinformationlikesizeofharddisk,cachememory,modeletc 14)Filesystem(Mounted) Q.20.Writeshellscriptusingforlooptoprintthefollowingpatternsonscreen for2 for3 for4

for5

for6

for7

for8

for8

for9

Q.21.WriteshellscripttoconvertfilenamesfromUPPERCASEtolowercasefilenamesorviceversa.