您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 咨询培训 > Linux - Programming with Shell Scripts
ESSENTIALCOMMANDSPOCKETGUIDELINUXCoversFedoraLinuxDANIELJ.BARRETT168|LinuxPocketGuideProgrammingwithShellScriptsEarlierwhenwecoveredtheshell(bash),wesaidithadaprogramminglanguagebuiltin.Infact,youcanwritepro-grams,orshellscripts,toaccomplishtasksthatasinglecom-mandcannot.Likeanygoodprogramminglanguage,theshellhasvariables,conditionals(if-then-else),loops,inputandoutput,andmore.Entirebookshavebeenwrittenonshellscripting,sowe’llbecoveringthebareminimumtogetyoustarted.Forfulldocumentation,runinfobash.WhitespaceandLinebreaksbashshellscriptsareverysensitivetowhitespaceandline-breaks.Becausethe“keywords”ofthisprogramminglan-guageareactuallycommandsevaluatedbytheshell,youneedtoseparateargumentswithwhitespace.Likewise,alinebreakinthemiddleofacommandwillmisleadtheshellintothinkingthecommandisincomplete.Followthecon-ventionswepresenthereandyoushouldbefine.VariablesWedescribedvariablesearlier:$MYVAR=6$echo$MYVAR6Allvaluesheldinvariablesarestrings,butiftheyarenumerictheshellwilltreatthemasnumberswhenappropriate.$NUMBER=10$expr$NUMBER+515Whenyourefertoavariable’svalueinashellscript,it’sagoodideatosurrounditwithdoublequotestopreventcer-tainruntimeerrors.Anundefinedvariable,oravariablewithspacesinitsvalue,willevaluatetosomethingunexpectedifnotsurroundedbyquotes,causingyourscripttomalfunction.$FILENAME=MyDocumentSpaceinthename$ls$FILENAMETrytolistitProgrammingwithShellScripts|169ls:My:NosuchfileordirectoryOops!lssaw2argumentsls:Document:Nosuchfileordirectory$ls-l$FILENAMEListitproperlyMyDocumentlssawonly1argumentIfavariablenameisevaluatedadjacenttoanotherstring,sur-rounditwithcurlybracestopreventunexpectedbehavior:$HAT=fedora$echoThepluralof$HATis$HATsThepluraloffedoraisOops!Novariable“HATs”$echoThepluralof$HATis${HAT}sThepluraloffedoraisfedorasWhatwewantedInputandOutputScriptoutputisprovidedbytheechoandprintfcommands,whichwedescribedin“ScreenOutput”onpage144:$echoHelloworldHelloworld$printfIam%dyearsold\n`expr20+20`Iam40yearsoldInputisprovidedbythereadcommand,whichreadsonelinefromstandardinputandstoresitinavariable:$readnameSandySmithENTER$echoIreadthename$nameIreadthenameSandySmithBooleansandReturnCodesBeforewecandescribeconditionalsandloops,weneedtheconceptofaBoolean(true/false)test.Totheshell,thevalue0meanstrueorsuccess,andanythingelsemeansfalseorfailure.Additionally,everyLinuxcommandreturnsanintegervalue,calledareturncodeorexitstatus,totheshellwhenthecom-mandexits.Youcanseethisvalueinthespecialvariable$?:$catmyfileMynameisSandySmithand170|LinuxPocketGuideIreallylikeFedoraLinux$grepSmithmyfileMynameisSandySmithandAmatchwasfound...$echo$?0...soreturncodeis“success”$grepaardvarkmyfile$echo$?Nomatchwasfound...1...soreturncodeis“failure”Thereturncodesofacommandareusuallydocumentedonitsmanpage.testand“[”Thetestcommand(builtintotheshell)willevaluatesimpleBooleanexpressionsinvolvingnumbersandstrings,settingitsexitstatusto0(true)or1(false):$test10-lt5Is10lessthan5?$echo$?1No,itisn't$test-nhelloDoesthestring“hello”havenonzerolength?$echo$?0Yes,itdoesAlistofcommontestargumentsarefoundinTable12,forcheckingpropertiesofintegers,strings,andfiles.testhasanunusualalias,“[”(leftsquarebracket),asashorthandforusewithconditionalsandloops.Ifyouusethisshorthand,youmustsupplyafinalargumentof“]”(rightsquarebracket)tosignifytheendofthetest.Thefollowingtestsareidenticaltothosebefore:$[10-lt5]$echo$?1$[-nhello]$echo$?0Rememberthat“[”isacommandlikeanyother,soitisfol-lowedbyindividualargumentsseparatedbywhitespace.Soifyoumistakenlyforgetsomewhitespace:$[5-lt4]Nospacebetween4and]bash:[:missing']'ProgrammingwithShellScripts|171thentestthinksthefinalargumentisthestring“4]”andcomplainsthatthefinalbracketismissing.Table12.SomecommonargumentsforthetestcommandFiletests-dnameFilenameisadirectory-fnameFilenameisaregularfile-LnameFilenameisasymboliclink-rnameFilenameexistsandisreadable-wnameFilenameexistsandiswritable-xnameFilenameexistsandisexecutable-snameFilenameexistsanditssizeisnonzerof1-ntf2Filef1isnewerthanfilef2f1-otf2Filef1isolderthanfilef2Stringtestss1=s2Strings1equalsstrings2s1!=s2Strings1doesnotequalstrings2-zs1Strings1haszerolength-ns1Strings1hasnonzerolengthNumerictestsa-eqbIntegersaandbareequala-nebIntegersaandbarenotequala-gtbIntegeraisgreaterthanintegerba-gebIntegeraisgreaterthanorequaltointegerba-ltbIntegeraislessthanintegerba-lebIntegeraislessthanorequaltointegerbCombiningandnegatingtestst1-at1And:Bothtestst1andt2aretruet1-ot2Or:Eithertestt1ort2istrue!your_testNegatethetest,i.e.,your_testisfalse\(your_test\)Parenthesesareusedforgrouping,asinalgebra172|LinuxPocketGuidetrueandfalsebashhasbuilt-incommandstrueandfalse,whichsimplysettheirexitstatusto0and1,respectively.$true$echo$?0$false$echo$?1Thesewillbeusefulwhenwediscussconditionalsandloops.ConditionalsTheifstatementchoosesbetweenalternatives,eachofwhichmayhaveacomplextest.Thesimplestformistheif-thenstatement:ifcommandIfexitstatusofcommandis0thenbodyfiForexample:if[`whoami`=root]thenechoYouarethesuperuserfiNextistheif-then-elsestatement:ifcommandthenbody1elsebody2fiForexample:if[`whoami`
本文标题:Linux - Programming with Shell Scripts
链接地址:https://www.777doc.com/doc-3442347 .html