《奥宝gensis脚本培训(英文版).docx》由会员分享,可在线阅读,更多相关《奥宝gensis脚本培训(英文版).docx(68页珍藏版)》请在课桌文档上搜索。
1、ProgramminginCshellThroughtheDemoandTraiCentre,Orbotechiscommittedtoofferingitscustomersthehighestqualityprofessionaltraining,whichprovidesthemostefficientandeconomicalsolutionstothechallengesofthePrintedCircuitBoardIndustry.SouthernChinaCommittedtoExcellence4B-4C,BlockC1ElectronicsScience&Technolog
2、yBldg.No.2070ShennanZhongRoadShenzhen518031Tel:(86)7553287800Fax:(86)7553287801DemozTrainingCentreSouthernChinaOrtxitechTechnology(Shenzhen)CompanyLtd.No.107-113,Block5A,InternationalCommerceCenterNo.1001HonghuaRoad,FutianFreeTradeZoneGuangzhouOfficeRoom1006-7l10F,EastTowerTianheEntertainmentPlaza62
3、1TianheRoadGuangzhou510630Tel:(86)20-8757-4616Fax:(86)20-8757-4620Tel:(86)75535951303595137NorthernChinaCommittedtoExcellenceFax:(86)7553595135DemoZTrainingCentreNorthernChinaShanghaiOffice1F,278ZhuJiangRoad(N)KunshanDevelopmentZoneKunshan1F,278ZhuJiangRoad(N)KunshanDevelopmentZoneKunshanRoom243,Xin
4、MaoBuilding,2TaiZhongRoad(三)WaigaoqiaoFreeTradeZone,Shanghai200131Tel:(86)520-735-7745Fax:(86)520-735-8628Tel:(86)520-735-7745Fax:(86)520-735-8628Tel:(86)21-5048-0555*4202Fax:(86)21-5048-0555-4202Cshismorethanasimplecommandlineprocessor.Itisalsoaprogramminglanguage.Youcanwriteprograms(calledscripts)
5、thatareexecutedbytheCShell.CONTENTSLCOmmandform琏音误!未定义书签。SingIeCOmmandlMUltiPleCommandS2COmmandGrOUPS3ConditionalCommandExecution4SUrnmary52IOredirectionandPiDeS音误!未定义书签。OUtPUtRedireCtionlAPPendingC)UtPUt2RedireCtingErrorC)UtPUl3SePanltingStandardOUtPUtandErrOrOUtPUt4TheBUilt-inNoClObberVariable5Red
6、ireCtingInPUt6COrmeCtingCommands:PiPeS7RedirectingStandardErrorThroughPipes9SummarylO3fWenameexpansion错误!未定义书签。FiIeIameEXPanSiOnMetaCharaCterSlMatChingFiIenameStringCOmPonentS2MatChingWithCharaCterSCIaSSeS3DeDVrdFilenameS4EscapeMechanisms5Summary641variableslSettingVaVabIeSlUsingShellVariables2Wordl
7、istVariables3VaVableSUbStitUtiOn4ReIeaSiagVariabIeS5TeStingifVariablesaseSet6PalhnamCVariableS7COmmandSUbStitUliOn8QUotiOgVariableS9ShellPreDefinedVariableslOSummaryl15,scriptslShellScriptslShelISCriCtS-EXamDleS2TheFOrmatOfShenSCriDtS3COmmentSinSheIISCriCtS4TheEChoCOmmand5ReadingDatafromtheTelTnina1
8、6PassingParameterstoShellProcedures7UsingArgv8TheShiflCommandloTheConditionalSlatemenl11ACaUIiOnOnUndefInedVariabIeS14TheEXECommand155.13SUmmary166.ExpreSSiolIEVaIUatk)IllEXDreSSiOnevaluationArithmetiCC)PeratorS2ReIatiOnalOPeratOrS3LOgiCalODeraIorS4OPeratOrPreCedenCe5FileInquiryOperators7SUmmary97Lu
9、odsandSWitCheSlTheForeaChStatementlTheWhveStatement2TheSWitChStatement3TheBreak&ContinUeStatement6theGotoStatement7SUmmary81. COMMANDFORMS11SlNGLECOMMANDTHEFoRNTATFoRASlNGLECOMMAND%command_nameargumentsNoTES1. command_nameisasimplenameoranyvalidpathname.2. argumentsmaybeaflag,apathnameorsomeotherspe
10、cialstring.3. Spacesand/ortabsalwaysseparatearguments.4. Akeystroketerminateseachcommandline.5. Youcanusetocontinuealongcommandtothenextline.EXAMPLESToprintthefullpathnameofyourcurrentworkingdirectory:%pwdTotypethestringHelloonourterminal:%echoHelloTocreatetwonewdirectoriesinyourcurrentdirectory:%mk
11、dirdir_ldir_2Tosearchthedirectoryhierarchystartingfromyourcurrentdirectoryforallthefilesnamedtest.dat,andtoprinttheirfullpathname:%find-nametest.dat-printNOTESIfyouliketogiveanargumentthathasablankinityoumustusequotesordoublequotes.EXAMPLES% prog New York % prog New Yorku % prog New Yorkoneargument=
12、NewYorkoneargument=NewYorktwoarguments;First=New,Second=York1.2MULTIPLECOMMANDSTheCShellallowsustoconcatenateseveralcommandsonasingleinputline.Asemicolonisusedtoseparatetheindividualcommands.THEFoRMATFoRMULTIPLECOMMANDS%command;command_2;command_nEXAMPLESTomakeanewdirectoryandtomakethatdirectorythew
13、ork_directory:%mkdirinformation;cdinformationGotoadirectoryandcompileaprogram,afterthatgototheroot:%cdsource;ccprogl.c;cd/NoTES TheC_Shellexecutescommand_1,Command_2,command_nsequentially. Eachcommandinthelistmayhavearguments. Usemultiplecommandswhenasetofcommandsformsalogicalgroup.1.3 COMMANDGROUPS
14、TheCShellallowsustotreatagroupofcommandsasasinglecommandandtorunthecommandgroupinasub_shell,preservingtheparentshellsenvironment.THEFORMATFoRACOMMANDGROUP%(cmd_l;cmd_2;.;cmd_n)EXAMPLESToillustrateacommandgroupinaction,consider:%(cdc_progs;ccprogl.c)Thiscommand(1)changesdirectories;(2)runsacompile;an
15、dthen(3)automaticallyreturnstoourparentshellandouroriginaldirectory.1.4 CONDITIONALCOMMANDEXECUTIONManyUNIXcommandsreturnstatusinformation.THECONVENTIONONormal(successful)exit.non-OAcommanderroroccurred.EXAMPLESTochecktheerrorstatusofacommand,usetheCShellvariablestatus:%echo$status1Inthiscase,Sstatu
16、s=1meansthatthefileprogl.cdoesntmatchthepatterngarfield.NoTES ACShellvariableisreferencedbyprefixingadollarsign($)toitsname. grepreturnsOstatusifitfindsthespecifiedpattern.Ifgrepcan,tfindthepattern,itreturns1;ifitcantaccessthefile(orothererror),itreturns2.Toexecutecmd_2onlyifcmd_lsucceeds,weusethelo
17、gicalconnectiveoroperator&asfollows:%cmd_l&cmd_2Similarly,Wecanusethelogicalconnectivetoexecutecmd_2onlyifcmd_lfailsasfollows:%cmd_lHcmd_2EXAMPLESHere,weusegreptosearchthefileforthestringG54.IfgrepfindsG54,itwillreturnastatusvalueofO(i.e.OK).Onlyinthiscasewillthefilebespooledtothelineprinter.%grepG5
18、4xl234.gbrif($status=1)echo,G54NOTFOUNDn1.5SUMMARY Commandsconsistofprogramnamesfollowedbyarguments(separatedbyspacesortabs). Manycommandsexpectspecialargumentscaseoptions,usuallyintroducedbythe,-,character. Mostotherargumentsarepathnames. Acommandlinemaycontainseveralrelaycommandsseparatedbysemicol
19、ons;thesecommandsexecutesequentially. Commandscanbealsoformedintogroups,enclosingtheminparentheses. Commandgroupsruninasub-shell,withoutdisturbingtheparentshellsexistingenvironment. Commandsconnectedby&orexecuteconditionally.TABLEOFCoMMANDFORMSCommandFormMeaning%cmd_nameargumentsSinglecommand%cmd_l;
20、cmd_2Multiplecommand%(cmd_l;cmd_2)Commandgroup%cmd_l&cmd_2Executecmd_2ifcmd_lsucceeds%cmd_lHcmd_2Executecmd_2ifcmd_lfails21OUTPuTREDHiECHONOutputredirectionletsussavecommandoutputinafileforlaterreferenceorforuseasinputtoanotherprogram.Theoutputthatnormallyappearsonourscreen(excludingerrormessages)is
21、calledstandardoutput(abbreviatedstdout).Wemayredirectstandardoutputtoafilebymeansofthesymbol,asin:%commandfileNoTES Outputfromasinglecommandorfromacommandgroupmayberedirected. Thespacessurroundingthesymbolareoptional. Iffiledoesnotexist,theCShellwillcreateit. Iffiledoesexist,itspreviouscontentswillb
22、eoverwritten(destroyed).EXAMPLESToredirecttheoutputofthelistdirectory(Is)commandintofile.infb,wecanuse:THECOMMANDPutsadate-timestampintobeforethedirectoryinformation.Notethatomittingthecommandgroupparenthesesasin:SendstheoutputfromdatetotheterminalandtheresultsoftheIs-1commandtofile.infb.CAUTIONDono
23、tusethesamefileasacommandlineargumentandalsoasthetargetofoutputredirection.EXAMPLESFirst,theCShellopensandtruncatesittoanullfile;thenitcatenates(nowanullfile)andinto.Thefinalresult:iscopiedto.Theoriginalcontentsofarelost.SettingtheCshellvariablenoclobberpreventsthiscommonerror.2.2APPENDINGOUTPUTWema
24、yredirectstandardoutputtotheendofanexistingfilebymeansoftheredirectionsymbol.Inthiscase,thepreviouscontentsofthedestinationfilewillnotbedestroyed.Ifthefiledoesnotexist,theCShellwillcreateit,justasinthecaseoftheredirectionsymbol.THEGENERALCOMMANDFORMAT%commandfileEXAMPLESNOTESEachtimetheabovesequence
25、ofthreecommandsisexecuted,additionaloutputwillbeappendedto.23REDIRECTlNGERGoROIJTPUTOftenacommandwillproducespecialoutput(errormessages)informingyouofproblemsthatitencounteredwhileexecuting.Thisiscallederroroutputordiagnosticoutput(abbreviatedstderr).Normallytheerroroutputappearsinterspersedwithstan
26、dardoutputonourterminal.Redirectingstandardoutputdoesnotredirecterroroutput.Forexample,supposethatisaonelinefilewhichcontainsabcdefandthatdoesnotexist.EXAMPLESbl.dat:NosuchfileordirectoryabcdefIfweredirectstandardoutput,westillseetheerrormessage:bl.dat:Nosuchfileordirectory.Wecanredirecterroroutputt
27、ogetherwithstandardoutputbyusingthe&redirectionsymbol,asin:%command&fileWecanappenderroroutputtogetherwithstandardoutputbyusingthe&redirectionsymbol,asin:%command&fileLookagainatthepreviousexample,thistimeredirectingbothstdoutandstderr:bl.dat:Nosuchfileordirectoryabcdef24SEPARATlNGSNANDARDOuTPIjTAND
28、EiwoROUTPUTWecanusecommandgroupingwithredirectiontoseparatestandardoutputfromerroroutput.Forexample,supposethatwehaveaproductiontaskcalledcmd_lthatgeneratesstandardoutputandalsodiagnosticoutput.Toseparatethetwotypesofoutput,wecanuse:Theredirectionorderisimportant.Wemustuseinsidethecommandgroupand&ou
29、tside.TheCShellfirstopensforbothstandardoutputanderroroutputredirection.Thenitcreatesasubshelltoexecutethecommandgroup.Withinthesubshell,itopensforstandardoutputredirectiononly.Whencmd_lgeneratesstandardoutput,itiscapturedwithinthesubshell.Erroroutputispassedonbythesubshell,tobecollectedin.2.5THEBUI
30、LT-INNOCLOBBERVARIABLETheCShellhasabuilt-invariablecallednoclobberthatmaybeusedtosafeguardexistingfilesfrombeingoverwrittenthroughoutputredirection.Settingnoclobberalsopreventsfilecreationifwehavespecifiedanappend()redirectionoperation.Toactivatenoclobberprotection,type:%setnoclobberToturnitoff,use:
31、%unsetnoclobberEXAMPLES%setnoclobber%dateusers%whoamiusers(users,notchanged)users:FileexistsNOTES%setnoclobber%dateusers%whoamiusers(willnotgiveanyerrormessage).Thesetnoclobberwillpreventthedeletionofthecontentofafilebutnottheadditionofnewdata.WecanforcetheCShelltooverridenoclobberprotectionbyadding
32、anexclamationpoint(!)foremphasisaftertheredirectionsymbol.%setnoclobber%dateusers%whoami!users(users*overwritten)Thefollowingappendcommandforcesthecreationofthefileevenifitdoesnotexist:%setnoclobberNOTESAspaceisalwaysrequiredaftertheexclamationpointwhenever!isappendedtoanyoutputredirectionoperator.T
33、hisistopreventCshfromtryingtointerpretthe!andwhateverfollowsitasahistoryvariable.26REDIREDTlNGNPUTIfacommandrequiresinputdatawhileitisexecuting,thatinputistakenfromthestandardinputstream(abbreviatedstdin).Thestandardinputfilemaybere-directedwiththeredirectionsymbol.THECOMMANDFORMAT%commandfileNoTES
34、Aswithoutputredirection,spacearoundthetmptemp;wc-1tmptemp;rmtmptemp15TheCShellprovidesanimportantmechanismcalledapipe(thesymbolis)forconnectingtheoutputofonecommanddirectlytotheinputofthenext.Thiseliminatestheneedforanintermediatefile.Usingapipe,wecanabbreviatetheabovecommandto:%whoIwc-115Morethanon
35、epipecanbeusedinasinglecommand.Forinstance,heresacommandthatuses2pipestoconnect3components:%Is-11grep-,sort-nrThiscommandliststhefilesinourCWD(longformat);usesgreptostripoutlinesbelongingtoordinaryfiles;andthensortsthesefilesbysizefromlargesttosmallest.Thepattern,-*tellsgreptolookforlinesthatbeginwi
36、ththecharacter-n.InIsoutput,allsuchlinesbelongtoordinaryfiles.Usingthepattern*x$wouldtellgreptolookforlinesthatendwiththecharacterxn.Notes: Asequenceofcommandsconnectedbypipesisoftencalledapipeline. Commandslikegrepthatreaddatafromstandardinput,transformthedatasomehow,andwritethechangeddatatostandar
37、doutputareoftencalledfilters.CoMMONFlLTERSINPIPELINESNameMeaningddUpper/Lowercaseconversion;alsoASCII/EBCDICtranslation.grepExtractslinesfromitsinputthatmatchagivenpattern.PrPrettyprintsitsinput.sedStreamEditor-editsinputlinesoneatatime.sortSortsitsinputinuser-specifiedways.trTranslateCharacters.uni
38、qDeletesrepeatedlinesinafile.WCCountscharacters,wordsorlinesinitsinput.Thegeneralformatforusingpipesis:%cmd_lIcmd_2.cmd_nNotethatanycommandontheleftsideofthepipemustwritetostandardoutputandthatanycommandontherightsideofapipemustreadfromstandardinput.Toillustratewhathappensifthisrequirementisignored,
39、letstrytoremoveallbackupfiles(extension.bak)inourCWDwithapipedcommand:%Is*.bakIrm-iTheproblemisthatrmexpectsitsargumentsonthecommandline,notinstandardinput.Ofcourse,wedontneedapipeforthistask;asimplerm*.baksuffices.28REDIRECTlNGSNANDARDERR。RTHROUGHPlPESOrdinarily,onlystandardoutputpassesthroughapipe
40、,noterroroutput.Toredirectbothtypesofoutputthroughapipe,usethesymbol|&asin:%cmd_l|&cmd_2Supposewearesearchingforacertainclassoffilesandwewanttoreviewbothfilenamesanderrormessagesfromthebeginningofthelist.WECANUSE%find/-name*.bak-print|&moreshowsallerrormessagesplusallpathnamesfound.2.9SUMMARY Redire
41、ctionallowsustousefilesasthesourceofstandardinputandasthedestinationforstandardoutputanderroroutput. Outputcaneitheroverwritethecontentsofanexistingfileorbeappendedtoit. Thenoclobbervariablecanbesettoprotectexistingfilesfrombeinginadvertentlyoverwritten. Pipesallowustodirecttheoutputofonecommandinto
42、theinputofanother. Aseriesofcommandsconnectedbypipesiscalledapipeline. Commandsinapipelineexecuteconcurrently.SUMMARYOFREDIREeTINGSYMBoLSSymbolMeaningRedirectstandardoutput(stdout)&Redirectstandardoutputandstandarderror(stderr)!Redirectstdout,overridenoclobber.&!Redirectstdoutandstderr,overridenoclo
43、bber.Appendstdout.&Appendstdoutandstderr.!Appendstdout,overridenoclobber.&!Appendstdoutandstderr,overridenoclobber.IPipestdout.l&Pipestdoutandstderr.(cmdfilel)&file2Redirectstdouttofilelandstderrtofile2.3.FILENAMEEXPANSION31RLENAMEEXPANSM)NMETACHARACTERSInmostshellcommands,theargumentthatarespecifie
44、dafterthecommandnamearethenamesoffilesonwhichthecommandistooperate.EXAMPLES%rmfilelfile2file3Often,wewanttooperateonagroupofrelatedfilesordirectories.Wecanspecifygroupsofpathnamesbymeansofpatternscontainingspecialcharacterscalledmetacharactersorwildcardscharacters.METACHARACTERSALSoALLOWUSTo abbrevi
45、atelongpathnames. toaccessobjectswhosenamescontainunprintable(control)characters.FlLENAMEEXPANSIoNMETACHARAeTERSSymbolMeaning9Matchesanysinglecharacter,(e.g.:Isiee?)*Matchesanystringofcharactersofanylength,(e.g.:lsidworkfile*.bak)Matchesanyofthecharactersenclosedwithinthesquarebrackets,(e.g.:Isiei(adr?)fcl-c2Matchesanycharacterbetweenclandc2(inclus