0% found this document useful (0 votes)
54 views54 pages

Introduction to Linux Shell Programming

This document provides an introduction to shell programming in Linux. It discusses what a shell is, common shells like bash, csh and ksh. It explains that a shell script is a text file containing shell commands that can automate tasks. The document then demonstrates how to write a basic "Hello World" shell script and explains some basic shell scripting concepts like variables, printing variables, and rules for naming variables.

Uploaded by

italoyure
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views54 pages

Introduction to Linux Shell Programming

This document provides an introduction to shell programming in Linux. It discusses what a shell is, common shells like bash, csh and ksh. It explains that a shell script is a text file containing shell commands that can automate tasks. The document then demonstrates how to write a basic "Hello World" shell script and explains some basic shell scripting concepts like variables, printing variables, and rules for naming variables.

Uploaded by

italoyure
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Source:[Link]

html

Chapter1:IntroductiontoShellprogramming WhatisLinuxShell?
Computerunderstandthelanguageof0'sand1'scalledbinarylanguage. Inearlydaysofcomputing,instructionareprovidedusingbinarylanguage,whichisdifficultforallofus,to [Link] English(mostly)andifitsavalidcommand,itispasstokernel. Shellisauserprogramorit'[Link] interpreterthatexecutescommandsreadfromthestandardinputdevice(keyboard)orfromafile. Shellisnotpartofsystemkernel,butusesthesystemkerneltoexecuteprograms,createfilesetc. SeveralshellavailablewithLinuxincluding:
ShellName Developedby Where FreeSoftwareFoundation Remark Mostcommonshellin [Link]'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,[Link],butit'snotaspowerful asourLinuxShellsare! Anyoftheaboveshellreadscommandfromuser(viaKeyboardorMouse)andtellsLinuxOswhatusers [Link](Usuallyinfrontof$ prompt,ThispromptisdependuponyourshellandEnvironmentthatyousetorbyyourSystem Administrator,thereforeyoumaygetdifferentprompt). Tip:Tofindyourcurrentshelltypefollowingcommand $echo$SHELL

WhatisShellScript?
[Link](viakeyboard)andexecutethem. Butifyouusecommandonebyone(sequenceof'n'numberofcommands),theyoucanstorethissequence [Link] knowasshellscript. Shellscriptdefinedas: "[Link] havemorepowerthantheMSDOSbatchfile."

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

WhichShellWeareusingtowriteShellScript?
Inthistutorialweareusingbashshell.

ObjectiveofthisTutorial(LSSTv.1.5)
TrytounderstandLinuxOs TrytounderstandthebasicsofLinuxshell TrytolearntheLinuxshellprogramming

GettingstartedwithShellProgramming
Inthispartoftutorialyouareintroducetoshellprogramming,howtowritescript,[Link] gettingstartedwithwritingsmallshellscript,thatwillprint"KnowledgeisPower"onscreen.

