编程bash

bash  时间:2021-01-31  阅读:()
Shell编程陈伟IndexTheshellofLinuxBourneShellProgrammingfind.
and.
regular.
expressiontextmanipulation*Shell编程TheshellofLinuxBourneshell(sh),Cshell(csh),Kornshell(ksh),TCshell(tcsh),BourneAgainshell(bash)*Shell编程DifferencebetweenprogrammingandscriptinglanguagesProgramminglanguagesaregenerallyalotmorepowerfulandalotfasterthanscriptinglanguages.
Programminglanguagesgenerallystartfromsourcecodeandarecompiledintoanexecutable.
Thisexecutableisnoteasilyportedintodifferentoperatingsystems.
Ascriptinglanguagealsostartsfromsourcecode,butisnotcompiledintoanexecutable.
Rather,aninterpreterreadstheinstructionsinthesourcefileandexecuteseachinstruction.
Interpretedprogramsaregenerallyslowerthancompiledprograms.
Themainadvantageisthatyoucaneasilyportthesourcefiletoanyoperatingsystem.
*Shell编程ThefirstbashprogramWemustknowhowtouseatexteditor.
TherearetwomajortexteditorsinLinux:vi,emacs(orxemacs).
Sofireupatexteditor;forexample:$vi&andtypethefollowinginsideit:#!
/bin/bashecho"HelloWorld"ThefirstlinetellsLinuxtousethebashinterpretertorunthisscript.
Wecallithello.
sh.
Then,makethescriptexecutable:$chmod700hello.
sh$ls–l-rwx------hello.
sh*Shell编程ThefirstbashprogramToexecutetheprogram:$hello.
sh-bash:hello.
sh:commandnotfoundThehomedirectory(wherethecommandhello.
shislocated)isnotinthevariablePATHecho$PATH:bin:/usr/bin:…Wemustspecifythepathofhello.
sh$/home/srinaldi/Scripts/hello.
sh$.
/hello.
sh*Shell编程ThesecondbashprogramWewriteaprogramthatcopiesallfilesintoadirectory,andthendeletesthedirectoryalongwithitscontents.
Thiscanbedonewiththefollowingcommands:$mkdirtrash$cp*trash$rm-rftrash$mkdirtrashInsteadofhavingtotypeallthatinteractivelyontheshell,writeashellprograminstead:$cattrash#!
/bin/bash#thisscriptdeletessomefilescp*trashrm-rftrashmkdirtrashecho"Deletedallfiles!
"*Shell编程VariablesWecanusevariablesasinanyprogramminglanguages.
Theirvaluesarealwaysstoredasstrings,buttherearemathematicaloperatorsintheshelllanguagethatwillconvertvariablestonumbersforcalculations.
Wehavenoneedtodeclareavariable,justassigningavaluetoitsreferencewillcreateit.
Example#!
/bin/bashSTR="HelloWorld!
"echo$STRLine2createsavariablecalledSTRandassignsthestring"HelloWorld!
"toit.
Thenthevalueofthisvariableisretrievedbyputtingthe'$'inatthebeginning.
*Shell编程Warning!
Theshellprogramminglanguagedoesnottype-castitsvariables.
Thismeansthatavariablecanholdnumberdataorcharacterdata.
count=0count=SundaySwitchingtheTYPEofavariablecanleadtoconfusionforthewriterofthescriptorsomeonetryingtomodifyit,soitisrecommendedtouseavariableforonlyasingleTYPEofdatainascript.
\isthebashescapecharacteranditpreservestheliteralvalueofthenextcharacterthatfollows.
$ls\*ls:*:Nosuchfileordirectory*Shell编程SingleandDoubleQuoteWhenassigningcharacterdatacontainingspacesorspecialcharacters,thedatamustbeenclosedineithersingleordoublequotes.
Usingdoublequotes(partialquoting)toshowastringofcharacterswillallowanyvariablesinthequotestoberesolved$var="teststring"$newvar="Valueofvaris$var"$echo$newvarValueofvaristeststringUsingsinglequotes(fullquoting)toshowastringofcharacterswillnotallowvariableresolution$var='teststring'$newvar='Valueofvaris$var'$echo$newvarValueofvaris$var*Shell编程Examples$pippo=pluto$pippo=pluto$ls[Pp]*$ls"[Pp]*"$ls'[Pp]*'$var=echo$var$echo"$var"$echo'$var'$echo\z#z$echo\\z#\z$echo'\\z'zmistakeNotresolved*Shell编程Examples$pippo=cat$echo"comando=\"$pippo\""comando="cat"$echo'comando=\"$pippo\"'comando=\"$pippo\"$echo'comando="$pippo"'comando="$pippo"*Shell编程TheexportcommandTheexportcommandputsavariableintotheenvironmentsoitwillbeaccessibletochildprocesses.
Forinstance:$x=hello$bash#Runachildshell.
$echo$x#Nothinginx.
$exit#Returntoparent.
$exportx$bash$echo$xhello#It'sthere.
Ifthechildmodifiesx,itwillnotmodifytheparent'soriginalvalue.
Verifythisbychangingxinthefollowingway:$x=ciao$exit$echo$xhello*Shell编程EnvironmentalVariablesTherearetwotypesofvariables:LocalvariablesEnvironmentalvariablesEnvironmentalvariablesaresetbythesystemandcanusuallybefoundbyusingtheenvcommand.
Environmentalvariablesholdspecialvalues.
Forinstance,$echo$SHELL/bin/bash$echo$PATH/usr/X11R6/bin:/usr/local/bin:/bin:/usr/binEnvironmentalvariablesaredefinedin/etc/profile,/etc/profile.
d/and~/.
bash_profile.
Thesefilesaretheinitializationfilesandtheyarereadwhenbashshellisinvoked.
Whenaloginshellexits,bashreads~/.
bash_logout*Shell编程EnvironmentalVariablesHOME:Thedefaultargument(homedirectory)forcd.
PATH:Thesearchpathforcommands.
Itisacolon-separatedlistofdirectoriesthataresearchedwhenyoutypeacommand.
Usually,wetypeinthecommandsinthefollowingway:$.
/trash.
shBysettingPATH=$PATH:.
ourworkingdirectoryisincludedinthesearchpathforcommands,andwesimplytype:$trash.
sh*Shell编程LOGNAME:containstheusernameHOSTNAME:containsthecomputername.
MACHTYPE:systemharwarePS1:sequenceofcharactersshownbeforetheprompt\thour\ddate\wcurrentdirectory\Wlastpartofthecurrentdirectory\uusername\$promptcharacterExample[rinaldi@homelinuxrinaldi]$PS1='ciao\u*'ciaorinaldi*_UID:containstheidnumberoftheuser(cannotbechanged).
SHLVL:containstheshelllevelEnvironmentalVariablesShell编程*ExitTheexitcommandmaybeusedtoterminateascript.
Itcanalsoreturnavalue,whichisavailabletothescript'sparentprocess.
Whenascriptendswithexitnnnnnn=0-255theexitstatusisnnn*Shell编程ReadcommandThereadcommandallowsyoutopromptforinputandstoreitinavariable.
Example(read.
sh)#!
/bin/bashecho-n"Enternameoffiletodelete:"readfileecho"Type'y'toremoveit,'n'tochangeyourmind.
.
.
"rm-i$fileecho"ThatwasYOURdecision!
"Line3createsavariablecalledfileandassignstheinputfromkeyboardtoit.
Thenthevalueofthisvariableisretrievedbyputtingthe'$'inatitsbeginning.
*Shell编程ReadcommandOptionsread–s(doesnotechoinput)read–nN(acceptsonlyNcharactersofinput)read–p"message"(promptsmessage)read–tT(acceptsinputforTseconds)Example$read–s–n1-p"Yes(Y)ornot(N)"answerYes(Y)ornot(N)Y$echo$answerY*Shell编程CommandSubstitutionThebackquote"`"isdifferentfromthesinglequote"".
Itisusedforcommandsubstitution:`command`$LIST=`ls`$echo$LISThello.
shread.
shPS1="`pwd`>"/home/rinaldi/didattica/>Wecanperformthecommandsubstitutionbymeansof$(command)$LIST=$(ls)$echo$LISThello.
shread.
shrm$(find/-name"*.
tmp")ls$(pwd)ls$(echo/bin)*Shell编程Example$a=`echoHello`$echo$a$echo'$a'$b=`ls/home`$echo$b$echo$a$b$echo"$a$b"*Shell编程ArithmeticOperators+plus-minus*multiplication/division**exponentiation%moduloExample$a=(5+2)*3$echo$a$b=2**3$echo$a+$b*Shell编程ArithmeticEvaluationTheletstatementcanbeusedtodomathematicalfunctions:$letX=10+2*7$echo$X24$letY=X+2*4$echo$Y32Anarithmeticexpressioncanbeevaluatedby$[expression]or$((expression))$echo$((123+20))143$VALORE=$[123+20]$echo$[123*$VALORE]1430$echo$[2**3]$echo$[8%3]Notnecessarytouse$XtorefertothevalueofX*Shell编程ArithmeticEvaluationExample(operations.
sh)#!
/bin/bashecho-n"Enterthefirstnumber:";readxecho-n"Enterthesecondnumber:";readyadd=$(($x+$y))sub=$(($x-$y))mul=$(($x*$y))div=$(($x/$y))mod=$(($x%$y))#printouttheanswers:echo"Sum:$add"echo"Difference:$sub"echo"Product:$mul"echo"Quotient:$div"echo"Remainder:$mod"*Shell编程ConditionalStatementsConditionalsletwedecidewhethertoperformanactionornot,thisdecisionistakenbyevaluatinganexpression.
Themostbasicformis:if[expression];thenstatementselif[expression];thenstatementselsestatementsfitheelif(elseif)andelsesectionsareoptional*Shell编程ExpressionsAnexpressioncanbe:Stringcomparison,Numericcomparison,FileoperatorsandLogicaloperatorsanditisrepresentedby[expression]:StringComparisons:=compareiftwostringsareequal!
=compareiftwostringsarenotequal-nevaluateifstringlengthisgreaterthanzero-zevaluateifstringlengthisequaltozeroExamples:[s1=s2](trueifs1sameass2,elsefalse)[s1!
=s2](trueifs1notsameass2,elsefalse)[s1](trueifs1isnotempty,elsefalse)[-ns1](trueifs1hasalengthgreaterthen0,elsefalse)[-zs2](trueifs2hasalengthof0,otherwisefalse)*Shell编程ExpressionsNumberComparisons:-eqcompareiftwonumbersareequal-gecompareifonenumberisgreaterthanorequaltoanumber-lecompareifonenumberislessthanorequaltoanumber-necompareiftwonumbersarenotequal-gtcompareifonenumberisgreaterthananothernumber-ltcompareifonenumberislessthananothernumberExamples:[n1-eqn2](trueifn1sameasn2,elsefalse)[n1-gen2](trueifn1greaterthenorequalton2,elsefalse)[n1-len2](trueifn1lessthenorequalton2,elsefalse)[n1-nen2](trueifn1isnotsameasn2,elsefalse)[n1-gtn2](trueifn1greaterthenn2,elsefalse)[n1-ltn2](trueifn1lessthenn2,elsefalse)*Shell编程#!
/bin/bash#if0.
shecho-n"Enteryourloginname:"readnameif["$name"="$USER"];thenecho"Hello,$name.
Howareyoutoday"elseecho"Youarenot$USER,sowhoareyou"fi*Shell编程#!
/bin/bash#if1.
shecho-n"Enteranumber1bashif[-f/etc/fstab];thencp/etc/fstab.
echo"Done.
"elseecho"Thisfiledoesnotexist.
"exit1fiExercise.
Writeashellscriptwhichacceptsafilename:Thescriptchecksiffileexists,andcreatesadirectoryBackupIffileexists,copiesthefiletothesamename+.
bak(ifthe.
bakfilealreadyexistsaskifyouwanttoreplaceit).
Ifthefiledoesnotexistthenexitswiththemessage"Thefiledoesnotexist!
!
!
"*Shell编程Solution#!
/bin/bashif[!
–d.
/Backup]thenmkdir.
/Backupfiread–p"insertthenameofafile"pippoif[-f$pippo]thencp$pippo.
/Backup/$pippo.
bakelseecho"Thefile$pippodoesnotexist!
!
!
"fi*Shell编程ExpressionsLogicaloperators:!
negate(NOT)alogicalexpression-alogicallyANDtwologicalexpressions-ologicallyORtwologicalexpressions#!
/bin/bash#if3.
shecho-n"Enteranumber1bash#if4.
shecho-n"Enteranumber1bashecho"Enterapath:";readxifcd$x2>/dev/nullthenecho"Iamin$xanditcontains";lselseecho"Thedirectory$xdoesnotexist";exit1fi$.
/iftrue.
shEnterapath:/homesrinaldiafrosiniriccardo…$.
/iftrue.
shEnterapath:pippoThedirectorypippodoesnotexist*Shell编程ShellParametersPositionalparametersareassignedfromtheshell'sargumentwhenitisinvoked.
Positionalparameter"N"maybereferencedas"${N}",oras"$N"when"N"consistsofasingledigit.
Specialparameters$#isthenumberofparameterspassed$0returnsthenameoftheshellscriptrunningaswellasitslocationinthefilesystem$*givesasinglewordcontainingalltheparameterspassedtothescript$@givesanarrayofwordscontainingalltheparameterspassedtothescript$catsparameters.
sh(sparameters.
sh)#!
/bin/bashecho"$#;$0;$1;$2;sparameters.
shalbachiara2;.
/sparameters.
sh;alba;chiara;albachiara;albachiara*Shell编程Trash$cattrash.
sh(trash.
sh)#!
/bin/bashif[$#-eq1];thenif[!
–d"$HOME/trash"];thenmkdir"$HOME/trash"fimv$1"$HOME/trash"elseecho"Use:$0filename"exit1fi*Shell编程CaseStatementUsedtoexecutestatementsbasedonspecificvalues.
Oftenusedinplaceofanifstatementiftherearealargenumberofconditions.
Valueusedcanbeanexpressioneachsetofstatementsmustbeendedbyapairofsemicolons;a*)isusedtoacceptanyvaluenotmatchedwithlistofvaluescase$varinval1)statements;;val2)statements;;*)statements;;esac*Shell编程Example#!
/bin/bash(case.
sh)echo-n"Enteranumber1bashletsum=0fornumin12345dolet"sum=$sum+$num"doneecho$sum*Shell编程IterationStatements:#!
/bin/bashforxinpaperpencilpen;doecho"Thevalueofvariablexis:$x"sleep1done#Thevalueofvariablexispaper#Thevalueofvariablexispencil#Thevalueofvariablexispen#!
/bin/bashforxin"paperA4""pencilSTADTLER""penBIC";doecho"Thevalueofvariablexis:$x"sleep1done#ThevalueofvariablexispaperA4#ThevalueofvariablexispencilSTADTLER#ThevalueofvariablexispenBIC*Shell编程IterationStatements:#!
/bin/bashlista="antoniomichelepaololuca"forxin$listadoecho"Thevalueofvariablexis:$x"sleep1done#Thevalueofvariablexisantonio#Thevalueofvariablexismichele#Thevalueofvariablexispaolo#Thevalueofvariablexisluca*Shell编程IterationStatements:#!
/bin/bashforxin*dols-l"$x"sleep1done#Listsallfilesincurrentdirectory#!
/bin/bashforxin/bindols-l"$x"done#Listsallfilesin/bin*Shell编程IterationStatements:#!
/bin/bashread–p"Insertthenameofadirectory"directoryecho"symboliclinksindirectory\"$directory\""forfilein$(find$directory-typel)#-typel=symboliclinksdoecho"$file"done|sort#Otherwisefilelistisunsorted*Shell编程IterationStatements:ifthelistpartisleftoff,varissettoeachparameterpassedtothescript($1,$2,$3,…)$catfor1.
sh(for1.
sh)#!
/bin/bashforxdoecho"Thevalueofvariablexis:$x"sleep1done$for1.
shalbachiaraThevalueofvariablexis:albaThevalueofvariablexis:chiara*Shell编程Example1#!
/bin/bash(old.
sh)#Movethecommandlineargfilestoolddirectory.
if[$#-eq0]#checkforcommandlineargumentsthenecho"Usage:$0file…"exit1fiif[!
–d"$HOME/old"]thenmkdir"$HOME/old"fiechoThefollowingfileswillbesavedintheolddirectory:echo$*forpin$*#loopthroughallcommandlineargumentsdomv$p"$HOME/old/"chmod400"$HOME/old/$p"donels-l"$HOME/old"*Shell编程Example2#!
/bin/bash(args.
sh)#Invokethisscriptwithseveralarguments:"onetwothree"if[!
-n"$1"];thenecho"Usage:$0arg1arg2.
.
.
";exit1fiecho;index=1;echo"Listingargswithforargin"$*";doecho"Arg$index=$arg"let"index+=1"#increasevariableindexbyonedoneecho"Entirearglistseenassingleword.
"echo;index=1;echo"Listingargswithforargin"$@";doecho"Arg$index=$arg"let"index+=1"doneecho"Arglistseenasseparatewords.
";exit0*Shell编程Operationsonvabiables…….
let"index+=5"#incrementindexby5……+=#incrementvariable-=#decrementvariable*=#multiplyvariable/=#dividevariable*Shell编程UsingArrayswithLoopsInthebashshell,wemayusearrays.
Thesimplestwaytocreateoneisusingoneofthetwosubscripts:pet[0]=dogpet[1]=catpet[2]=fishpet[4]=applepet=(dogcatfishapple)Wemayhaveupto1024elements.
Toextractavalue,type${arrayname[i]}$echo${pet[0]}dog$echo${pet[2]}fish*Shell编程ArraysToextractalltheelements,useanasteriskas:echo${arraynames[*]}Toseehowmanyelementsareinthearray:echo${#arraynames[*]}Wecancombinearrayswithloopsusingaforloop:forxin${arrayname[*]}doecho${arrayname[$x]}done*Shell编程AC-likeforloopAnalternativeformoftheforstructureisfor((EXPR1;EXPR2;EXPR3))dostatementsdoneFirst,thearithmeticexpressionEXPR1isevaluated.
EXPR2isthenevaluatedrepeatedlyuntilitevaluatesto0.
EachtimeEXPR2isevaluatestoanon-zerovalue,statementsareexecutedandEXPR3isevaluated.
$catfor2.
sh#!
/bin/bashecho–n"Enteranumber:";readxletsum=0for((i=1;$iBashprovidestwooptionswhichwillgiveusefulinformationfordebugging-v:displayseachlineofthescriptastypedbeforeexecution-x:displayseachlinebeforeexecution(abbreviated)Usage:#!
/bin/bash–v,or#!
/bin/bash–x$catfor3.
sh#!
/bin/bash–xecho–n"Enteranumber:";readxletsum=0for((i=1;$ibash-x#ex74.
sha=37if[$a-gt27]thenecho$afiexit0Outputfromscript:+a=37+'[37'-gt37']'+.
/ex74.
sh:[37:commandnotfound….
*Shell编程WhileStatementsThewhilestructureisaloopingstructure.
Usedtoexecuteasetofcommandswhileaspecifiedconditionistrue.
Theloopterminatesassoonastheconditionbecomesfalse.
Ifconditionneverbecomesfalse,loopwillneverexit.
whileexpressiondostatementsdone$catwhile.
sh(while.
sh)#!
/bin/bashecho–n"Enteranumber:";readxletsum=0;leti=1while[$i–le$x];dolet"sum=$sum+$i"i=$i+1doneecho"thesumofthefirst$xnumbersis:$sum"*Shell编程Menu#!
/bin/bash#menu.
shclear;loop=ywhile["$loop"=y];doecho"Menu";echoecho"D:printthedate"echo"W:printtheuserswhoarecurrentlylogon.
"echo"P:printtheworkingdirectory"echo"Q:quit.
"echoread–schoicecase$choiceinD|d)date;;W|w)who;;P|p)pwd;;Q|q)loop=n;;*)echo"Illegalchoice.
";;esacechodone*Shell编程FindaPatternandEdit$catgrep_edit.
sh#!
/bin/bash#grep_edit.
sh#Editargumentfiles$2.
.
.
,thatcontainpattern$1if[$#-le1]thenecho"Usage:$0patternfile…";exit1elsepattern=$1#Saveoriginal$1shift#shiftthepositionalparametertotheleftby1while[$#-gt0]#New$1isfirstfilenamedogrep"$pattern"$1>/dev/nullif[$-eq0];then#Ifgrepfoundpatternvi$1#thenvithefilefishiftdonefi$grep_edit.
shwhile~*Shell编程ContinueStatementsThecontinuecommandcausesajumptothenextiterationoftheloop,skippingalltheremainingcommandsinthatparticularloopcycle.
#!
/bin/bashLIMIT=19echoecho"PrintingNumbers1through20(butnot3and11)"a=0while[$a-le"$LIMIT"];doa=$(($a+1))if["$a"-eq3a"-eq11]thencontinuefiecho-n"$a"done*Shell编程BreakStatementsThebreakcommandterminatestheloop(breaksoutofit).
#!
/bin/bashLIMIT=19echo"PrintingNumbers1through20,butsomethinghappensafter2…"a=0while[$a-le"$LIMIT"];doa=$(($a+1))if["$a"-gt2]thenbreakfiecho-n"$a"doneecho;echo;echoexit0*Shell编程UntilStatementsTheuntilstructureisverysimilartothewhilestructure.
Theuntilstructureloopsuntiltheconditionistrue.
Sobasicallyitis"untilthisconditionistrue,dothis".
until[expression]dostatementsdone$catcountdown.
sh#!
/bin/bash#countdown.
sh#echo"Enteranumber:";readxecho;echoCountDownuntil["$x"-le0];doecho$xx=$(($x–1))sleep1doneecho;echoGO!
*Shell编程ManipulatingStringsBashsupportsasurprisingnumberofstringmanipulationoperations.
Unfortunately,thesetoolslackaunifiedfocus.
${#string}givesthestringlength${string:position}extractssub-stringfrom$stringat$position${string:position:length}Extracts$lengthcharactersofsub-stringfrom$stringat$positionExample$st=0123456789$echo${#st}10$echo${st:6}6789$echo${st:6:2}67*Shell编程ParameterSubstitutionManipulatingand/orexpandingvariables${parameter-default},Ifparameternotset,usedefault.
$echo${username-`whoami`}rinaldi$username=simone$echo${username-`whoami`}simone${parameter=default},Ifparameternotset,setittodefault.
$echo${username=`whoami`}$echo$usernamerinaldi${parameter+value},Ifparameterset,usevalue,elseusenullstring.
$echo${username+andrea}andrea$echo${pippo+andrea}nullstring*Shell编程ParameterSubstitution${parametermsg},Ifparameterset,useit,elseprintmsg$value=${total'totalisnotset'}total:totalisnotset$total=10$value=${total'totalisnotset'}$echo$value10Example:#!
/bin/bashOUTFILE=symlinks.
listdirectory=${1-`pwd`}forfilein"$(find$directory-typel)"doecho"$file"done|sort>>"$HOME/$OUTFILE"exit0*Shell编程Advancedoperationsonstrings${string#substring},stripstheshortestmatchofsubstringfromthefrontofstring.
pippo=abbcaabccbcabcdbcdabaecho${pippo#a*c}#aabccbcabcdbcdabaecho${pippo##a*c}stripsthelongestmatch#daba${string%substring},stripstheshortestmatchofsubstringfromthefrontofstring.
*Shell编程Advancedoperationsonstrings${string/substring/replacement},stripsthefirstmatchofsubstringinstringwithreplacement.
pippo=abbcaabccbcabcdbcdababecho${pippo/ca/11}#abb11abccbcabcdbcdababecho${pippo//ca/11}#abb11abccb11bcdbcdabab#replacesallmatchesecho${pippo/[ab]c/000}#a000aabccbcabcdbcdababecho${pippo/c*a/\!
}#abbc!
becho${pippo//b/00}#a00caa00c00a00d00da00b*Shell编程FunctionsFunctionsmakescriptseasiertomaintain.
Basicallyitbreaksuptheprogramintosmallerpieces.
Afunctionperformsanactiondefinedbyyou,anditcanreturnavalueifyouwish.
#!
/bin/bashhello(){echo"Youareinfunctionhello()"}echo"Callingfunctionhello()…"helloecho"Youarenowoutoffunctionhello()"Intheabove,wecalledthehello()functionbynamebyusingtheline:hello.
Whenthislineisexecuted,bashsearchesthescriptforthelinehello().
Itfindsitrightatthetop,andexecutesitscontents.
*Shell编程Functions#!
/bin/bashfunctioncheck(){if[-e"/home/$1"]thenreturn0elsereturn1fi}echo"Enterthenameofthefile:";readxifcheck$xthenecho"$xexists!
"elseecho"$xdoesnotexists!
"fi.
*Shell编程GreatestCommonDivisor#!
/bin/bash#gcd.
sh:greatestcommondivisor#UsesEuclid'salgorithm#The"greatestcommondivisor"(gcd)oftwointegersisthelargestinteger#thatwilldivideboth,leavingnoremainder.
#Euclid'salgorithmusessuccessivedivision.
#Ineachpass,dividendbash#Counthowmanyelements.
Suites="ClubsDiamondsHeartsSpades"Denominations="2345678910JackQueenKingAce"#Readintoarrayvariable.
suite=($Suites)denomination=($Denominations)#Counthowmanyelements.
num_suites=${#suite[*]}num_denominations=${#denomination[*]}echo-n"${denomination[$((RANDOM%num_denominations))]}of"echo${suite[$((RANDOM%num_suites))]}exit0*Shell编程Script2:Changesallfilenamestolowercase#!
/bin/bashforfilenamein*#Traverseallfilesindirectory.
dofname=`basename$filename`#Changenametolowercase.
n=`echo$fname|trA-Za-z`if["$fname"!
="$n"]#Renameonlyfilesnotalreadylowercase.
thenmv$fname$nfidoneexit0*Shell编程Script3:Comparetwofileswithascript#!
/bin/bashARGS=2#Twoargstoscriptexpected.
if[$#-ne"$ARGS"];thenecho"Usage:`basename$0`file1file2";exit1fiif[[!
-r"$1"||!
-r"$2"]];thenecho"Bothfilesmustexistandbereadable.
";exit2ficmp$1$2&>/dev/null#/dev/nullburiestheoutputofthe"cmp"command.
#Alsoworkswith'diff',i.
e.
,diff$1$2&>/dev/nullif[$-eq0]#Testexitstatusof"cmp"command.
thenecho"File\"$1\"isidenticaltofile\"$2\".
"elseecho"File\"$1\"differsfromfile\"$2\".
"fiexit0*Shell编程Exercise#!
/bin/bashMAX=10000for((nr=1;nrbash".
BashistheshellthatwillappearintheGNUoperatingsystem.
Bashisansh-compatibleshellthatincorporatesusefulfeaturesfromtheKornshell(ksh)andCshell(csh).
bashisnotonlyanexcellentcommandlineshell,butascriptinglanguageinitself.
Shellscriptingallowsustousetheshell'sabilitiesandtoautomatealotoftasksthatwouldotherwiserequirealotofcommands.
*Shell编程BorneShellBackgroundEarlyUnixshellthatwaswrittenbySteveBourneofAT&TBellLab.
BasicshellprovidedwithmanycommercialversionsofUNIXManysystemshellscriptsarewrittentorununderBourneShellAlongandsuccessfulhistoryShell编程*BourneShellProgrammingControlstructuresif…thenfor…inwhileuntilcasebreakandcontinueShell编程*if…thenStructureiftest-commandthencommandsfiExample:iftest"$word1"="$word2"thenecho"Match"fi*Shell编程testCommandtestisabuilt-incommandSyntaxtestexpression[expression]ThetestcommandevaluateanexpressionReturnsaconditioncodeindicatingthattheexpressioniseithertrue(0)orfalse(not0)ArgumentExpressioncontainsoneormorecriteriaLogicalANDoperatortoseparatetwocriteria:-aLogicalORoperatortoseparatetwocriteria:-oNegateanycriterion:!
GroupcriteriawithparenthesesSeparateeachelementwithaSPACE*Shell编程TestCriteriaTestOperatorforintegers:int1relopint2RelopDescription-gtGreaterthan-geGreaterthanorequalto-eqEqualto-neNoteuqalto-leLessthanorequalto-ltLessthan*Shell编程ExerciseCreateashellscripttocheckthereisatleastoneparameterSomethinglikethis:…iftest$#-eq0thenecho"youmustsupplyatleastonearguments"exit1fi…*Shell编程TestCriteriaThetestbuilt-inoptionsforfilesOptionTestPerformedonfile-dfilenameExistsandisadirectoryfile-ffilenameExistsandisaregularfile-rfilenameExistsanditreadable-sfilenameExistsandhasalengthgreaterthan0-ufilenameExistsandhassetuidbitset-wfilenameExistsanditwritable-xfilenameExistsanditisexecutable…………*Shell编程ExerciseCheckweatherornottheparameterisanon-zeroreadablefilenameContinuewiththepreviousscriptandaddsomethinglikeif[-r"$filename"–a–s"$filename"]then……fi*Shell编程TestCriteriaStringtestingCriteriameaningStringTrueifstringisnotthenullstring-nstringTrueifstringhasalengthgreaterthanzero-zstringTrueifstringhasalengthofzeroString1=string2Trueifstring1isequaltostring2String1!
=string2Trueifstring1isnotequaltostring2*Shell编程ExerciseCheckusersconfirmationFrist,readuserinputecho-n"Pleaseconfirm:[Yes|No]"readuser_inputThen,compareitwithstandardanswer'yes'if["$user_input"=Yes]thenecho"Thanksforyourconfirmation!
"Fi*Shell编程if…then…elseStructureiftest-commandthencommandselsecommandsfiYoucanusesemicolon(;)endsacommandthesamewayaNEWLINEdoes.
if[…];then……fiif[5=5];thenecho"equal";fi*Shell编程if…then…elifStructureiftest-commandthencommandseliftest-commandthencommandselsecommandsfi*Shell编程DebuggingShellScriptsDisplayeachcommandbeforeitrunsthecommandSetthe–xoptionforthecurrentshell$set–xUsethe–xtoinvokethescript$sh–xcommandargumentsAddthesetcommandatthetopofthescriptset–xTheneachcommandthatthescriptexecutesisprecededbyaplussign(+)DistinguishtheoutputoftracefromanyoutputthatthescriptproducesTurnoffthedebugwithset+x*Shell编程for…inStructureforloop-indexinargument_listdocommandsdoneExample:forfilein*doif[-d"$file"];thenecho$filefidone*Shell编程forStructureforloop-indexdocommandsdoneAutomaticallytakesonthevalueofeachofcommandlinearguments,oneatatime.
Whichimpliesforargin"$@"*Shell编程whileStructurewhiletest_commanddocommandsdoneExample:while["$number"–lt10]donumber=`expr$number+1`done*Shell编程untilStructureuntiltest_commanddocommandsdoneExample:secretname=jennyname=nonameuntil["$name"="$secretname"]doecho"Yourguess:\c"readnamedone*Shell编程breakandcontinueInterruptfor,whileoruntilloopThebreakstatementtransfercontroltothestatementAFTERthedonestatementterminateexecutionoftheloopThecontinuestatementTransfercontroltothestatementTOthedonestatementSkiptheteststatementsforthecurrentiterationContinuesexecutionoftheloop*Shell编程Example:forindexin12345678910doif[$index–le3];thenechocontinuecontinuefiecho$indexif[$index–ge8];thenecho"break"breakfidone*Shell编程caseStructurecasetest_stringinpattern-1)commands_1;;pattern-2)commands_2;;……esacdefaultcase:catchallpattern*)*Shell编程caseSpecialcharactersusedinpatternsPatternMatches*Matchesanystringofcharacters.
Matchesanysinglecharacter.
[…]Definesacharacterclass.
Ahyphenspecifiesarangeofcharacters|Separatesalternativechoicesthatsatisfyaparticularbranchofthecasestructure*Shell编程Example#!
/bin/shecho"\nCommandMENU\n"echo"a.
Currentdataandtime"echo"b.
Userscurrentlyloggedin"echo"c.
Nameoftheworkingdirectory\n"echo"Entera,b,orc:\c"readanswerechocase"$answer"ina)date;;b)who;;c)pwdecho"Thereisnoselection:$answer"esac*Shell编程echoandreadThebackslashquotedcharactersinecho\csuppressthenewline\nnewline\rreturn\ttabReadreadvariable1[variable2…]ReadonelineofstandardinputAssigneachwordtothecorrespondingvariable,withtheleftoverwordsassignedtolastvariablesIfonlyonevariableisspecified,theentirelinewillbeassignedtothatvariable.
*Shell编程Example:bundle#!
/bin/sh#bundle:groupfilesintodistributionpackageecho"#ToUble,shthisfile"foridoecho"echo$i"echo"cat>$ioutfile2>errfileExample:sh-2.
05b$moreredirect.
shexec>/dev/ttyecho"thisisatestofredirection"sh-2.
05b$.
/redirect.
sh1>/dev/null2>&1thisisatestofredirection*Shell编程Catchasignal:builtintrapBuilt-intrapSyntax:trap'commands'signal-numbersShellexecutesthecommandswhenitcatchesoneofthesignalsThenresumesexecutingthescriptwhereitleftoff.
Justcapturethesignal,notdoinganythingwithittrap''signal_numberOftenusedtocleanuptempfilesSignalsSIGHUP1disconnectlineSIGINT2control-cSIGKILL9killwith-9SIGTERM15defaultkillSIGSTP24control-z…*Shell编程Example[ruihong@dafinn~/cs3451]$moreinter#!
/bin/shtrap'echoPROGRAMINTERRUPTED'2whiletruedoecho"programmingrunning.
sleep1done*Shell编程Apartiallistofbuilt-inbg,fg,jobsjobcontrolbreak,continuechangetheloopcd,pwdworkingdirectoryecho,readdisplay/readevalscanandevaluatethecommandexecexecuteaprogramexitexitfromcurrentshellexport,unsetexport/removeavalorfuntestcomparearguments*Shell编程Apartiallistofbuiltinkillsendsasignaltoaprocessorjobsetsetsflagorargumentshiftpromoteseachcommandlineargumenttimesdisplaystotaltimesforthecurrentshellandtraptrapsasignaltypeshowwhetherunixcommand,build-in,functionumaskfilecreationmaskwaitwaitsforaprocesstoterminate.
ulimitprintthevalueofoneormoreresourcelimits*Shell编程functionsAshellfunctionissimilartoashellscriptItstoresaseriesofcommandsforexecutionatalatertime.
TheshellstoresfunctionsinthememoryShellexecutesashellfunctioninthesameshellthatcalledit.
WheretodefineIn.
profileInyourscriptOrincommandlineRemoveafunctionUseunsetbuilt-in*Shell编程functionsSyntaxfunction_name(commands}Example:sh-2.
05b$whoson()>{>date>echo"userscurrentlyloggedon">who>}sh-2.
05b$whosonTueFeb123:28:44EST2005userscurrentlyloggedonruihong:0Jan3108:46ruihongpts/1Jan3108:54(:0.
0)ruihongpts/2Jan3109:02(:0.
0)*Shell编程Examplesh-2.
05b$more.
profilesetenv(if[$#-eq2theneval$1=$2export$1elseecho"usage:setenvNAMEVALUE"1>&2fi}sh-2.
05b$.
.
profilesh-2.
05b$setenvT_LIBRARY/usr/local/tsh-2.
05b$echo$T_LIBRARY/usr/local/t*Shell编程ExerciseLet'slookatsomesystemscripts/etc/init.
d/syslog/etc/init.
d/crond*Shell编程SummaryShellisaprogramminglanguageProgramswritteninthislanguagearecalledshellscripts.
VariableBuilt-inControlstructureFunctionCallutilitiesoutsideofshellfind,grep,awk*Shell编程

racknerd:美国大硬盘服务器(双路e5-2640v2/64g内存/256gSSD+160T SAS)$389/月

racknerd在促销美国洛杉矶multacom数据中心的一款大硬盘服务器,用来做存储、数据备份等是非常划算的,而且线路还是针对亚洲有特别优化处理的。双路e5+64G内存,配一个256G的SSD做系统盘,160T SAS做数据盘,200T流量每个月,1Gbps带宽,5个IPv4,这一切才389美元...洛杉矶大硬盘服务器CPU:2 * e5-2640v2内存:64G(可扩展至128G,+$64)硬...

印象云七夕促销,所有机器7折销售,美国CERA低至18元/月 年付217元!

印象云,成立于2019年3月的商家,公司注册于中国香港,国人运行。目前主要从事美国CERA机房高防VPS以及香港三网CN2直连VPS和美国洛杉矶GIA三网线路服务器销售。印象云香港三网CN2机房,主要是CN2直连大陆,超低延迟!对于美国CERA机房应该不陌生,主要是做高防服务器产品的,并且此机房对中国大陆支持比较友好,印象云美国高防VPS服务器去程是163直连、三网回程CN2优化,单IP默认给20...

快云科技,美国VPS 2H5G独享20M 仅售19.8/月  年付仅需148

快云科技已稳步运行进两年了 期间没出现过线路不稳 客户不满意等一系列问题 本司资质齐全 持有IDC ICP ISP等正规手续 有独特的网站设计理念 在前几天刚是参加过魔方系统举行的设计大赛拿获最佳设计奖第一名 本公司主营产品 香港弹性云服务器,美国vps和日本vps,香港物理机,国内高防物理机以及美国日本高防物理机 2020年的国庆推出过一款香港的回馈用户特惠机 已作为传家宝 稳定运行 马上又到了...

bash为你推荐
美团月付怎么关闭美团月账单消费记录怎撤除啊?p图软件哪个好用新手用哪个软件p图较好?锦天城和君合哪个好和君智业和三人禾哪个公司的营销做的好燃气热水器和电热水器哪个好燃气热水器与电热水器的优缺点?压缩软件哪个好压缩软件用哪个会比较好用录音软件哪个好手机录音软件哪个好用二手车网站哪个好卖二手车网站哪个好网页传奇哪个好玩求最好玩的网页传奇?尼康和佳能单反哪个好请问佳能和尼康的单反哪个好?云盘哪个好哪个网盘好用 而且下载速度快 还免费
vps优惠码cnyvps 如何查询域名备案号 hkbn 56折 域名优惠码 抢票工具 双11抢红包攻略 天猫双十一秒杀 dropbox网盘 ev证书 铁通流量查询 java虚拟主机 gg广告 100m免费空间 域名和空间 服务器维护 lamp兄弟连 测试网速命令 asp空间 侦探online 更多