0% found this document useful (0 votes)
11 views6 pages

Understanding Korn Shell Scripts

This document discusses shell scripts, which are executable files containing shell commands that are executed sequentially. A shell script can automate repetitive tasks and contain comments, shell definitions, and commands. To execute a shell script, it must be given execute permissions and then can be run by specifying its filename or by just typing its name if the directory is in the PATH. Variables used in shell scripts must be exported to be available in subshells.

Uploaded by

sudhakarramineni
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 DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views6 pages

Understanding Korn Shell Scripts

This document discusses shell scripts, which are executable files containing shell commands that are executed sequentially. A shell script can automate repetitive tasks and contain comments, shell definitions, and commands. To execute a shell script, it must be given execute permissions and then can be run by specifying its filename or by just typing its name if the directory is in the PATH. Variables used in shell scripts must be exported to be available in subshells.

Uploaded by

sudhakarramineni
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 DOC, PDF, TXT or read online on Scribd

[Link]? Ashellscriptismerelyanexecutablefilecontainingmultipleshellcommands [Link]: ashelldefinitionstatement comments commands TheKornshellsupportsanumberoffeaturesandfunctionsthatmake learningshellscriptingtechniquespreferabletolearningastandard programminglanguagesuchasCorC++.Anaddedbonusofusingashell scriptisthatitisinterpreted,meaningthatitdoesnothavetobecompiled likemostprogramminglanguages. 5.1AnOverview [Link] familiarwithtwosimpleshellscriptsthatexecuteautomaticallyeachtimeyou [Link].

kshrcdefineacustomized "lookandfile"[Link] commandsforyousothatyoudon'thavetoenterthemmanuallyeachtime youlogon. [Link] simplethatprintsacopyofthecontentsofyourpresentworkingdirectory [Link]: #!/usr/bin/ksh #simpleprintsacopyofyourpwdtoafile print"Alistingof$PWD">[Link] lsl>>[Link] exit Typethecontentsofthescriptabove,namethefilesimple,andyouhavea [Link] astypingthescriptname,providedyoukeepinmindtherulesofexecution coveredinthenextsection. 5.2ShellScriptExecution Onceashellscriptiscreated,[Link],

