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编程
新网好不好?新网域名便宜吗?新网怎么样?新网是国内老牌知名域名注册商,企业正规化运营,资质齐全,与阿里云万网和腾讯云DNSPOD同为国内服务商巨头。近日新网发布了最新的七月放价季优惠活动,主要针对域名、云主机、企业邮箱、SSL证书等多款云产品推送了超值的优惠,其中.com顶级域名仅19.9元/首年,.cn域名仅16元/首年,云主机1核心2G内存3Mbps带宽仅9.9元/月,企业邮箱更是免费送1年,...
ZJI怎么样?ZJI是一家成立于2011年的商家,原名维翔主机,主要从事独立服务器产品销售,目前主打中国香港、日本、美国独立服务器产品,是一个稳定、靠谱的老牌商家。详情如下:月付/年付优惠码:zji??下物理服务器/VDS/虚拟主机空间订单八折终身优惠(长期有效)一、ZJI官网点击直达香港葵湾特惠B型 CPU:E5-2650L核心:6核12线程内存:16GB硬盘:480GB SSD带宽:5Mbps...
青云互联怎么样?青云互联是一家成立于2020年的主机服务商,致力于为用户提供高性价比稳定快速的主机托管服务,目前提供有美国免费主机、香港主机、韩国服务器、香港服务器、美国云服务器,香港安畅cn2弹性云限时首月五折,15元/月起;可选Windows/可自定义配置,让您的网站高速、稳定运行。点击进入:青云互联官方网站地址青云互联优惠码:八折优惠码:ltY8sHMh (续费同价)青云互联香港云服务器活动...
bash为你推荐
软银亏损65亿美元为什么软银市值不到500亿,却可以负债千亿帕萨特和迈腾哪个好2019帕萨特和迈腾哪个好?隔音怎么样?游戏盒子哪个好请问游戏盒子哪个好啊车险哪个好买汽车保险,买哪几种比较好红茶和绿茶哪个好红茶和绿茶 那个更好清理手机垃圾软件哪个好手机垃圾清理软件哪个好qq空间登录qq空间如何登陆51空间登录以前的51空间怎么进?辽宁联通网上营业厅中国移动辽宁营业厅dns服务器故障DNS服务解析故障 怎么办
免费网站域名注册 个人注册域名 北京域名空间 国外免费vps 免费主机 godaddy续费优惠码 evssl e蜗牛 有益网络 域名转向 卡巴斯基试用版 免费申请个人网站 gtt 华为云服务登录 1元域名 台湾google 网购分享 免费的域名 国外网页代理 web服务器有哪些 更多