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编程
10gbiz怎么样?10gbiz在本站也多次分享过,是一家成立于2020的国人主机商家,主要销售VPS和独立服务器,机房目前有中国香港和美国洛杉矶、硅谷等地,线路都非常不错,香港为三网直连,电信走CN2,洛杉矶线路为三网回程CN2 GIA,10gbiz商家七月连续推出各种优惠活动,除了延续之前的VPS产品4折优惠,目前增加了美国硅谷独立服务器首月半价的活动,有需要的朋友可以看看。10gbiz优惠码...
HostKvm商家我们也不用多介绍,这个服务商来自国内某商家,旗下也有多个品牌的,每次看到推送信息都是几个服务商品牌一起推送的。当然商家还是比较稳定的,商家品牌比较多,这也是国内商家一贯的做法,这样广撒网。这次看到黑五优惠活动发布了,针对其主打的香港云服务器提供终身6折的优惠,其余机房服务器依然是8折,另还有充值50美元赠送5美元的优惠活动,有需要的可以看看。HostKvm是一个创建于2013年的...
数脉科技(shuhost)8月促销:香港独立服务器,自营BGP、CN2+BGP、阿里云线路,新客立减400港币/月,老用户按照优惠码减免!香港服务器带宽可选10Mbps、30Mbps、50Mbps、100Mbps带宽,支持中文本Windows、Linux等系统。官方网站:https://www.shuhost.com* 更大带宽可在选购时选择同样享受优惠。* 目前仅提供HKBGP、阿里云产品,香港...
bash为你推荐
视频剪辑软件哪个好常见好用的视频剪辑软件都有哪些?电脑管家和360哪个好360和电脑管家哪个好轿车和suv哪个好SUV和轿车哪个好点?纠结法兰绒和珊瑚绒哪个好珊瑚绒和法兰绒哪个暖和手动挡和自动挡哪个好自动挡和手动挡哪个好?雅思和托福哪个好考雅思和托福哪个好考一点51空间登录51咋登录 咋登录好友的51空间qq空间登录不上为什么我登不进去QQ空间辽宁联通网上营业厅网辽宁省联通发短信查gprs流量方法东莞电信宽带套餐广东东莞电信宽带资费是怎么样的?
域名升级访问中 新网域名解析 阿里云搜索 arvixe hawkhost 电影服务器 jsp主机 特价空间 域名优惠码 好看的留言 炎黄盛世 怎样建立邮箱 双12 根服务器 移动服务器托管 带宽租赁 阿里云手机官网 如何登陆阿里云邮箱 中国联通宽带测试 云服务是什么意思 更多