Howtowriteshellscript
Followingstepsarerequiredtowriteshellscript: (1)[Link]. (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 [Link] aboutscript,logicalexplanationaboutshell script. Syntax: #commenttext clearthescreen Toprintmessageorvalueofvariableson screen,weuseechocommand,generalform ofechocommandisasfollows syntax: echo"Message"

# #Myfirstshellscript #

clear

echo"KnowledgeisPower"

Tip:[Link],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,[Link] intosmalllocations,andeachlocationhaduniquenumbercalledmemorylocation/address,whichisusedto [Link]/addresscalledmemoryvariable orvariable(Itsanamedstoragelocationthatmaytakedifferentvalues,butonlyoneatatime). InLinux(Shell),therearetwotypesofvariable: (1)[Link] LETTERS. (2)Userdefinedvariables(UDV)[Link]

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 [Link] Ourhomedirectory [Link] studentsOurloggingname OurOstype Ourpathsettings Ourpromptsettings Ourcurrentworkingdirectory Ourshellname UsernamewhoiscurrentlylogintothisPC Meaning

NOTEthatSomeoftheabovesettingscanbedifferentinyourPC/[Link] 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 [Link] HOME SYSTEM_VERSION vech no (2)Don'[Link] variabledeclarationtherewillbenoerror $ no=10 Buttherewillbeproblemforanyofthefollowingvariabledeclaration: $ no =10 $ no= 10 $ no = 10 (3)Variablesarecasesensitive,[Link].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 [Link]. (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. [Link] [Link],let'ssay6and3? [Link]=20,y=5andthentoprintdivisionofxandy(i.e.x/y) [Link] [Link] # # # 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.')[Link] generallyfoundonthekeyundertilde(~)onPCkeyboardORtotheaboveofTABkey. (2)Second,exprisalsoendwith`[Link]. (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$? [Link] $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,[Link] 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 [Link] 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/[Link] /bin/bash /bin/chgrp/bin/consolechars/bin/csh But $ls/bin/[!ao] $ls/bin/[^ao] Ifthefirstcharacterfollowingthe[isa!ora^,[Link] 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'[Link]'tuse $datewho forsamepurpose,youmustputsemicoloninbetweendateandwhocommand.

CommandLineProcessing
Trythefollowingcommand(assumesthatthefile"grate_stories_of"isnotexistonyoursystem) $lsgrate_stories_of Itwillprintmessagesomethinglikegrate_stories_of:Nosuchfileordirectory. lsisthenameofanactualcommandandshellexecutedthiscommandwhenyoutypecommandatshell [Link]?Whathappenedwhenyoutype$ls grate_stories_of?

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

WhyCommandLineargumentsrequired
1. Tellingthecommand/utilitywhichoptiontouse. 2. Informingtheutility/commandwhichfileorgroupoffilestoprocess(reading/writingoffiles). Let'stakermcommand,whichisusedtoremovefile,butwhichfileyouwanttoremoveandhowyouwill tailthistormcommand(evenrmcommanddon'taskyounameoffilethatyouwouldliketoremove).So whatwedoiswewritecommandasfollows: $rm{filename} [Link] [Link] specifyingfilenameAlsoyoucanpasscommandlineargumentstoyourscripttomakeitmoreusers [Link]. Letstakelscommand $Lsa/* Thiscommandhas2commandlineargumentaand/*[Link], $myshellfoobar

[Link] [Link] [Link]

Inshellifwewishtoreferthiscommandlineargumentwereferaboveasfollows myshellitis$0 fooitis$1 baritis$2 Here$#(builtinshellvariable)willbe2(SincefooandbaronlytwoArguments),Pleasenoteatatime such9argumentscanbeusedfrom$1..$9,Youcanalsoreferallofthembyusing$*(whichexpandto `$1,$2...$9`).Notethat$1..$[Link]"positionalparameters". Exercise Trytowritefollowingforcommands ShellScriptName($0), [Link](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'[Link] followingallstatementsinshellscriptareinvalid: $1=5 $2="MyName"

RedirectionofStandardoutput/[Link] Outputredirection
Mostlyallcommandgivesoutputonscreenortakeinputfromkeyboard,butinLinux(andinotherOSs also)it'spossibletosendoutputtofileortoreadinputfromfile. Fore.g. $lscommandgivesoutputtoscreen;tosendoutputtofileoflscommandgivecommand $ls>filename Itmeansputoutputoflscommandtofilename. Therearethreemainredirectionsymbols>,>>,< (1)>RedirectorSymbol Syntax: Linuxcommand>filename TooutputLinuxcommandsresult(outputofcommandorshellscript)[Link], [Link] $ls>myfiles Nowif'myfiles'fileexistinyourcurrentdirectoryitwillbeoverwrittenwithoutanytypeofwarning. (2)>>RedirectorSymbol Syntax: Linuxcommand>>filename TooutputLinuxcommandsresult(outputofcommandorshellscript)[Link], itwillbeopenedandnewinformation/datawillbewrittentoENDoffile,withoutlosingprevious information/data,Andiffileisnotexist,[Link] alreadyexistfilegivecommand $date>>myfiles (3)<RedirectorSymbol Syntax: Linuxcommand<filename [Link] $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([Link])isredirectedtosorted_namesfile. Tryonemoreexampletoclearyouridea: $tr"[az]""[AZ]"<sname>cap_names $catcap_names VIVEK ASHISH ZEBRA BABU [Link], andtr'soutputisredirectedtocap_namesfile. FuturePoint:Tryfollowingcommandandfindoutmostimportantpoint: $sort>new_sorted_names<sname $catnew_sorted_names

Pipes
Apipeisawaytoconnecttheoutputofoneprogramtotheinputofanotherprogramwithoutanytemporary file.

PipeDefinedas: "Apipeisnothingbutatemporarystorageplacewheretheoutputofonecommandisstoredandthen [Link](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 [Link].g..Supposeyou havefilecalled'[Link]'with100linesdata,Andfrom'[Link]'youwouldliketoprintcontainsfromline number20tolinenumber30andstorethisresulttofilecalled'hlist'thengivecommand: $tail+20<[Link]|headn30>hlist Hereheadcommandisfilterwhichtakesitsinputfromtailcommand(tailcommandstartselectingfrom [Link])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. [Link].g.ouroriginalfilecontains12333twice,so [Link],youwillnoticethat12333isgone (Duplicate),and"whatstillIremeberthatname"[Link] adjacentlines,[Link] commandasfollows $sortpersoname|uniq GeneralSyntaxofuniqutility: Syntax: uniq{filename}

WhatisProcesses
[Link].g. $lslR lscommandorarequesttolistfilesinadirectoryandallsubdirectoryinyourcurrentdirectoryItisa process. Processdefinedas: "Aprocessisprogram(commandgivenbyuser)[Link],it givesanumbertoprocess(calledPIDorprocessid),PIDstartsfrom0to65535."

WhyProcessrequired
AsYouknowLinuxismultiuser,[Link] [Link] commandlike: $ls/R|wcl [Link] 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 [Link] whetherApachewebserver processisrunningornotthen givecommand $psax|grephttpd Examples*

[Link] kill{PID} process [Link] process Togetinformationaboutallrunning process Tostopallprocessexceptyourshell Forbackgroundprocessing(With&, usetoputparticularcommandand programinbackground) killall{Processname} psag kill0 linuxcommand&

Todisplaytheowneroftheprocesses psaux alongwiththeprocesses Toseeifaparticularprocessisrunning [Link]|grepprocessUwanttosee pscommandincombinationwiththe grepcommand

Toseecurrentlyrunningprocessesand top otherinformationlikememoryand Seetheoutputoftopcommand. CPUusagewithrealtimeupdates. Todisplayatreeofprocesses pstree

$top
Notethattoexitfromtopcommand pressq.

$pstree

*Torunsomeofthiscommandyouneedtoberootorequivalntuser. NOTEthatyoucanonlykillprocesswhicharecreatedbyyourself.AAdministratorcanalmostkill9598% [Link],suchasVDUProcess.

Chapter2:Shells(bash)structuredLanguage Constructs Introduction


[Link] [Link] constrictssuchas: Decisionmaking Loops IsthereanydifferencemakingdecisioninReallifeandwithComputers?Wellreallifedecisionarequit complicatedtoallofusandcomputersevendon'thavethatmuchpowertounderstandourreallifedecisions. Whatcomputerknowis0(zero)[Link],letsplaysomegame (WOW!)withbcLinuxcalculatorprogram. $bc Afterthiscommandbcisstartedandwaitingforyourcommands,[Link] 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'[Link] 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)[Link],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"[Link] 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)[Link](0)then testwillreturn0andoutputwillprintedas5numberispositivebutfor45argumentthereisnooutput becauseourconditionisnottrue(0)(no45isnotgreaterthan0)[Link] laststatementwehavenotsuppliedanyargumenthenceerror./ispostive:test:gt:unaryoperatorexpected, isgeneratedbyshell,toavoidsucherrorwecantestwhethercommandlineargumentissuppliedornot. testor[expr]workswith [Link](Numberwithoutdecimalpoint) [Link] [Link]

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

[Link]: #!/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 [Link].e. echo"$0:Youmustgive/supplyoneintegers" || || 12 1willprintNameofscript 2willprintthiserrormessage Andfinallystatementexit1causesnormalprogramterminationwithexitstatus1(nonzeromeansscriptis notsuccessfullyrun). Thelastsamplerun$isnump_n0,givesoutputas"0numberisnegative",becausegivenargumentisnot> 0,henceconditionisfalseandit'[Link] test$1ge0.

Nestedifelsefi
Youcanwritetheentireifelseconstructwithineitherthebodyoftheifstatementofthebodyofanelse [Link]. 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+[Link] $./[Link] [Link](SunOs) [Link](RedHat) Selectyouoschoice[1or2]?1 YouPickupUnix(SunOs) $./[Link] [Link](SunOs) [Link](RedHat) Selectyouoschoice[1or2]?2 YouPickupLinux(RedHat) $./[Link] [Link](SunOs) [Link](RedHat) Selectyouoschoice[1or2]?3 Whatyoudon'tlikeUnix/LinuxOS. [Link] [Link] 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,[Link] 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,[Link] 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,[Link] 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,[Link] theloop. AllthestatementsbetweendoanddoneisexecutedrepeatedlyUNTILthevalueofexpr2isTRUE. AFTEReachiterationoftheloop,[Link]. $ 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++[Link]'sequivalenttoi=i+1statement.

NestingofforLoop
Asyouseetheifstatementcannested,[Link] 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+[Link] $./[Link] 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 [Link] 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 [Link].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) [Link] [Link] loopisterminated.

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

i=`expr$i+1`

done

ThecaseStatement
[Link] [Link]. Syntax: case $variable-name in pattern1) command ... .. command;; pattern2) command ... .. command;; patternN) command ... .. command;; *) command ... .. command;;

esac The$[Link] [Link]*)anditsexecutedifnomatch [Link]: $ # # # # # 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 [Link]: Syntax: shoption{shellscriptname} OR bashoption{shellscriptname} Optioncanbe vPrintshellinputlinesastheyareread. xAfterexpandingeachsimplecommand,bashdisplaystheexpandedvalueofPS4systemvariable, followedbythecommandanditsexpandedarguments. Example: $cat>[Link] # #Scripttoshowdebugofshell # tot=`expr$1+$2` echo$tot Pressctrl+dtosave,andrunitas $[Link] $./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 [Link]/devdirectorycontains [Link], soundcard,[Link],partitionand filesystem. FuturePoint: Runthefollowingtwocommands $ls>/dev/null $rm>/dev/null 1) Whytheoutputoflastcommandisnotredirectedto/dev/nulldevice?

LocalandGlobalShellvariable(exportcommand)
[Link],ifyouloadanothercopyof shell(bytypingthe/bin/bashatthe$prompt)thennewshellignoredalloldshell'[Link].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([Link]),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 [Link] $/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/[Link] followingexample $cat>myf Thisismyfile ^D(pressCTRL+Dtosavefile) Abovecommandsendoutputofcatcommandtomyffile $cal Abovecommandprintscalendaronscreen,butifyouwishtostorethiscalendartofilethengivecommand $cal>mycal [Link]. $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 [Link]. InLinux(AndinCprogrammingLanguage)yourkeyboard,[Link] nameofsuchfiles

StandardFile FileDescriptorsnumber stdin stdout stderr 0 1 2

Use asStandard output

Example

asStandardinput Keyboard Screen

asStandarderror Screen

BydefaultinLinuxeveryprogramhasthreefilesassociatedwithit,(whenwestartourprogramthesethree filesareautomaticallyopenedbyyourshell).Theuseoffirsttwofiles([Link]),arealready [Link](numberedas2)[Link] redirecttheoutputfromafiledescriptordirectlytofilewithfollowingsyntax Syntax: filedescriptornumber>filename Examples:(Assemumsthefilebad_file_name111doesnotexists) $rmbad_file_name111 rm:cannotremove`bad_file_name111':Nosuchfileordirectory Abovecommandgiveserrorasoutput,sinceyoudon'[Link] 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)[Link] 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,[Link] 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
[Link]'stask,infactmostofusdepend [Link],orteachertolearnnewtechnology(if computerteacher).Whatallthismeanisyoucan'tperformalloflife'[Link] helpyoutosolvespecifictask/problem. Theabovelogicalsoappliestocomputerprogram(shellscript).Whenprogramgetscomplexweneedtouse [Link],wedivideitintosmall chunks/entitieswhichisknowasfunction. Functionisseriesofinstruction/[Link] [Link]: Syntax: function-name ( ) { command1 command2 ..... ... commandN return } Wherefunctionnameisnameofyoufunction,[Link] [Link]: TypeSayHello()at$promptasfollows $SayHello() { echo"Hello$LOGNAME,Havenicecomputing" return }

ToexecutethisSayHello()functionjusttypeitnameasfollows: $SayHello Hellovivek,Havenicecomputing.

Whytowritefunction?
Saveslotoftime. Avoidsrewritingofsamecodeagainandagain Programiseasiertowrite. Programmaintainsisveryeasy.

UserInterfaceanddialogutilityPartI
Goodprogram/[Link]: (1)Usecommandlinearguments(args)[Link] scriptas:$./sutil.shfoo4,wherefoo&[Link]. (2)[Link]: $ 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 ([Link]/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([Link]/Stop)

Userinterfaceusuallyincludes,menus,differenttypeofboxeslikeinfobox,messagebox,[Link] Linuxshell([Link])thereisnobuiltinfacilityavailabletocreatesuchuserinterface,Butthereisone utilitysuppliedwithRedHatLinuxversion6.0calleddialog,whichisusedtocreatedifferenttypeofboxes likeinfobox,messagebox,menubox,[Link].

UserInterfaceanddialogutilityPartII
Beforeprogrammingusingdialogutilityyouneedtoinstallthedialogutility,sincedialogutilityinnot installedbydefault. ForRedHatLinux6.2userinstallthedialogutilityasfollows(FirstinsertRedHatLinux6.2CDinto CDROMdrive) #mount/mnt/cdrom #cd/mnt/cdrom/RedHat/RPMS #[Link] ForRedHatLinux7.2userinstallthedialogutilityasfollows(FirstinsertRedHatLinux7.2#1CDinto CDROMdrive) #mount/mnt/cdrom #cd/mnt/cdrom/RedHat/RPMS #[Link] [Link] 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..."[Link] titleoptionandinfoboxwithinfobox"Message"withthisoption.Here7and50areheightofboxand widthofboxrespectively."LinuxShellScriptTutorial"isthebacktitleofdialogshowonupperleftsideof [Link]. 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 [Link],whetheruserhaspressyesorno button?Theanswerisexitstatus,ifuserpressyesbuttonexitstatuswillbezero,ifuserpressnobuttonexit [Link] 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,[Link] 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([Link]/time)and descriptionformenuitemcalledasitem1(i.e."Shows DateandTime") Firstmenuitemcalledastag2([Link])and descriptionformenuitemcalledasitem2(i.e."Tosee calendar") Firstmenuitemcalledastag3([Link])anddescription formenuitemcalledasitem3(i.e."Tostartgediteditor") Sendselectedmenuitem(tag)tothistemporaryfile

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

Aftercreatingmenus,userselectsmenuitembypressingtheENTERkey,selectedchoiceisredirectedto temporaryfile,Nextthismenuitemisretrievedfromtemporaryfileandfollowingcasestatementcompare [Link],dialogutilityallows [Link] isitworkslowly.

[Link] [Link] [Link] thegoodprogrammerthenyourfirsthabitmustbetoseethegoodcode/samplesofprogramminglanguage thenpracticelotandfinallyimplementtheyourowncode(andbecomethegoodprogrammer!!!). [Link],whicharesuppliedascommandlineargument,andif thistwonosarenotgivenshowerroranditsusage [Link] [Link]. Q.3.Writescripttoprintnosas5,4,3,2,1usingwhileloop. [Link],usingcasestatementtoperformbasicmathoperationas follows +addition subtraction xmultiplication /division Thenameofscriptmustbe'q4'whichworksasfollows $./q420/3,Alsocheckforsufficientcommandlinearguments [Link],time,username,andcurrentdirectory [Link],foreg.Ifnois123itmustprintas321. [Link],Foreg.Ifnois123it'ssumofalldigitwillbe 1+2+3=6. [Link](numberwithdecimalpoint)calculationinLinux(TIP:manbc) Q.9.Howtocalculate5.12+2.5realnumbercalculationat$promptinShell? [Link] thirdvariable,letssaya=5.66,b=8.67,c=a+b? [Link],filenameissuppliedascommandline argument,alsocheckforsufficientnumberofcommandlineargument [Link]($1)contains"*"symbolornot,if$1 doesnotcontains"*"symboladditto$1,otherwiseshowmessage"Symbolisnotrequired".[Link] calledthisscriptQ12thenaftergiving, $Q12/bin Here$1is/bin,itshouldcheckwhether"*"symbolispresentornotifnotitshouldprintRequiredi.e. /bin/*,[Link] $Q12/bin $Q12/bin/* [Link] wecalledthisscriptasQ13andrunas $Q1355myf,Hereprintcontainsof'myf'filefromlinenumber5tonext5lineofthatfile. [Link],yourscriptshouldunderstandfollowingcommandline argumentcalledthisscriptQ14,

Q14cdme Whereoptionsworkas cclearthescreen dshowlistoffilesincurrentworkingdirectory mstartmc(midnightcommandershell),ifinstalled e{editor}startthis{editor}ifinstalled [Link],putthisscriptintoyourstartupfilecalled.bash_profile,thescriptshould runassoonasyoulogontosystem,anditprintanyoneofthefollowingmessageininfoboxusingdialog utility,ifinstalledinyoursystem,Ifdialogutilityisnotinstalledthenuseechostatementtoprintmessage: GoodMorning GoodAfternoon GoodEvening,accordingtosystemtime. [Link],thatwillprint,Message"HelloWorld",inBoldandBlinkeffect,andindifferent colorslikered,brownetcusingechocommand. [Link] cornerofthescreen,whileusercandohis/hernormaljobat$prompt. [Link] 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/[Link]

Delete

Todeleteselectedfile

Exit

ToExitthisshellscript

Note:[Link]/timeonscreencreatefunctionshow_datetime(). [Link] 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) [Link] for2 for3 for4

for5

for6

for7

for8

for8

for9

[Link].

You might also like