Sie sind auf Seite 1von 6

5.WhatisaShellScript? Ashellscriptismerelyanexecutablefilecontainingmultipleshellcommands thatareexecutedsequentially.Thefilecancontain: ashelldefinitionstatement comments commands TheKornshellsupportsanumberoffeaturesandfunctionsthatmake learningshellscriptingtechniquespreferabletolearningastandard programminglanguagesuchasCorC++.Anaddedbonusofusingashell scriptisthatitisinterpreted,meaningthatitdoesnothavetobecompiled likemostprogramminglanguages. 5.1AnOverview Shellscriptsgenerallyexisttoautomaterepetitivetasks.Youarealready familiarwithtwosimpleshellscriptsthatexecuteautomaticallyeachtimeyou logontothesystem.Thesescripts.profileand.

kshrcdefineacustomized "lookandfile"foryourenvironment.Bothofthesefilessimplyexecuteasetof commandsforyousothatyoudon'thavetoenterthemmanuallyeachtime youlogon. Hereisaslightlymorecomplexexample.Thisisasimpleshellscriptnamed simplethatprintsacopyofthecontentsofyourpresentworkingdirectory toafilenamedlist.outandgivesitatitleheadinginthefirstline: #!/usr/bin/ksh #simpleprintsacopyofyourpwdtoafile print"Alistingof$PWD">list.out lsl>>list.out exit Typethecontentsofthescriptabove,namethefilesimple,andyouhavea shellscript.Executingthescriptfromthecommandlineisasstraightforward astypingthescriptname,providedyoukeepinmindtherulesofexecution coveredinthenextsection. 5.2ShellScriptExecution Onceashellscriptiscreated,thereareseveralwaystoexecuteit.However,

beforeanyKornshellscriptbecanexecuted,itmustbeassignedtheproper permissions.Thechmodcommandchangespermissionsonindividualfiles,in thiscasegivingexecutepermissiontothesimplefile: $chmod+xsimple Afterthat,youcanexecutethescriptbyspecifyingthefilenameasan argumenttothekshcommand: $kshsimple Youcanalsoexecutescriptsbyjusttypingitsnamealone.However,forthat methodtowork,thedirectorycontainingthescriptmustbedefinedinyour PATHvariable.Whenlookingatyour.profileearlierinthecourse,youmay havenoticedthatthePATH=$PATH:$HOMEdefinitionwasalreadyinplace. Thisenablesyoutorunscriptslocatedinyourhomedirectory($HOME) withoutusingthekshcommand.Forinstance,becauseofthatpredefined PATHvariable,thesimplescriptcanberunfromthecommandlinelikethis: $simple (Forthepurposesofthiscourse,we'llsimplifythingsbyrunningallscriptsby theirscriptnameonly,notasanargumenttothekshcommand.) Youcanalsoinvokethescriptfromyourcurrentshellbyopeninga backgroundsubprocessorsubshellwheretheactualcommandprocessing willoccur.Youwon'tseeitrunning,butitwillfreeupyourexistingshellso youcancontinueworking.Thisisreallyonlynecessarywhenrunninglong, processingintensivescriptsthatwouldotherwisetakeoveryourcurrentshell untiltheycomplete. Torunthescriptyoucreatedinthebackground,invokeitthisway: $simple& Whenthescriptcompletes,you'llseeoutputsimilartothisinthecurrentshell: [1]Done(127)simple ItisimportanttounderstandthatKornshellscriptsruninasomewhat differentwaythantheywouldinothershells.Specifically,variablesdefinedin theKornshellaren'tunderstoodoutsideofthedefiningorparentshell.

Theymustbeexplicitlyexportedfromtheparentshelltoworkinasubsequent scriptorsubshell.Ifyouusetheexportortypesetxcommandstomakethe 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 command.Thiscommandcannotexportvariablestotheparentshellfroma subshell,butcanexportvariablescreatedintheparentshelltoallsubshells createdafterthecommandisrun.Likewise,itcanautomaticallyexport variablescreatedinsubshellstonewsubshellscreatedafterrunningthe command.setoallexportisahandycommandtoplaceinyour.kshrcfile. NOTE: Ifascriptiswritingoutputtoafile,youcaninteractivelymonitortheprogress oftheoutputfile(andtherebythescript)byusingthetailfoutputfile command.Toquitthetailcommand,useCtrlC. 5.3ShellScriptsAnIllustratedView Attheriskofsoundingredundant,let'srecap:shellscriptsaresimplyfiles containingalistofcommandstobeexecutedinsequence.Nowlet'sgoabit furtherandlookatashellscript,linebyline. AnyKornshellscriptshouldcontainthislineattheverybeginning: #!/usr/bin/ksh Asyouprobablyalreadyknow,the#signmarksanythingthatfollowsiton thelineasacommentanythingcomingafteritwon'tbeinterpretedor processedaspartofthescript.But,whenthe#characterisfollowedbya! (commonlycalled"bang"),themeaningchanges.Thelineabovespecifiesthat theKornshellwillbe(orshouldbe)executingthescript.Ifnothingis specified,thesystemwillattempttoexecutethescriptusingwhateverits defaultshelltypeis,notnecessarilyaKornshell.SincetheKornshellsupports somecommandsthatothershellsdonot,thiscansometimescauseaproblem. Tobevalid,thislinemustbeontheveryfirstlineofthescript. Shellscriptsareoftenusedtoautomatedaytodaytasks.Forexample,a systemadministratormightusethefollowingscript,nameddiskusehere,to keeptrackofdiskspaceusage: #!/usr/bin/ksh #diskuse

#Showsdiskusageinblocksfor/home cd/var/log cpdisk.logdisk.log.0 cd/home dusk*>/var/log/disk.log cat/var/log/disk.log Shownagainbutthistimewithannotationthescript'sprocessingstepsare clear: #!/usr/bin/ksh #SCRIPTNAME:diskuse #SCRIPTPURPOSE:Showsdiskusageinblocksfor/home #changetothedirectorywheredisk.logresides cd/var/log #makeacopyofdisk.log cpdisk.logdisk.log.0 #changetothetargetdirectory cd/home #runthedusk*commandonallfiles #in/homeandredirecttheoutput #to/var/log/disk.log dusk*>/var/log/disk.log #displaytheoutputofthedusk* #commandtostandardoutput cat/var/log/disk.log It'snotagoodideatohardcodepathnamesintoyourscriptslikewedidinthe previousexample.Wespecified/var/logasthetargetdirectoryseveraltimes, butwhatifthelocationofthefileschanged?Inashortscriptlikethisone,the impactisnotgreat.However,somescriptscanbehundredsoflineslong, creatingamaintenanceheadacheiffilesaremoved.Awayaroundthisisto createavariabletotaketheplaceofthefullpathname,suchas: LOGDIR=/var/log Thefourthlineofthescriptwouldchangefrom:

cpdisk.logdisk.log.0 to: cp${LOGDIR}/disk.log${LOGDIR}/disk.log.0 Then,ifthelocationsofdisk.logchangesinthefuture,youwouldonlyhaveto changethevariabledefinitiontoupdatethescript.Alsonotethatsinceyou aredefiningthepathnamewiththeLOGDIRvariable,thecd/var/loglinein thescriptisunnecessary.Likewise,thedusk*>/var/log/disk.logandcat /var/log/disk.loglinescansubstitute${LOGDIR}for/var/log.

Das könnte Ihnen auch gefallen