beforeanyKornshellscriptbecanexecuted,itmustbeassignedtheproper [Link],in thiscasegivingexecutepermissiontothesimplefile: $chmod+xsimple Afterthat,youcanexecutethescriptbyspecifyingthefilenameasan argumenttothekshcommand: $kshsimple [Link],forthat methodtowork,thedirectorycontainingthescriptmustbedefinedinyour [Link],youmay havenoticedthatthePATH=$PATH:$HOMEdefinitionwasalreadyinplace. Thisenablesyoutorunscriptslocatedinyourhomedirectory($HOME) [Link],becauseofthatpredefined PATHvariable,thesimplescriptcanberunfromthecommandlinelikethis: $simple (Forthepurposesofthiscourse,we'llsimplifythingsbyrunningallscriptsby theirscriptnameonly,notasanargumenttothekshcommand.) Youcanalsoinvokethescriptfromyourcurrentshellbyopeninga backgroundsubprocessorsubshellwheretheactualcommandprocessing [Link]'tseeitrunning,butitwillfreeupyourexistingshellso [Link], processingintensivescriptsthatwouldotherwisetakeoveryourcurrentshell untiltheycomplete. Torunthescriptyoucreatedinthebackground,invokeitthisway: $simple& Whenthescriptcompletes,you'llseeoutputsimilartothisinthecurrentshell: [1]Done(127)simple ItisimportanttounderstandthatKornshellscriptsruninasomewhat [Link],variablesdefinedin theKornshellaren'tunderstoodoutsideofthedefiningorparentshell.

Theymustbeexplicitlyexportedfromtheparentshelltoworkinasubsequent [Link] variableknownoutsidetheparentshell,anysubshellwillautomatically inheritthevaluesyoudefinedfortheparentshell. Forexample,here'sascriptnamedlookmeupthatdoesnothingmorethan printalinetostandardoutputusingthemyaddress(definedas123Anystreet USA)variable: $catlookmeup print"Iliveat$myaddress" Ifyouopenanewshell(usingthekshcommand)fromtheparentshelland runthescript,youseethatmyaddressisundefined: $ksh $lookmeup Iliveat $ However,ifyouexportmyaddressfromtheparentshell: $exit $exportmyaddress andthenopenanewshellandrunthelookmeupscriptagain,thevariableis nowdefined: $ksh $lookmeup Iliveat123AnystreetUSA Toillustratefurtherhowtheparentshelltakesprocessingprecedence,let's changethevalueofmyaddressinthesubshell: $myaddress='Houston,Texas' $print$myaddress Houston,Texas Now,ifyouexitthenewshellandgobacktotheparentshellandtypethe samecommand: $exit

$print$myaddress 123AnystreetUSA youseethattheoriginalvalueintheparentshellwasnotaffectedbywhat youdidinthesubshell. Awaytoexportvariablesautomaticallyistousethesetoallexport [Link] subshell,butcanexportvariablescreatedintheparentshelltoallsubshells [Link],itcanautomaticallyexport variablescreatedinsubshellstonewsubshellscreatedafterrunningthe [Link]. NOTE: Ifascriptiswritingoutputtoafile,youcaninteractivelymonitortheprogress oftheoutputfile(andtherebythescript)byusingthetailfoutputfile [Link],useCtrlC. 5.3ShellScriptsAnIllustratedView Attheriskofsoundingredundant,let'srecap:shellscriptsaresimplyfiles [Link]'sgoabit furtherandlookatashellscript,linebyline. AnyKornshellscriptshouldcontainthislineattheverybeginning: #!/usr/bin/ksh Asyouprobablyalreadyknow,the#signmarksanythingthatfollowsiton thelineasacommentanythingcomingafteritwon'tbeinterpretedor [Link],whenthe#characterisfollowedbya! (commonlycalled"bang"),[Link] theKornshellwillbe(orshouldbe)[Link] specified,thesystemwillattempttoexecutethescriptusingwhateverits defaultshelltypeis,[Link] somecommandsthatothershellsdonot,thiscansometimescauseaproblem. Tobevalid,thislinemustbeontheveryfirstlineofthescript. [Link],a systemadministratormightusethefollowingscript,nameddiskusehere,to keeptrackofdiskspaceusage: #!/usr/bin/ksh #diskuse

#Showsdiskusageinblocksfor/home cd/var/log [Link].0 cd/home dusk*>/var/log/[Link] cat/var/log/[Link] Shownagainbutthistimewithannotationthescript'sprocessingstepsare clear: #!/usr/bin/ksh #SCRIPTNAME:diskuse #SCRIPTPURPOSE:Showsdiskusageinblocksfor/home #[Link] cd/var/log #[Link] [Link].0 #changetothetargetdirectory cd/home #runthedusk*commandonallfiles #in/homeandredirecttheoutput #to/var/log/[Link] dusk*>/var/log/[Link] #displaytheoutputofthedusk* #commandtostandardoutput cat/var/log/[Link] It'snotagoodideatohardcodepathnamesintoyourscriptslikewedidinthe [Link]/var/logasthetargetdirectoryseveraltimes, butwhatifthelocationofthefileschanged?Inashortscriptlikethisone,the [Link],somescriptscanbehundredsoflineslong, [Link] createavariabletotaketheplaceofthefullpathname,suchas: LOGDIR=/var/log Thefourthlineofthescriptwouldchangefrom:

[Link].0 to: cp${LOGDIR}/[Link]${LOGDIR}/[Link].0 Then,[Link],youwouldonlyhaveto [Link] aredefiningthepathnamewiththeLOGDIRvariable,thecd/var/loglinein [Link],thedusk*>/var/log/[Link] /var/log/[Link]${LOGDIR}for/var/log.

You might also like