modernish开源项目

我要开发同款
匿名用户2021年11月09日
110阅读

技术信息

开源地址
https://gitee.com/J_Sky/jiance
授权协议
ISC License

作品详情

Releases

Forcodeexamples,seeEXAMPLES.mdadshare/doc/moderish/examples

moderish–haresstheshellSickofquotighelladsplit/globpitfalls?Tiredofbrittleshellscriptsgoighaywireadcausigdamage?Mystifiedbylieoisecommadslike[,[[,((?Isscriptigbasicthigsjusttoohard?Everwishthatfidwereabuilt-ishellloop?DoyouwatyourscripttoworkoearlyayshelloayUix-likeOS?

Moderishisalibraryforshellscriptprogrammigwhichprovidesfeatureslikesafervariableadcommadexpasio,ewlaguagecostructsforloopiteratio,admuchmore.Moderishprogramsareshellprograms;theewcostructsaremixedwithshellsytaxsothattheprogrammercatakeadvatageofthebestofboth.

Thereisocompiledcodetoistall,asmoderishiswritteetirelyitheshelllaguage.Itcabedeployediembeddedormulti-usersystemsiwhichewbiaryexecutablesmayotbeitroducedforsecurityreasos,adisportableamogumerousshellimplemetatios.Theistallercaalsobudleareducedcopyofthelibrarywithyourscripts,sotheycaruportablywithakowversioofmoderishwithoutrequirigprioristallatio.

Joiusadhelpbreathesomeewlifeitotheshell!Wearelookigfortesters,earlyadopters,addeveloperstojoius.Dowloadthelatestreleaseorcheckouttheverylatestdevelopmetcodefromthemasterbrach.Readthroughthedocumetatiobelow.Playwiththeexamplescriptsadwriteyourow.Trytobreakthelibraryadsedreportsofbreakage.Commuicateviathegithubpage,orjoithemailiglists:moderish-dev,moderish-users,moderish-aouce.

TableofcotetsGettigstartedTwobasicformsofamoderishprogramSimpleformPortableformIteractiveuseNo-iteractivecommadlieuseNo-iteractiveusageexamplesShellcapabilitydetectioNamesadidetifiersIteralamespaceModerishsystemcostatsCotrolcharacter,whitespaceadshell-safecharactercostatsReliableemergecyhaltLow-levelshellutilitiesOutputtigstrigsLegibilityaliases:ot,so,foreverEhacedexitchdirisubshellissetsetstatusTestigumbers,strigsadfilesItegerumberarithmetictestsadoperatiosThearithmeticcommadletArithmeticshortcutsStrigadfiletestsStrigtestsUarystrigtestsBiarystrigmatchigtestsMulti-matchigoptioFiletypetestsFilecomparisotestsFilestatustestsI/OtestsFilepermissiotestsThestackTheshelloptiosstackThetrapstackModulesusesafeWhythesafemode?HowthesafemodeworksImportatotesforsafemodeExtraoptiosforthesafemodeusevar/loopSimplerepeatloopBASIC-stylearithmeticforloopC-stylearithmeticforloopEumerativefor/selectloopwithsafesplit/globThefidloopAvailableoptiosAvailablefid-expressiooperadsPickigafidutilityCompatibilitymodeforobsoletefidutilitiesfidloopusageexamplesCreatigyourowloopusevar/localImportatvar/localusageotesusevar/arithArithmeticoperatorshortcutsArithmeticcomparisoshortcutsusevar/assigusevar/readfusevar/shellquoteshellquoteshellquoteparamsusevar/stackusevar/stack/extrausevar/stack/trapTrapstackcompatibilitycosideratiosTheewDIEpseudosigalusevar/strigusevar/strig/touplowusevar/strig/trimusevar/strig/replaceiusevar/strig/appedusevar/uexportusevar/geoptparserusesys/baseusesys/base/mktempusesys/base/readlikusesys/base/revusesys/base/seqDiffereceswithGNUadBSDsequsesys/base/shufusesys/base/tacusesys/base/whichusesys/base/yesusesys/cmdusesys/cmd/exterusesys/cmd/hardeImportatoteovariableassigmetsHardeigwhileallowigforbrokepipesTracigtheexecutioofhardeedcommadsSimpletracigofcommadsusesys/cmd/maprDifferecesfrommapfileDifferecesfromxargsusesys/cmd/procsubstusesys/cmd/sourceusesys/dirusesys/dir/coutfilesusesys/dir/mkcdusesys/termusesys/term/putrusesys/term/readkeyAppedixA:ListofshellcapIDsCapabilitiesQuirksBugsWarigIDsAppedixB:RegressiotestsuiteDifferecebetweecapabilitydetectioadregressiotestsTestigmoderishoallyourshellsAppedixC:SupportedlocalesAppedixD:SupportedshellsAppedixE:zsh:itegratiowithativescriptsAppedixF:BudligmoderishwithyourscriptGettigstarted

Ruistall.shadfollowistructios,choosigyourpreferredshelladistalllocatio.Aftersuccessfulistallatioyoucarumoderishshellscriptsadwriteyourow.Ruuistall.shtoremovemoderish.

Boththeistalladuistallscriptsareiteractivebydefault,butsupportfullyautomated(o-iteractive)operatioaswell.Commadlieoptiosareasfollows:

istall.sh[-][-sshell][-f][-Ppathspec][-distallroot][-Dprefix][-Bscriptfile...]

-:o-iteractiveoperatio-s:specifydefaultshelltoexecutemoderish-f:forceucoditioalistallatioospecifiedshell-P:specifyaalterativeDEFPATHfortheistallatio(becareful;usuallyotrecommeded)-d:specifyrootdirectoryforistallatio-D:extradestiatiodirectoryprefix(forpackagers)-B:budlemoderishwithyourscripts(-Drequired,-implied),seeAppedixF

uistall.sh[-][-f][-distallroot]

-:o-iteractiveoperatio-f:delete*/moderishdirectorieseveiffilesleft-d:specifyrootdirectoryofmoderishistallatiotouistallTwobasicformsofamoderishprogram

Ithesimpleform,moderishisaddedtoascriptwritteforaspecificshell.Itheportableform,yourscriptisshell-agosticadmayruoayshellthatcarumoderish.

Simpleform

Thesimplestwaytowriteamoderishprogramistosourcemoderishasadotscript.Forexample,ifyouwriteforbash:

#!/bi/bash.moderishusesafeusesys/base...yourprogramstartshere...

Themoderishusecommadloadmoduleswithoptioalfuctioality.Thesafemoduleiitialisesthesafemode.Thesys/basemodulecotaismoderishversiosofcertaibasicbuto-stadardisedutilities(e.g.readlik,mktemp,which),guarateeigthatmoderishprogramsallhaveakowversioattheirdisposal.Therearemayothermodulesaswell.SeeModulesformoreiformatio.

Theabovemethodmakestheprogramdepedetooeparticularshell(ithiscase,bash).Soitisokaytomixadmatchfuctioalityspecifictothatparticularshellwithmoderishfuctioality.

(Ozsh,thereisawaytoitegratemoderishwithativezshscripts.SeeAppedixE.)

Portableform

Themostportablewaytowriteamoderishprogramistousethespecialgeerichashbagpathformoderishprograms.Forexample:

#!/usr/bi/evmoderish#!usesafe#!usesys/base...yourprogrambegishere...

Forportability,itisimportatthereisospaceafterevmoderish;NetBSDadOpeBSDcosidertrailigspacespartoftheame,soevwillfailtofidmoderish.

Aprogramithisformisexecutedbywhatevershelltheuserwhoistalledmoderishothelocalsystemchoseasthedefaultshell.Siceyouastheprogrammerca'tkowwhatshellthisis(otherthathefactthatitpassedsomerigorousPOSIXcompliacetestigexecutedbymoderish),aprogramithisformmustbestrictlyPOSIXcompliat–except,ofcourse,thatitshouldalsomakefulluseoftherichfuctioalityofferedbymoderish.

Notethatmodulesareloadediadifferetway:theusecommadsarepartofhashbagcommet(startigwith#!liketheiitialhashbagpath).Olysuchliesthatimmediatelyfollowtheiitialhashbagpathareevaluated;eveaemptylieibetweecausestheresttobeigored.Thisspecialwayofpre-loadigmodulesiseededtomakeayaliasestheydefieworkreliablyoallshells.

Iteractiveuse

Moderishisprimarilydesigedtoehaceshellprograms/scripts,butalsooffersfeaturesforuseiiteractiveshells.Foristace,theewrepeatloopcostructfromthevar/loopmodulecabequitepracticaltorepeataactioxtimes,adthesafemoduleoiteractiveshellsprovidescoveiecefuctiosformaipulatig,savigadrestorigthestateoffieldsplittigadglobbig.

Tousemoderishoyourfavouriteiteractiveshell,youhavetoaddittoyour.profile,.bashrcorsimilariitfile.

Importat:Upoiitialisig,moderishadaptsitselftoothersettigs,suchasthelocale.Italsoremovescertaialiasesthatmaykeepmoderishfromiitialisigproperly.Soyouhavetoorgaiseyour.profileorsimilarfileithefollowigorder:

first,defiegeeralsystemsettigs(PATH,locale,etc.);the,.moderishaduseaymodulesyouwat;thedefieaythigthatmaydepedomoderish,adsetyouraliases.No-iteractivecommadlieuse

Afteristallatio,themoderishcommadcabeivokedasifitwereashell,withthestadardcommadlieoptiosfromothershells(suchas-ctospecifyacommadorscriptdirectlyothecommadlie),plussomeehacemets.Theeffectisthattheshellchoseatistallatiotimewillberuehacedwithmoderishfuctioality.Itisotpossibletousemoderishasaiteractiveshellithisway.

Usage:

moderish[--use=module|shelloptio...][scriptfile][argumets]moderish[--use=module|shelloptio...]-c[script[me-ame[argumets]]]moderish--test[testoptio...]moderish[--versio|--help]

Ithefirstform,thescriptithefilescriptfileisloadedadexecutedwithayargumetsassigedtothepositioalparameters.

Ithesecodform,-cexecutesthespecifiedmoderishscript,optioallywiththeme-ameassigedto$MEadtheargumetsassigedtothepositioalparameters.

The--useoptiopre-loadsaygivemoderishmodulesbeforeexecutigthescript.Themoduleargumettoeachspecified--useoptioissplitusigstadardshellfieldsplittig.Thefirstfieldisthemoduleameadayfurtherfieldsbecomeargumetstothatmodule'siitialisatioroutie.

Aygiveshort-formorlog-formshelloptiosaresetorusetbeforeexecutigthescript.BothPOSIXshelloptiosadshell-specificoptiosaresupported,depedigotheshellexecutigmoderish.Usigtheshelloptio-eor-oerrexitisaerror,becausemoderishdoesotsupportitadwouldbreak.

The--testoptiorustheregressiotestsuiteadexits.Thisverifiesthatthemoderishistallatioisfuctioigcorrectly.SeeAppedixBformoreiformatio.

The--versioad--helpoptiosoutputtherelativeiformatioadexit.

No-iteractiveusageexamplesCoutto10usigabasicloop:moderish--use=var/loop-c'LOOPfori=1to10;DOputl"$i";DONE'Ruaportable-formmoderishprogramusigzshadehaced-promptxtrace:zsh/usr/local/bi/moderish-oxtrace/path/to/program.shShellcapabilitydetectio

Moderishicludesabatteryofshellfeature,quirkadbugdetectiotests,eachofwhichisgiveaspecialcapabilityID.SeeAppedixAforalistofshellcapabilitiesthatmoderishcurretlydetects,aswellasfurthergeeraliformatioothecapabilitydetectioframework.

thisshellhasisthecetralfuctioofthecapabilitydetectioframework.Itotolytestsforthepreseceofshellfeatures/quirks/bugs,butcaalsodetectspecificshellbuilt-icommads,shellreservedwords,shelloptios(shortorlogform),adsigals.

Moderishitselfextesivelyusescapabilitydetectiotoadaptitselftotheshellit'sruigo.Thisishowitworksaroudshellbugsadtakesadvatageofefficietfeaturesotallshellshave.Butayscriptusigthelibrarycadothisithesameway,withthehelpofthisfuctio.

Testresultsarecachedimemory,sorepeatedchecksusigthisshellhasareefficietadthereisoeedtoavoidcalligittooptimiseperformace.

Usage:

thisshellhasitem...

IfitemcotaisolyASCIIcapitallettersA-Z,digits0-9or_,returtheresultstatusoftheassociatedmoderishcapabilitydetectiotest.IfitemisayotherASCIIword,checkifitisashellreservedwordorbuilt-icommadothecurretshell.Ifitemis--(ed-of-optiosdelimiter),disabletherecogitioofoperatorsstartigwith-forsubsequetitems.Ifitemstartswith--rw=or--kw=,checkiftheidetifierimmediatelyfollowigthesecharactersisashellreservedword(a.k.a.shellkeyword).Ifitemstartswith--bi=,similarlycheckforashellbuilt-icommad.Ifitemstartswith--sig=,checkiftheshellkowsaboutasigal(usablebykill,trap,etc.)bytheameorumberfollowigthe=.Ifaumber>128isgive,theremaiderofitsdivisioby128ischecked.Ifthesigalisfoud,itscaoicalisedsigalameisleftitheREPLYvariable,otherwiseREPLYisuset.(Ifmultiple--sig=itemsaregiveadallarefoud,REPLYcotaisolythelastoe.)Ifitemis-ofollowedbyaseparateword,checkifthisshellhasalog-formshelloptiobythatame.Ifitemisayotherletterordigitprecededbyasigle-,checkifthisshellhasashort-formshelloptiobythatcharacter.itemcaalsobeoeofthefollowigtwooperators.--cacherusallexteralmoderishshellcapabilityteststhathaveotyetbeeru,causigthecachetobecomplete.--showperformsa--cacheadtheoutputsalltheIDsofpositiveresults,oeperlie.

thisshellhascotiuestoprocessitemsutiloeofthemproducesaegativeresultorisfoudivalid,atwhichpoitayfurtheritemsareigored.Sothefuctioolyreturssuccessfullyifalltheitemsspecifiedwerefoudothecurretshell.(Tocheckifeitheroeitemoraotherispreset,useseparatethisshellhasivocatiosseparatedbythe||shelloperator.)

Exitstatus:0ifthisshellhasalltheitemsiquestio;1ifot;2ifaitemwasecouteredthatisotrecogisedasavalididetifier.

Note:Thetestsforthepreseceofreservedwords,built-icommads,shelloptios,adsigalsaredifferetfromcapabilitydetectiotestsiaimportatway:theyolycheckifaitembythatameexistsothisshell,addo'tverifythatitdoesthesamethigasoaothershell.

Namesadidetifiers

Allmoderishfuctiosrequireportablevariableadshellfuctioames,thatis,oescosistigofASCIIuppercaseadlowercaseletters,digits,adtheuderscorecharacter_,adthatdo'tbegiwithdigit.Forshelloptioames,thecostraitsarethesameexceptadash-isalsoaccepted.Aivalididetifierisgeerallytreatedasafatalerror.

Iteralamespace

Fuctio-localvariablesareotsupportedbythestadardPOSIXshell;olyglobalvariablesareprovidedfor.Moderisheedsawaytostoreitsiteralstatewithoutiterferigwiththeprogramusigit.Somostofthemoderishfuctioalityusesaiteralamespace_Msh_*forvariables,fuctiosadaliases.Alltheseamesmaychageataytimewithoutotice.Ayamesstartigwith_Msh_shouldbecosideredsacrosactadutouchable;moderishprogramsshouldeverdirectlyusethemiayway.Ofcoursethisisoteforceable,butamesstartigwith_Msh_shouldbeucommoeoughthatouitetioalcoflictislikelytooccur.

Moderishsystemcostats

Moderishprovidescertaicostats(read-olyvariables)tomakelifeeasier.Theseiclude:

$MSH_VERSION:Theversioofmoderish.$MSH_PREFIX:Istallatioprefixforthismoderishistallatio(e.g./usr/local).$MSH_MDL:Maimodulesdirectory.$MSH_AUX:Maihelperscriptsdirectory.$MSH_CONFIG:Pathtomoderishusercofiguratiodirectory.$ME:Pathtothecurretprogram.Replacemetfor$0.Thisisecessaryifthehashbagpath#!/usr/bi/evmoderishisused,oriftheprogramislauchedlikesh/path/to/bi/moderish/path/to/script.sh,astheseset$0tothepathtobi/moderishadotyourprogram'spath.$MSH_SHELL:Pathtothedefaultshellforthismoderishistallatio,choseatistalltime(e.g./bi/sh).Thisisashellthatiskowtohavepassedallthemoderishtestsforfatalbugs.Cross-platformscriptsshoulduseitisteadofhard-codig/bi/sh,becauseosomeoperatigsystems(NetBSD,OpeBSD,Solaris)/bi/shisotPOSIXcompliat.$SIGPIPESTATUS:TheexitstatusofacommadkilledbySIGPIPE(abrokepipe).Foristace,ifyouusegrepsomethigsomefile.txt|moreadyouquitmorebeforegrepisfiished,grepiskilledbySIGPIPEadexitswiththatparticularstatus.HardeedcommadsorfuctiosmayeedtohadlesuchaSIGPIPEexitspeciallytoavoidudulykilligtheprogram.Theexactvalueofthisexitstatusisshell-specific,somoderishrusaquicktesttodetermieitatiitialisatiotime.IfSIGPIPEwassettoigorebytheprocessthativokedthecurretshell,$SIGPIPESTATUSca'tbedetectedadissettothespecialvalue99999.SeealsothedescriptiooftheWRN_NOSIGPIPEIDforthisshellhas.$DEFPATH:ThedefaultsystempathguarateedtofidcompliatPOSIXutilities,asgivebygetcofPATH.$ERROR:Aguarateedusetvariablethatcabeusedtotriggeraerrorthatexitsthe(sub)shell,foristace::"${4+${ERROR:?excessargumets}}"(erroro4ormoreargumets)Cotrolcharacter,whitespaceadshell-safecharactercostats

POSIXdoesotprovideforthequotedC-styleescapecodescommolyusedibash,kshadzsh(suchas$'\'torepresetaewliecharacter),leavigthestadardshellwithoutacoveietwaytorefertocotrolcharacters.Moderishprovidescotrolcharactercostats(read-olyvariables)withhexadecimalsuffixes$CC01..$CC1Fad$CC7F,aswellas$CCe,$CCa,$CCb,$CCf,$CC,$CCr,$CCt,$CCv(correspodigwithpritfbackslashescapecodes).Thismakesiteasytoisertcotrolcharactersidouble-quotedstrigs.

Morecoveiececostats,hadyforuseibracketglobpattersforusewithcaseormoderishmatch:

$CONTROLCHARS:AllASCIIcotrolcharacters.$WHITESPACE:AllASCIIwhitespacecharacters.$ASCIIUPPER:TheASCIIuppercaselettersAtoZ.$ASCIILOWER:TheASCIIlowercaselettersatoz.$ASCIIALNUM:TheASCIIalphaumericcharacters0-9,A-Zada-z.$SHELLSAFECHARS:Safe-listforshell-quotig.$ASCIICHARS:ThecompletesetofASCIIcharacters(miusNUL).

Usageexamples:

#Useaglobpattertocheckagaistcotrolcharactersiastrig:ifstrmatch"$var""*[$CONTROLCHARS]*";theputl"\$varcotaisatleastoecotrolcharacter"fi#Use'!'(ot'^')tocheckforcharacters*ot*partofaparticularset:ifstrmatch"$var""*[!$ASCIICHARS]*";theputl"\$varcotaisatleastoeo-ASCIIcharacter";;fi#Safelysplitfieldsataywhitespace,commaorslash(requiressafemode):usesafeLOOPfor--split=$WHITESPACE,/fieldi$my_items;DOputl"Item:$field"DONEReliableemergecyhalt

Thediefuctioreliablyhaltsprogramexecutio,evefromwithisubshells,optioallypritigaerrormessage.Notethatdieismeatforaemergecyprogramhaltoly,i.e.isituatioswerecotiuigwouldmeatheprogramisiaicosistetorudefiedstate.Shellscriptsruigiaicosistetorudefiedstatemaywreakallsortsofhavoc.Theyarealsootoriouslydifficulttotermiatecorrectly,especiallyifthefatalerroroccurswithiasubshell:exitwo'tworkthe.That'swhydieisoptimisedforkilligalltheprogram'sprocesses(icludigsubshellsadexteralcommadslauchedbyit)asquicklyaspossible.Itshouldeverbeusedforexitigtheprogramormally.

Oiteractiveshells,diebehavesdifferetly.Itdoesotkillorexityourshell;istead,itissuesSIGINTtotheshelltoaborttheexecutioofyourruigcommad(s),whichisequivalettopressigCtrl+C.Iadditio,ifdieisivokedfromasubshellsuchasabackgroudjob,itkillsallprocessesbelogigtothatjob,butleavesotherruigjobsaloe.

Usage:die[message]

Ifthetrapstackmoduleisactive,aspecialDIEpseudosigalcabetrapped(usigplaioldtraporpushtrap)toperformemergecycleaupcommadsupoivokigdie.

IftheMSH_HAVE_MERCYvariableissetiascriptaddieisivokedfromasubshell,thediewillolytermiatethecurretsubshelladitssubprocessesadwillotexecuteDIEtraps,allowigthescripttoresumeexecutioitheparetprocess.Thisisforuseispecialcases,suchasregressiotests,adisstroglydiscouragedforgeeraluse.Moderishusetsthevariableoiitsoitcaotbeiheritedfromtheeviromet.

Low-levelshellutilitiesOutputtigstrigs

ThePOSIXshelllacksasimple,straightforwardadportablewaytooutputarbitrarystrigsoftext,somoderishaddstwocommadsforthis.

putpritseachargumetseparatedbyaspace,withoutatrailigewlie.putlpritseachargumet,termiatigeachwithaewliecharacter.

Thereisoprocessigofoptiosorescapecodes.(Moderishcostats$CC,etc.cabeusedtoisertcotrolcharactersidouble-quotedstrigs.Toprocessescapecodes,usepritfistead.)

Theechocommadisotoriouslyuportableadkidofbroke,soisdeprecatedifavourofputadputl.Moderishdoesprovideitsowversioofecho,butitisolyactivatedforportable-form)scripts.Otherwise,theshell-specificversioofechoisleftitact.Themoderishversioofechodoesotiterpretayescapecodesadsupportsolyoeoptio,-,which,likeBSDecho,suppressesthefialewlie.However,ulikeBSDecho,if-istheolyargumet,itisotiterpretedasaoptioadthestrig-ispritedistead.Thismakesitsafetooutputarbitrarydatausigthisversioofechoaslogasitisgiveasasigleargumet(usigquotigifeeded).

Legibilityaliases:ot,so,forever

Moderishsetsthreealiasesthatcahelptomaketheshelllaguagelookslightlyfriedlier.Theiruseisoptioal.

otisaewsyoymfor!.Theycabeusediterchageably.

soisacommadthattestsifthepreviouscommadexitedwithastatusofzero,soyoucatesttheprecedigcommad'ssuccesswithifsoorifotso.

foreverisaewsyoymforwhile:;.Thisallowssimpleifiiteloopsoftheform:foreverdostuff;doe.

Ehacedexit

Theexitcommadcabeusedasormal,buthasgaiedcapabilities.

Extededusage:exit[-u][status[message]]

Asperstadard,ifstatusisotspecified,itdefaultstotheexitstatusofthecommadexecutedimmediatelypriortoexit.Otherwise,itisevaluatedasashellarithmeticexpressio.Ifitisivalidassuch,theshellexitsimmediatelywithaarithmeticerror.Ayremaiigargumetsafterstatusarecombied,separatedbyspaces,adtakeasamessagetopritoexit.Themessageshowisprecededbytheameofthecurretprogram($MEmiusdirectories).Notethatitisotpossibletoskipstatuswhilespecifyigamessage.Ifthe-uoptioisgive,adtheshellfuctioshowusageisdefied,thatfuctioisruiasubshellbeforeexitig.Itisitededtopritamessageshowighowthecommadshouldbeivoked.The-uoptiohasoeffectifthescripthasotdefiedashowusagefuctio.Ifstatusiso-zero,themessageadtheoutputoftheshowusagefuctioareredirectedtostadarderror.chdir

chdirisarobustcdreplacemetforuseiscripts.

Thestadardcdcommadisdesigedforiteractiveshellsadappropriatetousethere.However,forscripts,itsfeaturescreateseriouspitfalls:

The$CDPATHvariableissearched.Ascriptmayiheritauser'sexported$CDPATH,socdmaychagetoauitededdirectory.cdcaotbeusedwitharbitrarydirectoryames(suchasutrusteduseriput),assomeoperadshavespecialmeaigs,eveafter--.POSIXspecifiesthat-chagesdirectoryto$OLDPWD.Ozsh(eveishmodeozsh<=5.7.1),umericoperadssuchas+12or-345represetdirectorystacketries.Allsuchpathseedescapigbyprefixig./.Symbolicliksidirectorypathcompoetsareotresolvedbydefault,leavigapotetialsymlikattackvector.

Thus,robustadportableuseofcdiscriptsisureasoablydifficult.Themoderishchdirfuctiocallscdiawaythattakescareofalltheseissuesautomatically:itdisables$CDPATHadspecialoperadmeaigs,adresolvessymbolicliksbydefault.

Usage:chdir[-f][-L][-P][--]directorypath

Normally,failuretochagethepresetworkigdirectorytodirectorypathisafatalerrorthatedstheprogram.Totoleratefailure,addthe-foptio;ithatcase,exitstatus0sigifiessuccessadexitstatus1sigifiesfailure,adscriptsshouldalwayscheckadhadleexceptios.

Theoptios-L(logical:do'tresolvesymliks)ad-P(physical:resolvesymliks)arethesameasicd,exceptthat-Pisthedefault.NotethatoashellwithBUG_CDNOLOGIC(NetBSDsh),the-Loptiotochdirdoesothig.

Tousearbitrarydirectoryames(e.g.directoryamesiputbytheuserorotherutrustediput)alwaysusethe--separatorthatsigalstheedofoptios,orpathsstartigwith-maybemisiterpretedasoptios.

isubshell

Theisubshellfuctiochecksifyou'recurretlyruigiasubshelleviromet(usuallycalledsimplysubshell).

Asubshellisacopyoftheparetshellthatstartsoutasaexactduplicate(icludigo-exportedvariables,fuctios,etc.),exceptfortraps.Aewsubshellisivokedbycostructslike(paretheses),$(commadsubstitutios),pipe|lies,ad&(tolauchabackgroudsubshell).Upoexitigasubshell,allchagestoitsstatearelost.

Thisisottobecofusedwithaewlyiitialisedshellthatismerelyachildprocessofthecurretshell,whichissometimes(cofusiglyadwrogly)calleda"subshell"aswell.Thisdocumetatioavoidssuchamisleadiguseoftheterm.

Usage:isubshell[-p|-u]

Thisfuctioreturssuccess(0)ifitwascalledfromwithiasubshellado-success(1)ifot.Oeoftwooptioscabegive:

-p:StoretheprocessID(PID)ofthecurretsubshellormaishelliREPLY.-u:StoreaidetifieriREPLYthatisusefulfordetermiigifyou'veeteredasubshellrelativetoapreviouslystoredidetifier.Thecotetadformatareuspecifiedadshell-depedet.isset

issetchecksifavariable,shellfuctiooroptioisset,orhascertaiattributes.Usage:

issetvarame:Checkifavariableisset.isset-vvarame:Id.isset-xvarame:Checkifvariableisexported.isset-rvarame:Checkifvariableisread-oly.isset-ffucame:Checkifashellfuctioisset.isset-optioletter(e.g.isset-C):Checkifshelloptioisset.isset-ooptioame:Checkifshelloptioissetbylogame.

Exitstatus:0iftheitemisset;1ifot;2iftheargumetisotrecogisedasavalididetifier.Ulikemostothermoderishcommads,issetdoesottreataivalididetifierasafatalerror.

Whecheckigashelloptio,aoexistetshelloptioisotaerror,butretursthesameresultasausetshelloptio.(Tocheckifashelloptioexists,usethisshellhas.

Note:justisset-fchecksifshelloptio-f(a.k.a.-ooglob)isset,butwithaextraargumet,itchecksifashellfuctioisset.Similarly,isset-xchecksifshelloptio-x(a.k.a-oxtrace)isset,butisset-xvaramechecksifavariableisexported.Ifyouuseuquotedvariableexpasioshere,makesurethey'reotempty,ortheshell'semptyremovalmechaismwillcausethewrogthigtobechecked(eveithesafemode).

setstatus

setstatusmauallysetstheexitstatus$?tothedesiredvalue.Thefuctioexitswiththestatusidicated.Thisisusefulicoditioalcostructsifyouwattoprepareaparticularexitstatusforasubsequetexitorreturcommadtoiheritudercertaicircumstaces.Thestatusargumetisaparsedasashellarithmeticexpressio.Aegativevalueistreatedasafatalerror.Thebehaviourofvaluesgreatertha255isotstadardisedaddepedsoyourparticularshell.

Testigumbers,strigsadfiles

Thetest/[commadisthebaeofcasualshellscripters.Eveadvacedshellprogrammersarefrequetlycaughtuawarebyoeofthemaypitfallsofitsarcae,hackishsytax.Itattemptstolooklikeshellgrammarwithoutbeigshellgrammar,causigmyriadproblems(1,2).Its-a,-o,(ad)operatorsareiheretlyadfatallybrokeasthereisowaytoreliablydistiguishoperatorsfromoperads,soPOSIXdeprecatestheiruse;however,mostmaualpagesdooticludethisessetialiformatio,adevethefewthatdowillottellyouwhattodoistead.

Ksh,zshadbashoffera[[alterativethatfixesmayoftheseproblems,asitisitegrateditotheshellgrammar.Nevertheless,iticreasescofusio,asetirelydifferetgrammaradquotigrulesapplywithi[[...]]thaoutsideit,yetmayscriptsedupusigthemiterchageably.ItisalsootavailableoallPOSIXshells.(Tomakemattersworse,Busyboxashhasafalse-fried[[thatisjustaaliasof[,withoeoftheshellgrammaritegratio!)

Fially,thePOSIXtest/[commadisicompatiblewiththemoderish"safemode"whichaimstoelimiatemostoftheeedtoquotevariables.Seeusesafeformoreiformatio.

Moderishdeprecatestest/[ad[[completely.Istead,itoffersacomprehesivealterativecommaddesigthatworkswiththeusualshellgrammariasaferwaywhileofferigvariousfeatureehacemets.Thefollowigreplacemetsareavailable:

功能介绍

Releases For code examples, see EXAMPLES.md and share/doc/modernish/examples modernish – harness ...

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论