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编程
目前,我们都在用哪个FTP软件?喜欢用的是WinSCP,是一款免费的FTP/SFTP软件。今天在帮助一个网友远程解决问题的时候看到他用的是FlashFXP FTP工具,这个工具以前我也用过,不过正版是需要付费的,但是网上有很多的绿色版本和破解版本。考虑到安全的问题,个人不建议选择破解版。但是这款软件还是比较好用的。今天主要是遇到他的虚拟主机无法通过FTP连接主机,这里我就帮忙看看到底是什么问题。一...
进入6月,各大网络平台都开启了618促销,腾讯云目前也正在开展618云上Go活动,上海/北京/广州/成都/香港/新加坡/硅谷等多个地区云服务器及轻量服务器秒杀,最低年付95元起,参与活动的产品还包括短信包、CDN流量包、MySQL数据库、云存储(标准存储)、直播/点播流量包等等,本轮秒杀活动每天5场,一直持续到7月中旬,感兴趣的朋友可以关注本页。活动页面:https://cloud.tencent...
速云怎么样?速云,国人商家,提供广州移动、深圳移动、广州茂名联通、香港hkt等VDS和独立服务器。现在暑期限时特惠,力度大。广州移动/深圳移动/广东联通/香港HKT等9折优惠,最低月付9元;暑期特惠,带宽、流量翻倍,深港mplc免费试用!点击进入:速云官方网站地址速云优惠码:全场9折优惠码:summer速云优惠活动:活动期间,所有地区所有配置可享受9折优惠,深圳/广州地区流量计费VDS可选择流量翻...
bash为你推荐
美国10次啦导航如何才能摧毁美国的Gps导航系统腾讯空间首页怎么才能让自己QQ空间被腾讯推荐在QQ空间首页里面?租车平台哪个好想网上租车,选什么平台好?视频剪辑软件哪个好常见好用的视频剪辑软件都有哪些?电脑管家和360哪个好电脑管家和360安全卫士哪个好手动挡和自动挡哪个好自动挡和手动挡哪个更好一点朱祁钰和朱祁镇哪个好大家怎么看明英宗和明代宗手机音乐播放器哪个好手机音乐播放器音质好的APP是那款苹果手机助手哪个好苹果手机助手哪个好用些谁知道炒股软件哪个好用股票交易软件哪个好?
淘宝二级域名 免费域名跳转 精品网 rak机房 wordpress技巧 evssl 双11秒杀 免费cdn 免费网页申请 web应用服务器 谷歌台湾 空间服务器 湖南铁通 godaddy退款 ipower windowsserver2012 瓦工工资 香港云主机 什么是云主机 服务器监测软件 更多